April 20, 2017
Xcode unit tests are captured inside an XCTestCase subclass. XCTestCase is a concrete subclass of XCTest (abstract base class for testing), that needs to be overridden for defining any custom tests.
By norm, each XCTestCase subclass encapsulates multiple test methods with optional setup and teardown before and after tests are run.
To write your own test cases, all you need to do is follow the below steps:
Test methods are instance methods that have no parameters, do not return a value, and whose name begins with the lowercase word “test”. To test the functionality of our method we could follow a certain pattern defined by the following:
For e.g. let’s say, we have got a class called MyClass with an initialization method called initWithDictionary. This method takes a dictionary parameter and assigns to its properties.
In order to test the same, we are going to follow the below.
Here, an assertion is to determine whether the test case is passed or failed. We could see that we happen to cover the positive case for the method. Now let’s try to cover the negative one as well.
Also for code coverage of a method, we ideally should cover all the cases possible to test the methods. Like we could write one more negative case for the same but this time by passing a valid but an empty dictionary.
WHY MOCKING ??
Till now what we have covered involves the classes and methods written by us. But in real time projects, there would be a lot of third party frameworks integrated inside our application. How do you test now?
For e.g. let say, we have a method in our class which makes a call to a third party api.
In order to test the above functionality, we need to stub the third party api using the OCMock framework and call in a way that whatever we want from the api could be seen and tested for all the use cases. Below is the code to test the positive case.
Negative code coverage for the same is depicted below:
In regular programming, we often work on blocks and that is something tricky when it comes to writing unit test cases for the same. So here is an example which would help us write unit tests seamlessly.
Let say we have a class called Util which has got two functions with block parameter.
And we have a place in myMethod, where we have utilized the Util method.
Now in order to test the method, myMethod, we first need to mock the Util dispatch methods. Only then we would be able to write proper unit test cases accordingly.
To learn more on OCMock, please refer to OCMock website – Front Page · OCMock.