Created
April 4, 2012 08:29
-
-
Save n-b/2299695 to your computer and use it in GitHub Desktop.
A simple runloop addition to ease Asynchronous Unit Tests in ObjC
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
// | |
// NSRunLoop+TimeOutAndFlag.h | |
// | |
// | |
@interface NSRunLoop (TimeOutAndFlag) | |
- (void)runUntilTimeout:(NSTimeInterval)delay orFinishedFlag:(BOOL*)finished; | |
@end |
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
// | |
// NSRunLoop+TimeOutAndFlag.m | |
// | |
// | |
#import "NSRunLoop+TimeOutAndFlag.h" | |
@implementation NSRunLoop (TimeOutAndFlag) | |
- (void)runUntilTimeout:(NSTimeInterval)delay orFinishedFlag:(BOOL*)finished; | |
{ | |
NSDate * endDate = [NSDate dateWithTimeIntervalSinceNow:delay]; | |
do { | |
[self runMode:NSDefaultRunLoopMode beforeDate:nil]; | |
} while (!*finished && [endDate compare:[NSDate date]]==NSOrderedDescending); | |
} | |
@end |
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
// | |
// Request_tests.m | |
// | |
// | |
#import "NSRunLoop+TimeOutAndFlag.h" | |
@interface Request_tests : SenTestCase | |
@end | |
@implementation Request_tests | |
- (void) testRequest | |
{ | |
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]; | |
__block BOOL found; | |
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] | |
completionHandler:^(NSURLResponse * response, NSData * data, NSError * error) { | |
STAssertEquals([(NSHTTPURLResponse*)response statusCode],(NSInteger)200,@"server did not respond correctly"); | |
found = YES; | |
}]; | |
[[NSRunLoop mainRunLoop] runUntilTimeout:5 orFinishedFlag:&found]; | |
STAssertTrue(found,@"server did not respond in time"); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment