OGeek|极客世界-中国程序员成长平台

标题: ios - 在 XCode 中开始下一个单元测试之前等待 XCTestExpectation [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:51
标题: ios - 在 XCode 中开始下一个单元测试之前等待 XCTestExpectation

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

- (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);
    }
}];

}



Best Answer-推荐答案


使用 XCTWaiterwaitForExpectations(timeout:handler推迟每个测试的完成,直到达到预期为止。

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

关于ios - 在 XCode 中开始下一个单元测试之前等待 XCTestExpectation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46497158/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4