简体   繁体   English

在 Swift 中使用异步等待控制时间

[英]Controlling time with async await in Swift

Up to now I've been using Combine and the PointFree TestSchedulers https://github.com/pointfreeco/combine-schedulers to "control time" in my tests.到目前为止,我一直在使用Combine和 PointFree TestScheduler https://github.com/pointfreeco/combine-scheduler在我的测试中“控制时间”。

I can make a request and then assert values at certain points in the process without any trouble.我可以提出请求,然后在过程中的某些点断言值而不会遇到任何麻烦。

Example...例子...

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)
}

Is there a way to do something similar with async await?有没有办法用异步等待做类似的事情?

Yes, and it's awesome!是的,而且太棒了!

You can just declare test methods as async , then await right in the test method.您可以将测试方法声明为async ,然后在测试方法中直接await

So if this test is really about the results of the fetch, it could just be:所以如果这个测试真的是关于 fetch 的结果,它可能只是:

func testFetchContentSuccess() {
    let sut = ContentFetcher()

    XCTAssertEqual(sut.content, .notAsked)

    await sut.fetchContent()

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

I have lots of tests that use XCTestExpectation , and most get a lot shorter and easier to read when they're converted to be async/await based.我有很多使用XCTestExpectation的测试,当它们转换为基于 async/await 时,大多数测试会变得更短且更容易阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM