Skip to content

Instantly share code, notes, and snippets.

@lxcid
Last active October 4, 2015 05:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lxcid/2586763 to your computer and use it in GitHub Desktop.
Save lxcid/2586763 to your computer and use it in GitHub Desktop.
Call resume() to stop the block from exercising the run loop and break out of the loop/block. Failure to call resume() will cause the test to hang indefinitely. This is useful to testing asynchronous actions like AFNetworking operations. See https://gist.github.com/2215212 With some reference from https://github.com/icanzilb/MTTestSemaphore, I w…
typedef void (^LXSResumeBlock)(void);
typedef void (^LXSRunLoopBlock)(LXSResumeBlock resume);
// Call resume() to stop the block from exercising the run loop and break out of the loop/block.
// Failure to call resume() will cause the test to hang indefinitely.
// This is useful to testing asynchronous actions like AFNetworking operations. See https://gist.github.com/2215212
// With some reference from https://github.com/icanzilb/MTTestSemaphore, I was able to simplify this method.
inline void LXS_exercisesRunLoopInBlock(LXSRunLoopBlock block) {
__block BOOL keepRunning = YES;
block(^{ keepRunning = NO; });
while (keepRunning && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.03]]) {
}
}
// The example...
- (void)testExercisesRunLoopInBlock {
// The workaround with testRunLoopInBlock method...
LXS_exercisesRunLoopInBlock(^(LXSResumeBlock resume) {
AFHTTPClient *theHTTPClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.google.com/"]];
[theHTTPClient
getPath:@""
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
STAssertTrue(YES, @"This has pass...");
resume();
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
STFail(@"This has fail...");
resume();
}];
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment