Skip to Content
Technical Articles
Author's profile photo Marco Eidinger

Write unit tests for your network requests in your iOS apps

Recently I got the question if it is possible to write unit tests for network requests performed with SAPURLSession from the SAPFoundation framework. Yes, it is 🙂

You cannot access the underlying URLSession but you can inject your own URLSessionConfiguration and therefore you can make use of a technique called Mock URLProtocol.

This technique was presented in Apple’s WWDC 2018 session “Testing Tips & Tricks“. I strongly encourage you to watch it.

High-level summary:

  • In your test bundle create your custom URLSessionConfiguration
  • In your test classes create and register classes which conform to URLProtocol . Those classes will be called instead of sending actual HTTP requests. In your class you can then return data or errors as you please.
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [MockURLProtocol.self]
let urlSession = SAPURLSession(configuration: configuration)
urlSession.dataTask(with: urlRequest) { data, response, error in
   // ... handle your response


Slide from WWDC 2018 session


Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.