我知道默认情况下 xUnit 将串行执行类内的任务,但会并行执行跨类的任务。
我创建了 3 个测试类,但它们每个都需要通用的设置数据(在数据库中 - 是的,我知道包含数据库是一种不幸的情况,但这种包含不能改变)。
因此,为了初始化数据库中的数据集,我创建了一个固定装置:
/// <summary>
/// This fixture is used to initialize a known state of test data in the database
/// </summary>
public class DBFixture
{
/// <summary>
/// Clear out and create new test data. Ensure we have a known state of input data.
/// </summary>
public DBFixture()
{
string script = File.ReadAllText("Database\\DataSetup.sql");
using (SqlConnection con = new SqlConnection(...))
{
var result = con.QueryMultiple(script);
}
}
}
然后,为了将固定装置关联到多个类,我创建了一个将固定装置关联到集合的类。
/// <summary>
///
/// </summary>
/// <see cref="https://xunit.net/docs/shared-context"/>
[CollectionDefinition("My Collection")]
public class MyCollection: ICollectionFixture<DBFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
//This class, and it's CollectionDefinition attribute tell the xUnit framework that any Test class that has a Collection attribute with the same collection name, will use the same instance of DBFixture.
}
然后,我使用测试创建测试类,并将它们关联到我的集合。
[Collection("My Collection")]
public class MyTests
{
...
}
[Collection("My Collection")]
public class MyTests2
{
...
}
当我运行所有测试时,似乎没有任何并行化,我认为这是因为现在我所有的测试类都是同一个集合的一部分。 有没有办法在测试类中拥有通用的固定实例并并行执行?
我使用装配夹具(Nuget)
public class TestClass : IAssemblyFixture<TestFixture>
{
private readonly TestFixture fixture;
public MyTest(TestFixture fixture)
{
this.fixture = fixture;
}
[Fact]
public void MyTest()
{
// test code here
}
}
在AssemblyInfo.cs文件中注册TestFramework替换:
[assembly: TestFramework("Xunit.Extensions.Ordering.TestFramework", "Xunit.Extensions.Ordering")]
将 Meziantou.Xunit.ParallelTestFramework nuget 包添加到您的测试项目并并行进行所有测试。