Last active
November 24, 2015 17:43
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (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]; | |
}]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, i'm hustlin'