Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit tests with NSURLSession

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?

like image 718
hpique Avatar asked Mar 09 '14 18:03

hpique


1 Answers

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.

like image 129
Marcelo Fabri Avatar answered Oct 14 '22 00:10

Marcelo Fabri