XCTestExpectation 似乎在 Task() 中不起作用
XCTestExpectation does not seem to work in Task()
我正在尝试 运行 发出网络请求的测试 actor
,如果您在它仍有请求时调用它,它将取消第一个请求并抛出 CancellationError
.我使用 Task()
来模拟它被异步调用两次,代码似乎工作正常。我可以看到正确的错误被抛出并且 catch
-block 被执行。下面是代码。
func testCancellation() async throws {
//setup code
let expectation = XCTestExpectation(description: "Cancellation Error thrown")
let autocompleteHandler = AutocompleteHandler(session: session)
Task() {
do {
let _ = try await autocompleteHandler.autocomplete(query: "Grizzly Bear")
} catch {
if error is CancellationError { expectation.fulfill() }
}
}
Task() {
do {
let _ = try await autocompleteHandler.autocomplete(query: "Grizzly Bear")
} catch {
if error is CancellationError { expectation.fulfill() }
}
}
wait(for: [expectation], timeout: 1)
}
当 运行 执行此操作时,出现以下错误:
Asynchronous wait failed: Exceeded timeout of 1 seconds, with unfulfilled expectations: "Cancellation Error thrown".
但正如我所说。我可以看到 catch
块正在执行,error
是正确的类型并且正在调用 expectation.fulfill()
。
看完@Alexander 的评论后,我意识到我确实不需要等待任何事情。我将代码重新格式化为以下内容,现在可以使用了。
func testCancellation() async {
//Setup code
let autocompleteHandler = AutocompleteHandler(session: session)
async let first = autocompleteHandler.autocomplete(query: "Grizzly Bear")
async let second = autocompleteHandler.autocomplete(query: "Grizzly Bear")
do {
let _ = [try await first, try await second]
XCTFail("Should have thrown cancellation error")
} catch {
XCTAssert(error is CancellationError)
}
}
这按预期工作。
我正在尝试 运行 发出网络请求的测试 actor
,如果您在它仍有请求时调用它,它将取消第一个请求并抛出 CancellationError
.我使用 Task()
来模拟它被异步调用两次,代码似乎工作正常。我可以看到正确的错误被抛出并且 catch
-block 被执行。下面是代码。
func testCancellation() async throws {
//setup code
let expectation = XCTestExpectation(description: "Cancellation Error thrown")
let autocompleteHandler = AutocompleteHandler(session: session)
Task() {
do {
let _ = try await autocompleteHandler.autocomplete(query: "Grizzly Bear")
} catch {
if error is CancellationError { expectation.fulfill() }
}
}
Task() {
do {
let _ = try await autocompleteHandler.autocomplete(query: "Grizzly Bear")
} catch {
if error is CancellationError { expectation.fulfill() }
}
}
wait(for: [expectation], timeout: 1)
}
当 运行 执行此操作时,出现以下错误:
Asynchronous wait failed: Exceeded timeout of 1 seconds, with unfulfilled expectations: "Cancellation Error thrown".
但正如我所说。我可以看到 catch
块正在执行,error
是正确的类型并且正在调用 expectation.fulfill()
。
看完@Alexander 的评论后,我意识到我确实不需要等待任何事情。我将代码重新格式化为以下内容,现在可以使用了。
func testCancellation() async {
//Setup code
let autocompleteHandler = AutocompleteHandler(session: session)
async let first = autocompleteHandler.autocomplete(query: "Grizzly Bear")
async let second = autocompleteHandler.autocomplete(query: "Grizzly Bear")
do {
let _ = [try await first, try await second]
XCTFail("Should have thrown cancellation error")
} catch {
XCTAssert(error is CancellationError)
}
}
这按预期工作。