OHHTTPStubs Unit Test Implementation

535 Views Asked by At

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"];
1

There are 1 best solutions below

2
On BEST ANSWER

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];
}];
...