解决方法
我认为这个帖子中的许多建议的解决方案有一个问题,如果异步操作不完成,“完成”标志永远不会设置,测试将永久挂起.
我在许多测试中已经成功地使用了这种方法.
- (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; }