我们可以使用XCTAssertThrowsError
测试抛出的错误。异步事物可以用expectation
进行测试。我有一些方法可以将工作分派到后台线程,并且有时会引发错误。
是否有可能在将来某个地方引发错误?我需要将expectation
和XCTAssertThrowsError
结合起来,但我不知道如何。
复制项目:https://github.com/Jasperav/ThrowingAsyncError。只需克隆项目并运行测试,其中一项将失败。我创建了一个类,该类将在分配后几秒钟后崩溃。我想确保它在几秒钟后仍然崩溃,所以我需要一个测试用例。
Apple有一些示例代码使用expectation
测试异步功能,这听起来像正是您要查找的内容:
func testDownloadWebData() {
// Create an expectation for a background download task.
let expectation = XCTestExpectation(description: "Download apple.com home page")
// Create a URL for a web page to be downloaded.
let url = URL(string: "https://apple.com")!
// Create a background task to download the web page.
let dataTask = URLSession.shared.dataTask(with: url) { (data, _, _) in
// Make sure we downloaded some data.
XCTAssertNotNil(data, "No data was downloaded.")
// Fulfill the expectation to indicate that the background task has finished successfully.
expectation.fulfill()
}
// Start the download task.
dataTask.resume()
// Wait until the expectation is fulfilled, with a timeout of 10 seconds.
wait(for: [expectation], timeout: 10.0)
}
我看过复制项目,以了解您要在这里完成的工作...
您引用的异步代码不会抛出(计时器初始化程序)。据我所知,没有任何异步块可以抛出。也许您应该问的问题是,我们如何才能使同步操作有时选择同步运行,但在感觉到...时也异步运行...或者,对于要在每个类中进行测试的其他复杂性,我已经制定了一个解决方案,其几乎只有最低限度,以使其易于测试和可移植...据我了解:
XCTAssertThrowsError是采用可以抛出的块的断言。他们只是断言,同步块运行完成后会在同步块中引发错误。
XCTestExpectation是用于跟踪是否满足所请求条件的类。它们用于跟踪异步代码行为对象/引用,需要保留并在以后检查。
您似乎想做的是使XCTestExpectation之类的东西以与[[XCTAssertThrowsError相同的方式工作,就像在做出synchronous断言,将抛出一个[[asynchronous块一样。由于代码的运行和返回方式,它无法完全正常工作。
https://github.com/Jasperav/ThrowingAsyncError/pull/1/files
请问您为什么要做这样的事情?