我有一组需要共享状态的 xunit.net 测试。希望我希望这些测试并行运行。所以我希望跑步者做:
在阅读 xunit 文档时,它说要在测试类之间共享状态,我需要定义一个“集合固定装置”,然后将我所有的测试类都放入该新集合中(例如:)[Collection("Database collection")]。但是,当我将我的测试类放在同一个装置中时,它们不再并行运行,因此它超出了目的:(
是否有内置的方法可以在 XUnit 中执行我想要的操作?
我的回退是将我的共享状态放入一个静态类中。
您可以使用下面粘贴的示例中的AssemblyFixture 示例来扩展 xUnit ,以创建一个夹具,该夹具可以在并行运行时通过测试进行访问。
使用此方法,夹具在测试之前创建,然后注入到引用它的测试中。我使用它来创建一个用户,然后为该特定集运行共享该用户。
还有一个 nuget 包xunit.assemblyfixture:
using System;
using Xunit;
// The custom test framework enables the support
[assembly: TestFramework("AssemblyFixtureExample.XunitExtensions.XunitTestFrameworkWithAssemblyFixture", "AssemblyFixtureExample")]
// Add one of these for every fixture classes for the assembly.
// Just like other fixtures, you can implement IDisposable and it'll
// get cleaned up at the end of the test run.
[assembly: AssemblyFixture(typeof(MyAssemblyFixture))]
public class Sample1
{
MyAssemblyFixture fixture;
// Fixtures are injectable into the test classes, just like with class and collection fixtures
public Sample1(MyAssemblyFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void EnsureSingleton()
{
Assert.Equal(1, MyAssemblyFixture.InstantiationCount);
}
}
public class Sample2
{
MyAssemblyFixture fixture;
public Sample2(MyAssemblyFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void EnsureSingleton()
{
Assert.Equal(1, MyAssemblyFixture.InstantiationCount);
}
}
public class MyAssemblyFixture : IDisposable
{
public static int InstantiationCount;
public MyAssemblyFixture()
{
InstantiationCount++;
}
public void Dispose()
{
// Uncomment this and it will surface as an assembly cleanup failure
//throw new DivideByZeroException();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2528 次 |
| 最近记录: |