Delay the execution of all unit tests in XCTest

时间:2016-08-31 17:41:43

标签: objective-c unit-testing testing xctest

I need my unit tests to wait for our sub-systems to initialize, which usually takes a few seconds. In order to wait for this, I can do the following in a test

- (void)testReverseActionWithOffset
{
    XCTestExpectation *expectation = [self expectationWithDescription:@"High Expectations"];

    // Wait for proper initialization of Realm and CrimsonObject system...
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{

The problem is, using this technique, I have to do this wait in every single test method. This leads to there being a two second delay between each test even after the system is booted up. Because the test methods run in an undetermined order, I can't put the delay in just one method. What is the correct way to handle this under XCTest?

1 个答案:

答案 0 :(得分:2)

  

因为测试方法以不确定的顺序运行,所以我不能只将延迟放在一个方法中

每次测试之间需要完成的任何事情都可以在-setUp-tearDown中完成。

如果您需要按XCTestCase执行一次,则可以使用类方法+setUp+tearDown。第一次运行在任何测试运行之前,后者在所有测试之后运行。

您可以通过旋转运行循环来执行任何这些方法中的非阻塞等待:

+ (void)setUp
{
    while( /* subsystems not ready */ ){
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
    }
}