在Swift中编写单元测试以测试异步任务

今天,我想快速告诉您如何测试异步代码。

想象一下您需要从Internet下载数据并检查是否一切运行正常,或需要其他一些异步运行的任务。 以及如何测试呢? 如果您尝试与常规同步代码相同怎么办?

func testAscynFunction() { someAsyncFunction() } func someAsyncFunction() { let bg = DispatchQueue.global(qos: .background) bg.asyncAfter(deadline: .now() + 5) { XCTAssert(false, "Something went wrong") } } 

这样的测试将为我们返回肯定的结果,因为该方法不会等待所有异步任务。

为了在测试中解决此类问题,有一件很棒的事情: XCTestExpectation
XCTestExpectation设置应执行异步方法的次数,并且只有在所有这些执行之后,测试才会结束并告知是否存在任何错误。 这是一个例子:

 class TestAsyncTests: XCTestCase { // 1)  expectation var expectation: XCTestExpectation! func testWithExpectationExample() { //2)   expectation = expectation(description: "Testing Async") //3)    ,     expectation.fulfill() expectation.expectedFulfillmentCount = 5 for index in 0...5 { someAsyncFunctionWithExpectation(at: index) } //5)      expectation.fulfill() //       60     ,     waitForExpectations(timeout: 60) { (error) in if let error = error { XCTFail("WaitForExpectationsWithTimeout errored: \(error)") } } } func someAsyncFunctionWithExpectation(at index: Int) { let bg = DispatchQueue.global(qos: .background) bg.asyncAfter(deadline: .now() + 5) { [weak self ] in XCTAssert(false, "Something went wrong at index \(index)") //4)      expectation.expectedFulfillmentCount self?.expectation.fulfill() } } } 

我希望这篇文章对某人有帮助。

Source: https://habr.com/ru/post/zh-CN439772/


All Articles