在iOS中单机测试异步通话时,我遇到问题. (虽然在视图控制器中工作正常)
有人面临这个问题吗?我已经尝试使用等待功能,但我仍然面临同样的问题.
请建议一个很好的方法来做这个例子.
解决方法
我认为这个帖子中的许多建议的解决方案有一个问题,如果异步操作不完成,“完成”标志永远不会设置,测试将永久挂起.
我在许多测试中已经成功地使用了这种方法.
- (void)testSomething {
__block BOOL done = NO;
[obj asyncmethodUnderTestWithCompletionBlock:^{
done = YES;
}];
XCTAssertTrue([self waitFor:&done timeout:2],@"Timed out waiting for response asynch method completion");
}
- (BOOL)waitFor:(BOOL *)flag timeout:(NSTimeInterval)timeoutSecs {
NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutSecs];
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeoutDate];
if ([timeoutDate timeIntervalSinceNow] < 0.0) {
break;
}
}
while (!*flag);
return *flag;
}