Hi,
In this article, I share a neat method to unit test networking code in Swift; where we’ll implement mocking of URLSession network requests without having to build loads of mock classes for each API.
While unit testing networking code, it is a standard industry best-practice to mock the network request and not actually communicate with the server.
There are many reasons for this, some of which are listed below-
Note: this article and implementation is meant for URLSession in Swift only.
We’ll be using Combine dataTaskPublisher for URLSession in this article. However, we can also use the standard URLSession.dataTask instead. The concept remains the same.
Let’s get started!
Let’s say we are using a backend REST API to load the profile of the user.
Our class that networks with this backend API using URLSession may look something like this —
We have defined a method ‘getProfile()’ in our class which networks with the backend API and returns the user. For this simple example, we simply print the name of the user received (line 19).
We can use this class to get the user simply like this —
Code
let profileAPI = ProfileAPI()
profileAPI.getProfile()
Sample Output
Yugantar
Our ProfileAPI class isn’t testable and ready for mocking yet.
To be able to mock it, we’ll have to make some changes in it after which the final class may look something like this —
#networking #ios-app-development #swift #unit-testing #programming