.net - 如何使用通用夹具并行执行 xUnit 类测试?
问题描述
我知道默认情况下 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")]
推荐阅读
- json - Swift: Parse data Codable protocol not working
- vmware - 打包器:从源 ova 构建时出错
- python - Django - 重定向到子类管理页面
- oracle - Oracle中字段的自动调整
- php - Laravel Get Column Name error
- vb.net - 在 VB.net 屏幕上的任意位置使用鼠标滚动
- neo4j - Neo4J 多步骤导入/转换期间的性能问题
- python - Upgrade python 3.4 to python 3.6 on rpi
- c# - Image Getting Stretched when trying to Resize It keeping the aspect Ratio
- exoplayer - 点击 ExoPlayer 通知打开应用