非同期ユニットテストを書く時に便利なメソッド。
非同期呼び出し時に、startAsyncTest、完了時にendAsyncTestを呼ぶようにするだけで、各テストごとに終了待ちをするようになります。
#import <XCTest/XCTest.h>
@interface SampleTestCase : XCTestCase
@property int numOfRunningAsyncTest;
@end
@implementation SampleTestCase
- (void)setUp
{
[super setUp];
self.numOfRunningAsyncTest = 0;
}
- (void)tearDown
{
//Wait until all the async test completes
NSTimeInterval timeoutSec = 1;
NSTimeInterval monitorInterval = 0.1;
NSDate *startDate = [NSDate date];
while(true) {
@synchronized(self){
if(self.numOfRunningAsyncTest == 0){
break;
}
}
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate dateWithTimeIntervalSinceNow:monitorInterval]];
if([[NSDate date] timeIntervalSinceDate:startDate] >= timeoutSec){
XCTFail(@"Timed out, Didn't you forget to call endAsyncTest?");
break;
}
}
[super tearDown];
}
- (void) startAsyncTest
{
@synchronized(self){
self.numOfRunningAsyncTest++;
}
}
- (void) endAsyncTest
{
@synchronized(self){
self.numOfRunningAsyncTest--;
}
}
@end