In order to have qualified code, writing Unit Test is an important skill that every developer needs to know. Here are some tips for writing it easier.
1. Using Dependency Injection and Protocols:
Let’s see how can we write Unit Test for class User here.
There are 2 cases need to be tested:
But how can we control the output of DataProvider().getListUsers?
That is time for you to use Dependency Injection and Protocols to control the output.
We can refactor the code above a little bit.
See? Now in Test Target, we can use another mock DataProvider class to control the outputs.
It’s very easy and clean.
You should be aware of this pattern from the beginning, then you don’t need to refactor your code just to write Unit Test.
2. Mock system/framework functions:
In a real application, we always need to use functions from system or framework. Because they are all not able to be modified, we need another solution to mock it.
See this example, we need to test whether the device is an iPad.
Because that value will be returned from Apple framework, so you cannot directly modify it.
How to control output of UIDevice.current.userInterfaceIdiom?
We will use a protocol that has the same function as the framework.
Because in the framework, UIDevice already defined the function in the protocol, so we don’t need to write anything when conforming to the protocol.
You can get the exact function by entering Apple framework. (Copy function name except
open access control.
Now you just need to use Dependency Injection. Done ╰ (▔∀▔) ╯