David David - 3 months ago 28
Objective-C Question

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?

Answer

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( /* systemIsStarting */ ){
        [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
    }
}