Network Unit Testing

Here’s a good read on a strategy for writing useful unit tests for network access code, specifically that AFNetworking library:

Using NSURLProtocol for Injecting Test Data

… I didn’t find any easy way to mock the interface to AFJSONRequestOperation in order to intercept the network access. So an alternative solution is to intercept the standard http protocol built into iOS. This is done by registering our own custom NSURLProtocol subclass capable of handling http requests: ILCannedURLProtocol. Since each registered protocol handler is asked in reverse order of registration our class will always be consulted before the standard classes.

The primary goal of ILCannedURLProtocol is to respond with a pre-loaded set of test data every time a http request is made. This way we’ll be able to remove any outside influences when running the tests. We’ll also be able to have the http request fail when we want it to fail…

Definitely worth a read, and check out an example with ILBitly on github, an Objective-C wrapper for shortening services. Which is useful on its own if your app has a need for stuff, no doubt.

There’s a bunch of other interesting-looking posts on unit testing stuff on the blog there too:

Using Mock Objects to Stabilize Unit Tests

Unit Testing Asynchronous Network Access

Testing Location Based iPhone Apps

Covering it all up


bcharp / BOURLProtocol – “…  mocking of network call. It is made with the idea of working with AFNetworking.”

Alex | October 13, 2011

Leave a Reply