Created
January 16, 2013 20:10
-
-
Save mikekatz/4550430 to your computer and use it in GitHub Desktop.
Example of writing an OCUnit test that uses asynchronous methods by polling for completion
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
#define POLL_INTERVAL 0.05 //50ms | |
#define N_SEC_TO_POLL 1.0 //poll for 1s | |
#define MAX_POLL_COUNT N_SEC_TO_POLL / POLL_INTERVAL | |
- (void) testAnAsynchronousFunction | |
{ | |
__block BOOL done = NO; | |
//do async on a delay | |
float delayInSeconds = 0.5; | |
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); | |
dispatch_after(popTime, dispatch_get_current_queue(), ^(void){ | |
BOOL result = dosomething(); //do the actual logic | |
STAssertTrue(result, @"this would be whatever needed testing"); | |
done = YES; | |
}); | |
NSLog(@"started poll"); | |
NSUInteger pollCount = 0; | |
while (done == NO && pollCount < MAX_POLL_COUNT) { | |
NSLog(@"polling... %i", pollCount); | |
NSDate* untilDate = [NSDate dateWithTimeIntervalSinceNow:POLL_INTERVAL]; | |
[[NSRunLoop currentRunLoop] runUntilDate:untilDate]; | |
pollCount++; | |
} | |
if (pollCount == MAX_POLL_COUNT) { | |
STFail(@"polling timed out"); | |
} | |
NSLog(@"done polling"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment