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 [EDIT: Disappeared.]

… 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.



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

Alex | October 13, 2011

Leave a Reply