If you follow this blog for some time you might have realized that one
of my favorite testing problems is the stubbing of NSURLSession.
In case you are not familiar with the terms, stubbing means to fake the
answer of a method. In the case of NSURLSession this means that we fake
the web API response. This has several advantages. For example:
We don’t need a working web API to developer the network requests of
The response is instantaneous. This results in a faster
The tests can run on a computer that has no internet connection.
Normally the stubbing of NSURLSession requests is done using
NSURLProtocol. Libs doing that are for example
Mockingjay. The advantage of
using NSURLProtocol is, that the stubbing also works when using libs as
Alamofire for the network
requests. This works great but for me this is to much code. I would have
to study and understand that code to get the desired confidence im my
An easy solution
I use NSURLSession for my network requests. Here is how I stub my
To make it easier, I have written a mock class for NSURLSession and a
protocol. All that together looks like this:
So, the complete helper code I need to write my stubs is 47 lines of
code. And all that code is easy to understand. No swizzling, not
complicated methods. Nice!
To be able to use the NSURLSession mock in the test, we need a way to
inject the dependency into the code. One possibility is the usage of a
Then an example test would look like this:
I really like this approach because I can understand the mocking within
a few minutes by scanning over 50 lines of code. There is no
NSURLProtocol and not swizzling involved.
The NSURLSession mock is on
github and it’s also
available via CocoaPods.