使用 async await 在 Swift 中控制时间

4

到目前为止,我一直在使用Combine和PointFree的TestSchedulershttps://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)
}

有没有一种类似于async/await的方法可以实现相同的功能?

1个回答

0

是的,它很棒!

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

因此,如果这个测试确实关注于获取结果,那么它可以这样写:

func testFetchContentSuccess() {
    let sut = ContentFetcher()

    XCTAssertEqual(sut.content, .notAsked)

    await sut.fetchContent()

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

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


我能在fetchContent实际完成之前拦截吗? - Fogmeister

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接