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.
URLSession Default Flow by Eric Yang
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 appURLsessionUploadTask
: Upload data and files to the remoteURLSessionDownloadTask
: Download data and files from the remoteURLSessionStreamTask
: Read and write from and to the remote by using an enqueued and executed serially TCP/IP connectionURLSessionWebSocketTask
: 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