Testable Network Layer in Swift – Part 2

https://cdn-images-1.medium.com/max/1000/1*b6A7a-RMrW8gdV8OGuCyLg.png

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.

testMakeRequest

Testing API Response:

The response might be a success or an error returned from server.

For LoginAPI, below is the success response test case.

Testing API Response

Testing success response parsing.

We can test server errors, such as status 203, 400 etc., which will return ServiceError object.

Testing API Response

Testing 203 response.

 

Testing API Response - 400 Error

Testing 400 error response.

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.

Testing API Response

You can find the source code below: (UserServicesTests.swift)

appitventures/IOS-Blog
To share files related to blogs which can be made public — appitventures/IOS-Bloggithub.com

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.

In the coming article, we will learn how to Mock a Network Layer.

If you like this article, give some claps and follow me on Medium.

Download Your Free Mobile App Development eBook

App-Development

Subscribe to our newsletter!