如何在 XCTest 中等待 T 秒而不会出现超时错误?

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

提问人:meaning-matters 提问时间:5/9/2018 最后编辑:meaning-matters 更新时间:3/8/2023 访问量:23438

问:

我想在不生成超时的情况下将测试进度延迟 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 等待函数的文档说的:

超时始终被视为测试失败。

我有哪些选择?

iOS Swift 超时 等待 xctest

评论


答:

80赞 A.Munzer 5/9/2018 #1

可以使用 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")
}
28赞 Robin Stewart 1/11/2021 #2

如果您知道某件事需要多少时间,并且只想等待该持续时间然后再继续测试,则可以使用以下一行:

_ = XCTWaiter.wait(for: [expectation(description: "Wait for n seconds")], timeout: 2.0)
13赞 André Henrique da Silva 3/26/2021 #3

对我最有效的是:

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)