Skip to content

Instantly share code, notes, and snippets.

@jamztang
Forked from lxcid/gist:2586763
Created May 3, 2012 16:28
Show Gist options
  • Save jamztang/2587002 to your computer and use it in GitHub Desktop.
Save jamztang/2587002 to your computer and use it in GitHub Desktop.
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();
}];
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment