Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save ccabanero/1160dc6d95182593d111 to your computer and use it in GitHub Desktop.

Select an option

Save ccabanero/1160dc6d95182593d111 to your computer and use it in GitHub Desktop.
Sample iOS Unit Tests: Model can Process the Response From Async Network Request
- (void)testFetchingFoursquareVenues {
//create a semaphore with initial value
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
NSURL *url = [NSURL URLWithString:@"https://api.yourawesome.com"];
NSURLSessionDataTask *task = [self.session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
XCTAssertNil(error, @"NSURLSessionDataTask returned completed with Error: %@", error);
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger statusCode = [httpResponse statusCode];
XCTAssertEqual(statusCode, 200, @"NSURLSessionDataTask did not complete with status code 200. Check the request URL. Returned Status Code of: %ld", (long)statusCode);
if(statusCode == 200) {
XCTAssertNotNil(data, @"NSURLSessionDataTask did not return data");
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *collectionOfStuff = [MyFetcher serializeTheStuffForResponse:responseDict];
XCTAssertTrue(collectionOfStuff.count > 0, @"Failed to serialize to a collection of stuff");
MyStuff *stuff = [collectionOfStuff lastObject];
XCTAssertTrue([venue isKindOfClass:[MyStuff class]], @"Collection does not have objects of type MyStuff");
//increment the semaphore
dispatch_semaphore_signal(semaphore);
}
}];
[task resume];
//decrement the semaphore
long rc = dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC));
XCTAssertEqual(rc, 0, @"Network request timed out.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment