iOS apps interact a lot with the network. They read or write state to or from the server, and fetch data, images, audios, and videos from remote. To protect and verify the network layer, we write unit tests around it. Sadly, if we write tests that rely on networking, they will be slow and unstable. And to be fair, they are not really unit tests but more integration tests.

How can you stub the network request and response and isolate the unit test’s code from networking without installing any third-party libraries? Registering your own instance of URLProtocol at the URLSession configuration is the key:

urlSessionConfiguration.protocolClasses = [StubURLProtocol.self]

The following explains the code in detail.

road sign warning of curves ahead on a mountain road

Photo by NOAA on Unsplash

1. The Core Flow of the URL Loading System

diagram of default flow of URLSession

URLSession Default Flow by Eric Yang

URLSession

URLSession plays the core role of the iOS URL Loading System. The instance of URLSession creates one or more instances of URLSessionTask, which can be the instances of its subclasses:

  • URLSessionDataTask: Fetch and return data to your app
  • URLsessionUploadTask: Upload data and files to the remote
  • URLSessionDownloadTask: Download data and files from the remote
  • URLSessionStreamTask: Read and write from and to the remote by using an enqueued and executed serially TCP/IP connection
  • URLSessionWebSocketTask: Read and write asynchronously from and to the remote by using TCP and TLS in the form of WebSocket framing.

#swift #programming #xcode #ios #mobile

Stubbing HTTP Response by Using Apple-Authorised Man-in-the-Middle Attack
2.25 GEEK