2015-06-18 21 views
1

我有一个XCTTestClass,它具有异步设置方法。这需要一些时间(必须解析文件,将它们插入bd等),并且我想确保我的测试只在完成此设置后运行。异步setUp方法完成后运行测试

我该怎么做?

回答

2

您可以使用信号量等到您从异步调用中获得结果。

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); 
0

在您的-setup方法中,使用上面的信号量或使用dispatch_group。 dispatch_group是我的首选方法。

@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. 
    }); 
} 

然后覆盖-invokeTest并确保组块(设置)已完成运行。

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

这保证了-setup完成后的测试才会运行。