How to serialize parameterized tests with Swift Testing 如何使用 Swift Testing 序列化参数化测试

How to serialize parameterized tests with Swift Testing 如何使用 Swift Testing 序列化参数化测试

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

Swift Testing’s parameterized tests allow us to send multiple values into a single test, and they’ll be run in parallel for maximum performance. If you don’t want this – if you want to run parameterized tests serially rather than in parallel, you should add the .serialized trait to the @Test macro.
Swift Testing 的参数化测试允许我们将多个值发送到单个测试中,并且它们将并行运行以获得最佳性能。如果你不想这样做 —— 如果你想串行而不是并行运行参数化测试,你应该将 .serialized trait 添加到 @Test 宏中。

Important: This only affects parameterized tests, and will have no effect on non-parameterized tests.
重要: 这只影响参数化测试,对非参数化测试没有影响。

As an example, you might have a Player type that tracks scores, but you know it doesn’t handle parallel access very well – perhaps it uses a server that limits connections, for instance.
例如,您可能有一个跟踪分数的 Player 类型,但您知道它不能很好地处理并行访问 – 例如,它可能使用限制连接的服务器。

In this case, we could use the .serialized test trait to perform our tests. Even though each test itself uses async/await, Swift Testing won’t allow multiple instances of the test to run in parallel:
在这种情况下,我们可以使用 .serialized 测试 trait 来执行我们的测试。即使每个测试本身都使用 async/await,Swift 测试也不允许测试的多个实例并行运行:

@Test("Scores should always be in the range 0...100", .serialized, arguments: [0, 50, 100, 200, -1]
)
func addingPoints(score: Int) async {
    var player = Player()
    await player.add(points: score)
    #expect(player.score >= 0 && player.score <= 100)
}

This feature is only available in Swift Testing – to get something similar in XCTest you’d need to create separate test targets and manually enable or disable parallel testing for each one.
此功能仅在 Swift Testing 中可用 – 要在 XCTest 中获得类似的功能,您需要创建单独的测试目标并为每个目标手动启用或禁用并行测试。

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