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.

Purpose of Mocking Network Requests

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-

  • Unit Tests are supposed to be fast and reliable. Actually communicating with the server won’t only make the unit tests extremely slow, but also unreliable due to dependence on the internet connection.
  • **Actually communicating with the server would disrupt the backend. **Example: Let’s say you are unit testing networking code to delete a user. Making an actual call to the server would lead to actual deletion of the user, we don’t want that :P

Implementation

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!

1. REST API Networking Class (starting point)

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

2. Make REST API Networking Class Testable

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

Unit Test Networking Code in Swift, Without Making Loads of Mock Classes
9.30 GEEK