The idea behind
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:
- Create a fake class object with one-line code
- Let a class method return a specific value/object
- Test whether a specific method is called
- Test a static method
The post includes three examples of how to use the
1. Test class methods
Suppose we have one class named
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.