Networking Layer Unit and Integration Testing Techniques using Swift

UNIT TESTING : is a level of software testing where individual units components of a software are tested. The purpose is to validate that each unit of the software performs as designed.

INTEGRATION TESTING : is a level of software testing where individual units are combined and tested as a group. The purpose of this level of testing is to expose faults in the interaction between integrated units.

Testing network requests

Figure 1
Figure 2
Figure 3

Unit Test Request Creation And Parsing

Figure 4

Integration Testing Network Call

Figure 5
Figure 6
Figure 7
Figure 8

URLSessionDataTask Integration Testing

Figure 9

Mocking Using URLProtocol

URLSession provides a high level API for apps to use to perform network requests. Objects like URLSession data tests that represent an inflight request. Behind the scenes though, there’s another lower-level API URLProtocol which performs the underlying work of opening network connection, writing the request, and reading back a response. URLProtocol is designed to be subclassed giving an extensibility point for the URL loading system.

Foundation provides built-in protocols subclasses for common protocols like HTTPS.But we can override these in our tests by providing a mock protocol that lets us make assertions about requests that are coming out and provide mock responses.

URLProtocol communicates progress back to the system via the URLProtocolClient protocol.

Figure 10

Testing Configuration

Figure 11
Figure 12

URLSessionDataTask Partial Mocking

Partial mocking, you are modifying an existing type to only partially behave differently in a test

Figure 13
Figure 14

When you see mock subclasses with overridden method. You are doing Partial mocking
Partial Mocking = Subclasses + Overridden method

Issues with partial Mocking

URLSessionDataTask Complete Mocking

Complete mocking : you are replacing the entire implementation

Figure 15
Figure 16
Figure 17
Figure 18
Figure 19


Useful Links