Unit tests with NSURLSession
Asked Answered
P

1

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?

Poliard answered 9/3, 2014 at 18:20 Comment(0)
H
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.

Hosier answered 9/3, 2014 at 18:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.