chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

iOS Unit Test Practise with OCMock 2/3


The idea behind Mock:

Using a fake object to simulate target object, a method returned value/object. For example, there might be an amount of classes including models, viewControllers and etc. With regular unit tests, we need to instantiate the objects that we are going to tests. If the object have more than 5 properties, writing tests will become a disaster. That might the reason why developers don't want to write the tests.

However with mock, there are some ways to make the work not that painful. :). OCMock can do the following things:

  1. Create a fake class object with one-line code
  2. Let a class method return a specific value/object
  3. Test whether a specific method is called
  4. Test a static method

The post includes three examples of how to use the OCMock:

1. Test class methods

Suppose we have one class named Todo:


Testing cases:


We are using a OCMPartialMock to mock an object of Todo, and in the stub method, 4 is expected to return.

2. Test an expecting method is called

Suppose we want to know whether our method printTodo: get called or not. we can use OCMock expect. The following code is using OCMock 2:


The trick is on expect, if the printTodo: is called, then test case success. Otherwise it will raise an exception and test failed. To catch such exception, verify must be used.

3. Test an expecting method is called

In the original Todo class, isPending returns a YES, here, we assign a NO instead. The above test case is not ideal for testing, as it will always pass, as we assign a NO to isPending and test with NO == NO.