Mocking Network Layer in Swift— Part 3

by mocking URLProtocol

Please check the previous articles on Network Layer Part 1 and Part 2.

What is Mocking?

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. (wiki)

In our case, we have to mimic URLSession so that it will return the mock object without hitting the physical server. We can achieve this by creating MockURLProtocol that confirms to URLProtocol and implementing its required methods. Now our MockURLProtocol is capable of handling the specified request.

MockURLProtocol

Now we have to add our MockURLProtocol to the URLSessionConfiguration.protocolClasses array to handle requests in a session.

Custom URLSessionConfiguration

Mocking in Action:

For example, to mock loginUser function, we have to prepare a fake response object that what we expect on a real server call. This response object will be returned as a response from requestHandler of the MockURLProtocol.

Actual implementation for reference
Fake Response Object

the final mockLoginUser function looks like this.

Mock loginUser function

Please check the APIMockingTests.swift file in the sample code.

Also, check updates in APIHandler.swift file, as updated code using Builder Pattern and refactored BaseRequest, AuthRequest with RequestBuilder.

Run the tests again, as we observed after refactoring the code also all the tests passed without changing the test cases. So the advantages of testing is that we can give guarantee that all cases are handled even after refactoring.

You can find the complete source code below:

This is based on WWDC 2018: “Testing Tips & Tricks”

link: https://developer.apple.com/videos/play/wwdc2018/417/

--

--