Based on https://gist.github.com/2215212, a method helper to unit test AFNetworking operations in SenTestingKit.
// Call theResume() to stop the semaphore from blocking/waiting.
// Failure to call theResume() will cause the test to hang.
// This is needed to test asynchronous operations. See https://gist.github.com/2215212
- (void)dispatchSemaphoreInBlock:(void (^)(void (^theResume)(void)))theBlock {
dispatch_semaphore_t theSemaphore = dispatch_semaphore_create(0);
theBlock(^{ dispatch_semaphore_signal(theSemaphore); });
while (dispatch_semaphore_wait(theSemaphore, DISPATCH_TIME_NOW)) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
dispatch_release(theSemaphore);
}
// The unit test: Fail to succeed...
- (void)testDispatchSemaphoreInBlock {
// How it should have worked...
{
AFHTTPClient *theHTTPClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.google.com/"]];
[theHTTPClient
getPath:@""
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
STFail(@"This will not fail when it should...");
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
STFail(@"This will not fail when it should...");
}];
}
// The workaround with dispatchSemaphoreInBlock method...
[self dispatchSemaphoreInBlock:^(void (^theResume)(void)) {
AFHTTPClient *theHTTPClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.google.com/"]];
[theHTTPClient
getPath:@""
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
STFail(@"This will fail...");
theResume();
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
STFail(@"This will fail...");
theResume();
}];
}];
}