Stub network calls in Unit-Tests

Make sure you know your responses

A few years ago I was asked to support a different branch of my company. Their iOS developer left on short notice and the app he was working on was nearly finished. I went there to fix about 10 bugs… it ended with more than 50 issues, but we all know, this is normal during development. Especially when you have an amazing designer who is very picky about margins.

Anyways.. I got there and wanted to test some network code. Eager and young as I was (just started using Kiwi about a year earlier) I thought, I could just stub those methods and be on my way. A colleague of mine wasn't very fond of the idea. She suggested to use the currently existing dependencies and not introduce a new one (we were using XCTest during that time and not Kiwi).

So what was her solution? She was already using KIF and running UI tests against a backend is no fun. Instead OHHTTPStubs was used. With this library you are able to intercept network requests and return whatever you want. My guess is, it's using Method Swizzling on NSURL to intercept, but why do it yourself, if there is a library.

How to use

Writing an interceptor is quite easy. Just specify the host and path you want to intercept and return your response. I tend to create an extension with class methods on OHHTTPStubs which contain my interceptors.

Response is your JSON object. Depending on what you want to return, you can use the provided initializers by the library. I'm also creating a matcher for easier checking if I'm calling the correct url. OHHTTPStubs provides some, but sometimes you'll have to write your own. This is done by creating a OHHTTPStubsTestBlock. It is a closure in which will be passed a RequestObject and return a Bool.

To setup our suite, as always we can use beforeEach or beforeSuite. Just don't forget to clean up afterwards! So don't forget:

OHHTTPStubs.removeAllStubs()

Conclusion

I love this library. It is all you'll ever need for your Unit-Tests. A few months ago I introduced it to my team and ever since then our network tests run against OHHTTPStubs.

Using OHHTTPStubs enables us to test our entire app without having to introduce any testing code into our production system. This way, we can be sure, as long as the backend api doesn't change, our app will behave the way we expect it to.

Next: TDD is backwards

Previous: Testing Apples MVC