David
David

Reputation: 1650

Delay the execution of all unit tests in 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?

Upvotes: 3

Views: 1370

Answers (1)

jscs
jscs

Reputation: 64022

Because the test methods run in an undetermined order, I can't put the delay in just one method

Anything that needs to be done between every test can be done in either -setUp or -tearDown.

If you need to do something once per XCTestCase, you can use either of the class methods +setUp or +tearDown. The first runs before any tests are run, and the latter after all tests.

You can do a non-blocking wait in any of those methods by spinning the run loop:

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

Upvotes: 2

Related Questions