Introduction to testing Swift concurrency Swift 并发测试简介

Introduction to testing Swift concurrency Swift 并发测试简介

温馨提示:本文最后更新于2025-02-10 10:12:33,某些文章具有时效性,若有错误或已失效,请在下方留言

Swift’s full range of concurrency features work great with unit tests using both the legacy XCTest framework and the new Swift Testing framework.
Swift 的全套并发功能非常适合使用旧版 XCTest 框架和新 Swift 测试框架的单元测试。

Although the way both frameworks work differs, they share some fundamentals:
尽管这两个框架的工作方式不同,但它们有一些共同的基本原理:

  1. Both should mark tests as async in order to test async functions.
    两者都应该将测试标记为 async 以测试async函数。
  2. Both can handle assertions completing a fixed number of times.
    两者都可以处理完成固定次数的断言。
  3. Both can force some or all of their tests to run on a specific actor.
    两者都可以强制其部分或全部测试在特定 actor 上运行。
  4. Both must handle completion-based asynchronous code carefully.
    两者都必须仔细处理基于完成的异步代码。
  5. Both can throw errors directly from their test, or catch them internally.
    两者都可以直接从测试中引发错误,也可以在内部捕获错误。

It’s worth adding that both frameworks can also run tests in parallel, although Swift Testing makes it easier with its struct-based approach.
值得补充的是,这两个框架也可以并行运行测试,尽管 Swift Testing 的基于结构的方法使其更容易。

Of course, there are also differences:
当然,也有不同之处:

  • XCTest runs synchronous tests on the main actor unless you say otherwise, whereas Swift Testing can run them anywhere it wants. This might mean you need to use @MainActor more, depending on your code.
    XCTest 在主要参与者上运行同步测试,除非你另有说明,而 Swift Testing 可以在任何它想要的地方运行它们。这可能意味着您需要使用更多@MainActor,具体取决于您的代码。
  • Swift Testing lets us selectively force specific tests to be run serially – i.e., one by one.
    Swift Testing 让我们有选择地强制特定测试按顺序运行 – 即逐个运行。
  • Swift Testing makes it trivial to set time limits for tests. This was possible with XCTest if you did it by hand, so the Swift Testing approach is a big improvement.
    Swift Testing 使设置测试的时间限制变得非常简单。如果您手动完成,那么使用 XCTest 是可能的,因此 Swift 测试方法是一个很大的改进。
  • Swift Testing allows test suites to be actors if you want.
    Swift Testing 允许您根据需要将测试套件作为参与者。

In the following chapters, we’ll explore testing Swift concurrency using both XCTest and Swift Testing, but if you have the choice I’d suggest using Swift Testing – the extra functionality it offers for organizing tests is really invaluable.
在接下来的章节中,我们将探索使用 XCTest 和 Swift Testing 测试 Swift 并发性,但如果您可以选择,我建议您使用 Swift Testing——它为组织测试提供的额外功能非常有价值。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享