5

I'd like to write unit tests for methods that use the shared NSURLSession, and in particular, NSURLSessionDataTask to download data. Basically, I would like the target methods to receive mock responses/data without requiring an internet connection.

What is the less unobtrusive way of mocking these components? I was thinking of populating NSURLCache with mock responses and data but I feel this assumes too much of how NSURLSession and NSURLSessionDataTask work. Any other suggestions?

hpique
  • 119,096
  • 131
  • 338
  • 476

1 Answers1

5

I've used OHHTTPStubs to mock responses lately.

You just register the stub before you test (example from the README):

[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
    return [request.URL.host isEqualToString:@"mywebservice.com"];
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
    // Stub it with our "wsresponse.json" stub file
    return [OHHTTPStubsResponse responseWithFileAtPath:OHPathForFileInBundle(@"wsresponse.json",nil)
        statusCode:200 headers:@{@"Content-Type":@"text/json"}];
}];

Internally, it uses NSURLProtocol to intercept the requests and stub them.

Marcelo
  • 9,916
  • 3
  • 43
  • 52