0

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

1 回答 1

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];
}];
...
于 2018-07-09T20:40:52.650 回答