【问题标题】:How to test async functions in swift using XCTWaiter and exceptions如何使用 XCTWaiter 和异常快速测试异步函数
【发布时间】:2018-10-04 15:51:44
【问题描述】:

我想在 Swift 中测试 异步 函数,因此如下所示,我创建了一个 XCTestExpectation 并将其传递给 XCTWaiter。现在,无论期望是否实现,我总是成功运行测试

你能指出代码中有什么问题吗?我完全关注了一个为 Swift 3 制作的博客,但是,我正在运行 Swift 4。这是问题所在吗?

func testAsyncFunction() {
        let expectation = XCTestExpectation(description: "Some description")
        vc.asyncFunction(5) { (abc: Int) -> Int in
            if (abc != 25) {
                // expectation.fulfill()
            }
            return 0
        }
        _ = XCTWaiter.wait(for: [expectation], timeout: 2.0)
    }

【问题讨论】:

  • 使用 XCTestCase 的便捷函数更容易:let asyncCompleted = self.expectation(description: "Some description")self.waitForExpectations(timeout: 2.0)。似乎 XCTWaiter.wait 不仅返回结果,而且在超时的情况下不会使测试失败。
  • 按预期工作,谢谢

标签: swift unit-testing xctest xctestexpectation xctwaiter


【解决方案1】:

XCTWaiter.wait 返回一个XCTWaiter.Result,您应该观察它。

func testAsyncFunction() {
    let expectation = XCTestExpectation(description: "Some description")
    vc.asyncFunction(5) { (abc: Int) -> Int in
        if (abc != 25) {
            // expectation.fulfill()
        }
        return 0
    }

    let result = XCTWaiter.wait(for: [expectation], timeout: 2.0) // wait and store the result
    XCTAssertEqual(result, .timedOut) // check the result is what you expected
}

【讨论】:

  • 添加到这个答案。如果期望得到满足或者这就是你所期望的,那么你的断言应该更改为:XCTAssertEqual(result, .completed)
猜你喜欢
  • 2018-11-18
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
相关资源
最近更新 更多