gpt4 book ai didi

c# - 如何使 xUnit 并行运行 Theory?

转载 作者:太空狗 更新时间:2023-10-29 17:44:32 26 4
gpt4 key购买 nike

我有一个很慢的测试(理论)和一堆测试用例。所以我希望它们同时运行。

我创建了一个简单的示例:

[Theory]
[MyTestData]
public void MyTheory(int num, int sleep)
{
Console.WriteLine("{0:HH:mm:ss.ffff} - Starting {1} - Sleeping {2}", DateTime.Now, num, sleep);
Thread.Sleep(sleep);
Console.WriteLine("{0:HH:mm:ss.ffff} - Finished {1} - Sleeping {2}", DateTime.Now, num, sleep);
}

[AttributeUsage(AttributeTargets.Method)]
public class MyTestDataAttribute : DataAttribute
{
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
yield return new object[2] { 1, 5000 };
yield return new object[2] { 2, 2000 };
yield return new object[2] { 3, 4000 };
}
}

运行测试的命令行:

"\packages\xunit.runner.console.2.0.0\tools\xunit.console" "\Projects\xUnitTest\xUnitTest\bin\Debug\xUnitTest.dll" -parallel all > xUnitResult.txt

结果:

xUnit.net console test runner(64-bit.NET 4.0.30319.42000)
Copyright(C) 2015 Outercurve Foundation.

Discovering: xUnitTest
Discovered: xUnitTest
Starting: xUnitTest
21:55:39.0449 - Starting 2 - Sleeping 2000
21:55:41.0627 - Finished 2 - Sleeping 2000
21:55:41.0783 - Starting 1 - Sleeping 5000
21:55:46.0892 - Finished 1 - Sleeping 5000
21:55:46.0892 - Starting 3 - Sleeping 4000
21:55:50.0989 - Finished 3 - Sleeping 4000
Finished: xUnitTest

=== TEST EXECUTION SUMMARY ===
xUnitTest Total: 3, Errors: 0, Failed: 0, Skipped: 0, Time: 11,137s

这是非常连续的。我确信可以使其并行。

最佳答案

从 xUnit 2.1 开始,这目前是不可能的。根据parallelization docs ,

By default, each test class is a unique test collection. Tests within the same test class will not run in parallel against each other.

文档没有明确说明的是:

  • xUnit 中最小的“可并行化”单元是集合
  • 同一类中的测试不可能在不同的集合中

推而广之,不可能有平行的理论,因为理论不能跨多个类别进行拆分。


在您的情况下,这意味着您至少有两个选择:

  • 重构您的测试代码,以便抽象出任何占用大量时间的内容。例如,假设您必须运行一些业务逻辑然后进行数据库调用。如果您可以将可测试的业务逻辑分离到另一个类中,您就可以针对它运行您的理论(不是并行,而是在 <1 毫秒内),并单独测试慢速数据访问代码。

  • 如果您的测试用例足够少,只需为每个测试用例创建一个新类并使用 Fact 而不是 Theory。您甚至可以将它们全部放在一个文件中。它更加冗长,你失去了使用理论的“酷”因素,但你会得到并行执行。

关于c# - 如何使 xUnit 并行运行 Theory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32702969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com