OHHTTPStubs 单元测试实现
Posted
技术标签:
【中文标题】OHHTTPStubs 单元测试实现【英文标题】:OHHTTPStubs Unit Test Implementation 【发布时间】:2018-07-09 20:16:56 【问题描述】:我正在尝试正确实现OHHTTPStubs,但遇到了一些麻烦。
我想做这个库所做的事情。向 URL 发出请求并返回模拟的 JSON 响应。
这就是我设置它的方式,但没有任何东西被正确调用,甚至没有运行存根。
- (void)testWithOHHTTP
[OHHTTPStubs initialize];
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request)
return [request.URL.host isEqualToString:@"http://www.myweb.com"];
withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request)
NSDictionary* obj = @ @"key1": @"value1", @"key2": @[@"value2A", @"value2B"] ;
return [OHHTTPStubsResponse responseWithJSONObject:obj statusCode:200 headers:nil];
];
NSURL *URL = [NSURL URLWithString:@"http://www.myweb.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[OHHTTPStubs setEnabled:YES forSessionConfiguration:config];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
[request setHTTPMethod:@"GET"];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
NSLog(@"#### Data: %@, Response: %@, Error: %@", data, response, error);
NSDictionary *dataJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(@"#### %@", dataJSON);
];
[dataTask resume];
NSLog(@"All stubs: %@", [OHHTTPStubs allStubs]);
kevinosaurio 提供的答案是更改此行:
[request.URL.host isEqualToString:@"http://www.myweb.com"];
到
[request.URL.host isEqualToString:@"www.myweb.com"];
【问题讨论】:
【参考方案1】:你的问题是你的主机是 www.myweb.com 没有http://www.myweb.com。
...
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request)
return [request.URL.host isEqualToString:@"www.myweb.com"];
withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request)
NSDictionary* obj = @ @"key1": @"value1", @"key2": @[@"value2A", @"value2B"] ;
return [OHHTTPStubsResponse responseWithJSONObject:obj statusCode:200 headers:nil];
];
...
【讨论】:
我试过了,但每次都会出现这个错误。Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=NSUnderlyingError=0x1c024f0c0 Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)", NSErrorFailingURLStringKey=www.myweb.com, NSErrorFailingURLKey=www.myweb.com, NSLocalizedDescription=unsupported URL
您只需要在这一行中更改它:[request.URL.host isEqualToString:@"www.myweb.com"]
。在其他人使用:"http://www.myweb.com"
以上是关于OHHTTPStubs 单元测试实现的主要内容,如果未能解决你的问题,请参考以下文章
让 Alamofire 和 OHHTTPStubs 一起工作
iOS单元測试:Specta + Expecta + OCMock + OHHTTPStubs + KIF