如何在没有超时错误的情况下在 XCTest 中等待 T 秒?

How to wait in a XCTest for T seconds without timeout error?

我想将测试进程延迟 T 秒,而不产生超时。

首先我尝试了显而易见的:

sleep(5)
XCTAssert(<test if state is correct after this delay>)

但是失败了。

然后我尝试了:

let promise = expectation(description: "Just wait 5 seconds")
waitForExpectations(timeout: 5) { (error) in
    promise.fulfill()

    XCTAssert(<test if state is correct after this delay>)
}

我的 XCTAssert() 现在成功了。但是 waitForExpectations() 因超时而失败。

这是根据 XCTest wait functions 的文档说的:

Timeout is always treated as a test failure.

我有哪些选择?

您可以使用XCTWaiter.wait个函数;例如:

 let exp = expectation(description: "Test after 5 seconds")
 let result = XCTWaiter.wait(for: [exp], timeout: 5.0)
 if result == XCTWaiter.Result.timedOut {
     XCTAssert(<test if state is correct after this delay>)
 } else {
     XCTFail("Delay interrupted")
 }

如果您知道某件事需要多长时间,并且只想等待这段时间再继续测试,您可以使用这一行:

_ = XCTWaiter.wait(for: [expectation(description: "Wait for n seconds")], timeout: 2.0)

最适合我的是:

let timeInSeconds = 2.0 // time you need for other tasks to be finished
let expectation = XCTestExpectation(description: "Your expectation")

DispatchQueue.main.asyncAfter(deadline: .now() + timeInSeconds) {
    expectation.fulfill()
}    

wait(for: [expectation], timeout: timeInSeconds + 1.0) // make sure it's more than what you used in AsyncAfter call.

// do your XCTAssertions here
XCTAssertNotNil(value)