【问题标题】:Controlling time with async await in Swift在 Swift 中使用异步等待控制时间
【发布时间】:2022-08-04 00:27:20
【问题描述】:

到目前为止,我一直在使用 Combine 和 PointFree TestScheduler https://github.com/pointfreeco/combine-schedulers 在我的测试中“控制时间”。

我可以提出请求,然后在过程中的某些点断言值而不会遇到任何麻烦。

例子...

func testFetchContentSuccess() {
    let queue = TestSchedulerOf<DispatchQueue>(now: .init(.now()))

    let sut = sut(queue: queue.eraseToAnyScheduler())

    XCTAssertEqual(sut.content, .notAsked)

    sut.fetchContent()

    XCTAssertEqual(sut.content, .loading) // this would be impossible without a TestScheulder as the mock endpoint would return immediately.

    queue.advance() // this is what I\'m looking for from async await

    assertSnapshot(matching: sut.content, as: .dump)
}

有没有办法用异步等待做类似的事情?

    标签: swift async-await combine


    【解决方案1】:

    是的,而且太棒了!

    您可以将测试方法声明为async,然后在测试方法中声明await

    所以如果这个测试真的是关于 fetch 的结果,它可能只是:

    func testFetchContentSuccess() {
        let sut = ContentFetcher()
    
        XCTAssertEqual(sut.content, .notAsked)
    
        await sut.fetchContent()
    
        assertSnapshot(matching: sut.content, as: .dump)
    }
    

    我有很多使用 XCTestExpectation 的测试,当它们转换为基于 async/await 时,大多数测试会变得更短更容易阅读。

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 2020-07-11
      • 2021-10-13
      • 1970-01-01
      • 2017-04-16
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多