Last active
August 29, 2015 13:57
-
-
Save drance/9613950 to your computer and use it in GitHub Desktop.
Got tired of semaphore/runloop boilerplate for async unit tests
This file contains 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
- (void)sleepRunLoopForInterval:(NSTimeInterval)interval whileRunningAsynchronousTest:(void (^)(dispatch_semaphore_t semaphore))test { | |
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); | |
NSAssert((test != NULL), @"Passed a NULL test block"); | |
test(semaphore); | |
while(dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) { | |
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:interval]]; | |
} | |
} | |
- (void)testAsynchronousStuff { | |
[self sleepRunLoopForInterval:1.0 whileRunningAsynchronousTest:^(dispatch_semaphore_t semaphore) { | |
[self thatAPIWeNeedToTestWithCompletion:^{ | |
STAssertTrue(something, @"Noes"); | |
dispatch_semaphore_signal(semaphore); | |
}]; | |
}]; | |
} | |
- (void)testMoreAsynchronousStuff { | |
[self sleepRunLoopForInterval:0.2 whileRunningAsynchronousTest:^(dispatch_semaphore_t semaphore) { | |
[self thatOtherAPIWeNeedToTestWithCompletion:^(id result){ | |
STAssertNotNil(result, @"Noes"); | |
dispatch_semaphore_signal(semaphore); | |
}] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@benlings: I like that.
Here it is as an XCTestCase subclass:
Then you can write tests thusly:
Unfortunately Xcode's introspection of test code doesn't appear to be deep enough to get a little green/red diamond next to passing/failing tests if it's architected this way.