Skip to content

Instantly share code, notes, and snippets.

@n-b
Created April 4, 2012 08:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n-b/2299695 to your computer and use it in GitHub Desktop.
Save n-b/2299695 to your computer and use it in GitHub Desktop.
A simple runloop addition to ease Asynchronous Unit Tests in ObjC
//
// NSRunLoop+TimeOutAndFlag.h
//
//
@interface NSRunLoop (TimeOutAndFlag)
- (void)runUntilTimeout:(NSTimeInterval)delay orFinishedFlag:(BOOL*)finished;
@end
//
// 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
//
// 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