使用NSURLSession进行单元测试

编程入门 行业动态 更新时间:2024-10-23 18:29:12
本文介绍了使用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?

推荐答案

我用 OHHTTPStubs 最近模拟回复。

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"]; } 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进行单元测试

本文发布于:2023-06-13 09:35:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/679009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   NSURLSession

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!