如何编写一个单元测试来检查异步函数是否不会超时?
我正在尝试常规XCTestExpectation
, 但是因为await
暂停一切,是等不到期待。
在下面的代码中,我正在检查loader.perform()
执行时间不超过1秒。
func testLoaderSuccess() async throws {
let expectation = XCTestExpectation(description: "doesn't timeout")
let result = try await loader.perform()
XCTAssert(result.value == 42)
wait(for: [expectation], timeout: 1) // execution never gets here
expectation.fulfill()
}
如果任务超时,取消任务可能是明智的做法:
func testA() async throws {
let expectation = XCTestExpectation(description: "timeout")
let task = Task {
let result = try await loader.perform()
XCTAssertEqual(result, 42)
expectation.fulfill()
}
await fulfillment(of: [expectation], timeout: 1)
task.cancel()
}
如果你不,perform
即使之后仍可能继续运行testA
在失败场景中完成。
另一种方法是使用任务组:
func testB() async throws {
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask {
let result = try await self.loader.perform()
XCTAssertEqual(result, 42)
}
group.addTask {
try await Task.sleep(for: .seconds(1))
XCTFail("Timed out")
}
let _ = try await group.next() // wait for the first one
group.cancelAll() // cancel the other one
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)