func execute(after: TimeInterval, testBlock: () -> Void) {
let result = XCTWaiter.wait(for: [expectation(description: "Delayed Test")], timeout: after)
if result == XCTWaiter.Result.timedOut {
testBlock()
} else {
XCTFail("Delay interrupted.")
}
}
然后我写了一个测试:
func testExecute() {
var i = 1
DispatchQueue.main.asyncAfter(deadline: .now() + 0.40) {
i = 2
}
execute(after: 0.20) {
XCTAssert(i == 1)
}
execute(after: 0.15) {
XCTAssert(i == 1) // Fails once every three or four runs.
}
execute(after: 0.06) { // Never fails.
XCTAssert(i == 2)
}
}
为什么第二个XCTAssert()
经常失败?
这是我的模拟器上唯一运行的东西。您预计会有一些抖动,但不应该保持 1/60 秒系统时钟周期的 1 或 2 倍吗?