Skip to content

Instantly share code, notes, and snippets.

@chillpop
Last active August 29, 2015 14:00
Asynchronous unit test helpers
@property (nonatomic, strong) dispatch_semaphore_t waitSemaphore
- (void)setUp {
[super setUp];
// Set-up code here.
self.waitSemaphore = dispatch_semaphore_create(0);
}
- (void)waitForAsynchronousTask:(int)waitTimeInSeconds {
NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:waitTimeInSeconds];
while (dispatch_semaphore_wait(self.waitSemaphore, DISPATCH_TIME_NOW)) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeoutDate];
NSLog(@"waiting for response...");
if (timeoutDate == [timeoutDate earlierDate:[NSDate date]]) {
XCTAssertTrue(NO, @"Waiting for a response took longer than %dsec", waitTimeInSeconds);
return;
}
}
}
- (void)completeAsynchronousTask {
dispatch_semaphore_signal(self.waitSemaphore);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment