Skip to content

Instantly share code, notes, and snippets.

@Thunderbird7
Last active November 24, 2015 17:43
Show Gist options
  • Save Thunderbird7/98bae610b3236387722a to your computer and use it in GitHub Desktop.
Save Thunderbird7/98bae610b3236387722a to your computer and use it in GitHub Desktop.
Test case example to test response of an asynchronous networking request with XCTestExpectation APIs
- (void)testAsynchronousURLConnection {
// Create request
NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"];
NSString *description = [NSString stringWithFormat:@"GET %@", URL];
XCTestExpectation *expectation = [self expectationWithDescription:description];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithURL:URL
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError * error)
{
XCTAssertNotNil(data, @"data should not be nil");
XCTAssertNil(error, @"error shuold be nill");
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
XCTAssertEqual(httpResponse.statusCode, 200, @"HTTP response status code should be return 200");
XCTAssertEqualObjects(httpResponse.URL.absoluteString, URL.absoluteString, @"HTTP response URL should be equal to Original URL");
XCTAssertEqualObjects(httpResponse.MIMEType, @"application/json", @"HTTP response content type should be application/json");
} else {
XCTFail(@"Response was not NSHTTPURLResponse");
}
[expectation fulfill];
}];
// fire request
[task resume];
// wait timeout
[self waitForExpectationsWithTimeout:task.originalRequest.timeoutInterval handler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"ERROR: %@", error.localizedDescription);
}
[task cancel];
}];
}
@Thunderbird7
Copy link
Author

Hey, i'm hustlin'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment