How do you write a unit test that checks whether an async function doesn't timeout?
I'm trying with regular XCTestExpectation, but because await suspends everything, it can't wait for the expectation.
In the code below, I'm checking that loader.perform() doesn't take more than 1 second to execute.
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()
}
It might be prudent to cancel the task if it times out:
If you do not,
performmay continue to run even aftertestAfinishes in the failure scenario.The other approach would be to use a task group: