使用NSURLSession进行单元测试

使用NSURLSession进行单元测试

本文介绍了使用NSURLSession进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为使用共享 NSURLSession 的方法编写单元测试,特别是 NSURLSessionDataTask 下载数据。基本上,我希望目标方法在不需要互联网连接的情况下接收模拟响应/数据。

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.

模拟这些组件的不那么不引人注目的方法是什么?我想用模拟响应和数据填充 NSURLCache ,但我觉得这假设过多的 NSURLSession NSURLSessionDataTask 工作。还有其他任何建议吗?

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?

推荐答案

我用最近模拟回复。

I've used OHHTTPStubs to mock responses lately.

您只需在测试前注册存根(例如来自README):

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"}];
}];

在内部,它使用 NSURLProtocol 拦截请求和存根。

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

这篇关于使用NSURLSession进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 23:12