Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 241
David Avatar asked Dec 06 '25 03:12

David


1 Answers

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]];
    }
}
like image 81
jscs Avatar answered Dec 08 '25 16:12

jscs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!