Writing unit test cases using XCTest framework.
In the previous article in this series, we learned how to write a Testable Network layer.
In this article, we will learn how to write unit tests for that network layer. To perform unit tests, we need to know the expected output for the given inputs.
Remember, we never actually hit the physical server to run tests, so we cannot test all possible cases.
For each APIHandler, we have two methods to perform tests, as mentioned in Part 1.
func makeRequest(from parameters: [String: Any]) -> Request
func parseResponse(data: Data) throws -> LoginResponse
Testing API Request:
For LoginAPI, we can confirm that a request is prepared correctly by checking all the request parameters, like http method, http body, url, header fields, etc.
Testing API Response:
The response might be a success or an error returned from server.
For LoginAPI, below is the success response test case.
[caption id="attachment_12469" align="alignnone" width="994"]
Testing success response parsing.[/caption]
We can test server errors, such as status 203, 400 etc., which will return ServiceError object.
[caption id="attachment_12470" align="alignnone" width="974"]
Testing 203 response.[/caption]
[caption id="attachment_12471" align="alignnone" width="963"]
Testing 400 error response.[/caption]
Using Json files to test the API response:
For large API responses, it’s a good idea to create json files with the expected response. You can access the data from json files as shown below.
You can find the source code below: (UserServicesTests.swift)
Writing test cases will take time initially, but once developers get used to it, it will make their lives easier in later stages. We, as developers, tend to integrate the API’s and then do the testing to check for response and UI updates. If there is any issue with API response, this process is repeated. Test cases come in handy as a means of avoiding this repetitive testing.
For example, to test a newly created API in fifth screen in navigation stack, it takes time to run the application, navigate to the respective screen and do a manual test to see if everything is working correctly. If something goes wrong, we have to repeat that process several times. Instead, if we have written a test case for the API, we can directly run that test case instead of executing the whole appm. Writing unit tests will take more time at the beginning, but it will save time later during testing or debugging.
Additionally, using test cases allows us to cover error cases like server errors, which are not possible to produce in manual testing.