Running tests after an asynchronous setUp method is finished

42 views Asked by At

I have a XCTTestClass that has an asynchronous setup method. It will take some amount of time (has to parse files, insert them in a bd, etc) and I want to make sure my tests only run after this setup is done.

How can I do this?

2

There are 2 answers

0
lead_the_zeppelin On

In your -setup method use either a semaphore as above or use dispatch_group. dispatch_group is my preferred approach.

@implementation XCTTestSubClass()
{
    dispatch_group_t _dispatchGroup;
}
@end

-(id)init
{
    _dispatchGroup = dispatch_group_create();
    return [super init];
}

-(void)setup
{
    dispatch_group_async(_dispatchGroup, dispatch_get_current_queue(), ^{
        //your setup code here.
    });
}

Then override -invokeTest and make sure the group blocks(setup) is done running.

-(void)invokeTest
{
    dispatch_group_notify(group, dispatch_get_current_queue(), ^{
        [super invokeTest];
    });
}

This guarantees that the tests will run only after -setup is completed.

0
GoodSp33d On

You can use semaphores to wait till you get the results back from your async call.

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
// Do your async call here
// Once you get the response back signal:
[self asyncCallWithCompletionBlock:^(id result) {
    dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);