考虑以下单元测试:
- (void)testSample {
XCTestExpectation *expectation = [self expectationWithDescription:@"Sample"];
[self.manager loadAllSuccess:^{
[expectation fulfill];
NSArray *data = [self.manager dataForIndex:0];
// Correct count of data is 10, not 44 - this should fail.
XCTAssertEqual(44, data.count);
} failure:^(NSError *error) {
[expectation fulfill];
XCTFail(@"Error encountered");
}];
[self waitForExpectationsWithTimeout:60 handler:nil];
}
我在已知的失败案例中遇到了一些问题。测试成功完成,尽管数据数组中应该只有 10 个项目。
如果我把
[expectation fulfill]
在 XCTAssertEqual(44, data.count)
之后的 block 底部调用方法调用,测试按预期工作并失败,直到我将值更正为 10。这是一个已知的问题?我一直无法阅读文档说我应该在最后一刻调用...
最佳答案
根据http://nshipster.com/xctestcase/
Always call fulfill() at the end of the asynchronous callback—fulfilling the expectation earlier can set up a race condition where the run loop may exit before completing the test. If the test has more than one expectation, it will not pass unless each expectation executes fulfill() within the timeout specified in waitForExpectationsWithTimeout().
刚刚发现这个 - 不确定它是否 100% 准确,因为我在其他地方看不到任何其他文件说明这一点。
关于ios - XCTestExpectation 在单元测试中的正确时间/位置完成方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263255/