我正在尝试正确实现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"];
答案 0 :(得分:0)
您的问题是您的主机是 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];
}];
...