在 iOS 单元测试中模拟 NSHTTPURLRequest 和 NSHTTPURLResponse [英] Mock NSHTTPURLRequest and NSHTTPURLResponse in iOS unit test

查看:19
本文介绍了在 iOS 单元测试中模拟 NSHTTPURLRequest 和 NSHTTPURLResponse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 iOS 中开发一个框架,它对服务器进行 HTTP 调用.我想编写单元测试来测试 API.我想模拟服务器调用,而不实际进行真正的服务器调用.任何人都可以帮助我提供示例进行模拟服务器调用的单元测试.我们如何设置期望并返回手动构建的 url 响应.?我使用 XCTest 框架进行单元测试,使用 OCMock 进行模拟对象.

I'm developing a framework in iOS which makes HTTP calls to server.I wanted to write unit test to test the API's.I wanted to mock the server calls,without actually making real server call.Can anyone help me with sample unit test which makes mocked server calls.How to do we set expectations and return the hand constructed url response.?I'm using XCTest framework for unit test and OCMock for mocking objects.

推荐答案

使用 OHTTPStubs,https://github.com/AliSoftware/OHHTTPStubs.

Use OHTTPStubs, https://github.com/AliSoftware/OHHTTPStubs.

这是模拟对特定 GET 请求的响应并返回 JSON 数据的实际示例.

Here's a practical example of mocking the response to a specific GET request and returning JSON data.

[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
    return [request.URL.path isEqualToString:@"/api/widget"];
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
    id JSON = @{ @"id": @"1234", @"name" : @"gadget" };
    NSData *data = [NSJSONSerialization dataWithJSONObject:JSON options:0 error:nil];
    return [OHHTTPStubsResponse responseWithData:data statusCode:200 headers:@{ @"Content-Type": @"application/json" }];
}];

这篇关于在 iOS 单元测试中模拟 NSHTTPURLRequest 和 NSHTTPURLResponse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆