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

zu0ti5jz  于 2023-03-09  发布在  iOS
关注(0)|答案(3)|浏览(144)

我想将测试的进程延迟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的文档说明:
超时始终被视为测试失败。
我有什么选择?

bqujaahr

bqujaahr1#

您可以使用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")
}
mbyulnm0

mbyulnm02#

如果您知道某项测试将花费多长时间,并且只是想在继续测试之前等待该持续时间,则可以使用以下一行代码:

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

ars1skjm3#

对我最有效的是:

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)

相关问题