Mock NSHTTPURLRequest and NSHTTPURL Failure in iOS unit test

I am developing an iOS framework that calls HTTP requests to a server. I wanted to write unit test to test the API '. I wanted to make fun of server calls without actually making a real server call. Can anyone help me with a unit test sample that makes mocking server calls. How to do it, we set expectations and return a manually processed URL response. "I use the XCTest framework for unit test and OCMock for mock objects."

+4
source share
2 answers

Here's how you could make fun of sendAsynchronousRequest:

NSDictionary *serverResponse = @{ @"response" : [[NSHTTPURLResponse alloc] initWithURL:nil statusCode:200 HTTPVersion:nil headerFields:@{}],
                                  @"data" : [@"SOMEDATA" dataUsingEncoding:NSUTF8StringEncoding]
                                  };

id connectionMock = [OCMockObject mockForClass:NSURLConnection.class];
[[[connectionMock expect] andDo:^(NSInvocation *invocation) {
    void (^handler)(NSURLResponse*, NSData*, NSError*);
    handler = [invocation getArgumentAtIndexAsObject:4];
    handler(serverResponse[@"response"], serverResponse[@"data"], serverResponse[@"error"]);
}] sendAsynchronousRequest:OCMOCK_ANY queue:OCMOCK_ANY completionHandler:OCMOCK_ANY];

EDIT

, . [NSURLConnection sendAsynchronousRequest: queue: completionHandler:]. _cmd self, Objective-C. , NSInvocation, 4 . , , , .

getArgumentAtIndexAsObject , OCMock, . , NSInvocation+OCMAdditions.h. , id.

+2

OHTTPStubs, https://github.com/AliSoftware/OHHTTPStubs.

GET JSON.

[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
    return [request.URL.path isEqualToString:@"/api/widget"];
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
    id JSON = @{ @"id": @"1234", @"name" : @"gadget" };
    NSData *data = [NSJSONSerialization dataWithJSONObject:JSON options:0 error:nil];
    return [OHHTTPStubsResponse responseWithData:data statusCode:200 headers:@{ @"Content-Type": @"application/json" }];
}];
+2

All Articles