我正在尝试正确实现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"];