1

I am trying to correctly implement OHHTTPStubs but am having a bit of trouble.

I want to do exactly what this library does. Make a request to a URL and return a mocked JSON response.

This is how I have it set up, yet nothing ever gets called correctly, and stubs aren't even ran.

- (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]);

}

The answer, provided by kevinosaurio, was to change this line:

[request.URL.host isEqualToString:@"http://www.myweb.com"];

to

[request.URL.host isEqualToString:@"www.myweb.com"];
Michael
  • 193
  • 2
  • 12

1 Answers1

1

Your problem it's that your host is www.myweb.com no 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];
}];
...
Kevinosaurio
  • 1,952
  • 2
  • 15
  • 18
  • I have tried that, but get this error every time. `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` – Michael Jul 09 '18 at 20:42
  • You only need to change it in this line: `[request.URL.host isEqualToString:@"www.myweb.com"]`. In the others use: `"http://www.myweb.com"` – Kevinosaurio Jul 09 '18 at 20:46