Infinite Loop
September 2011

Using NSURLProtocol for Injecting Test Data

In earlier posts I described methods for unit testing asynchronous network access and how to use mock objects for further control of the scope of these unit tests. In this tutorial I’ll present an alternative way of providing reliable test data by customizing the NSURLProtocol class in order to deliver static test data.

A few months ago Gowalla made the networking code used in their iPhone client available as open source on GitHub. The AFNetworking library as it is called is a “A delightful iOS networking library with NSOperations and block-based callbacks“. One of the things that first caught my eye was the built-in support for accessing JSON based services with just a few lines of code.

The simplicity of the AFNetworking interface inspired me to give it a test spin and write ILBitly which provides an Objective C based wrapper for the Bitly url shortening service. It’s very easy to use AFNetworking and especially the JSON support that is accessed using a single class methods. Unfortunately this simplicity also makes it quite difficult to write self-contained unit and mock tests using OCMock. This is mainly because OCMock doesn’t support mocking of class methods. My attempts with other techniques such as method swizzling wasn’t successful either.

It wasn’t until a few days ago when I noticed a discussion on GitHub about how to properly mock the interface to AFNetworking. In the discussion Adam Ernst suggested to use a customized NSURLProtocol for doing the task. That finally gave me the missing clue on how to solve the testing problem.
(more…)

Comments (7) | Trackback