Unit tests with NSURLSession

2019-04-09 00:26发布

问题:

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?

回答1:

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.