LoginSignup
23
25

More than 5 years have passed since last update.

非同期のユニットテスト

Last updated at Posted at 2014-02-20

非同期ユニットテストを書く時に便利なメソッド。
非同期呼び出し時に、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
23
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
25