Mocking network requests with OHHTTPStubs.

Oct 2, 2012 15:47 · 150 words · 1 minute read

This is an outboard brain post, so I remember how to wire up a mocked-out test involving AFNetworking:

#import "Kiwi.h"
#import "AFNetworking.h"
#import "OHHTTPStubs.h"
#import "OHHTTPStubsResponse.h"

SPEC_BEGIN(NetworkTest)

describe(@"The call to the external service", ^{

    beforeEach(^{
        [OHHTTPStubs addRequestHandler:^OHHTTPStubsResponse*(NSURLRequest *request, BOOL onlyCheck){
            return [OHHTTPStubsResponse responseWithFile:@"test.json" contentType:@"text/json" responseTime:1.0];
         }];
    });

    it(@"should return an IP address", ^{

        __block NSString *origin;

        NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/ip"]];

        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            origin = [JSON valueForKeyPath:@"origin"];
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            // no action
        }];

        [operation start];

        [[expectFutureValue(origin) shouldEventuallyBeforeTimingOutAfter(3.0)] equal:@"111.222.333.444"];

    });

});

SPEC_END

The prerequisites are:

A simple summary is that OHHTTPStubs intercepts any HTTP requests, and then sends back a canned response.  That response is parsed in AFJSONRequestOperation’s success block, and the resulting value is tested with Kiwi’s asynchronous shouldEventuallyBe: test.