2

我有许多异步单元测试,它们使用期望可以正常工作。但是,当我运行套装中的所有测试时,它们不会等待彼此完成 - 当下一个测试开始运行时,异步回调仍处于挂起状态。我想要的是每个测试在运行之前等待上一个测试中的期望。这些测试使用共享数据库,因此让它们重叠会导致烦人的额外复杂性,并且在作为套件运行时会导致测试失败。

- (void)testSignIn {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.

XCTestExpectation *expectation =
[self expectationWithDescription:@"Expectations"];

[_userManager signInWithUsername:kUserEmail andPassword:kUserPassword
                         success:^{
                             XCTAssertNotNil([_userManager getCurrentUser]);

                             XCTAssertNotNil([_userManager getCurrentUser].plan);
                             XCTAssertTrue([_userManager getCurrentUser].plan.liveStream == TRUE);

                             [expectation fulfill];

                         } failure:^(EDApiError *apiError) {
                             XCTAssertTrue(FALSE); // Should not fail
                             [expectation fulfill];

                         }];

[self waitForExpectationsWithTimeout:5.0 handler:^(NSError *error) {
    if (error) {
        NSLog(@"Timeout Error: %@", error);
    }
}];

}

4

2 回答 2

0

我发现您需要满足对主线程的期望——如果您的异步完成块可能在另一个线程上运行,这很重要。我还发现问题可能是由较早运行的错误测试触发的,因此它并不总是由出现故障的测试引起。

另外,请注意您是否生成了大量异步块(我这样做是为了进行疯狂的线程安全测试,或者测试检查对资源的独占访问是否按预期工作,并且按预期顺序工作)。一旦你达到了预期,测试就会进入下一个测试,但如果你在那之后触发了很多异步块,它们可能仍在运行。

于 2017-10-30T18:56:26.357 回答
0

使用XCTWaiterwaitForExpectations(timeout:handler:)来停止每个测试的完成,直到期望得到满足。

这篇博文解释了您在编写异步测试时可能遇到的一些更复杂的陷阱以及如何防止它们:https ://jeremywsherman.com/blog/2016/03/19/xctestexpectation-gotchas/

于 2017-09-30T08:47:54.353 回答