.net - 如何使用通用夹具并行执行 xUnit 类测试?

标签 .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
{
    ...
}

当我运行所有测试时,似乎没有任何并行化,我认为这是因为现在我所有的测试类都是同一个集合的一部分。有没有办法在测试类中拥有一个通用的固定实例并并行执行?

最佳答案

我使用Assembly Fixture (Nuget)

Refer

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")]

关于.net - 如何使用通用夹具并行执行 xUnit 类测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66607741/

相关文章:

unit-testing - 对 Azure Functions 和 .csx 文件进行单元测试

c# - 如何在 Xunit 中创建基测试类来测试接口(interface)实现?

c# - 真正的通用实现

c# - MySql.Data 与 MySql.Data.CF

c# - 如何配置 xUnit 测试以与 NLog 一起使用?

带有 bUnit 的 C# Blazor 测试表单

sqlite - 在单元测试期间避免在 EF Core 2.2 中使用 HasData Seed DbContext

.net - 通过 VSTO 解决方案资源管理器文件夹结构与代码路径的 Excel 功能区

c# - 使用 DotNet HighCharts dll 在代码隐藏中制作图表

.net - 将对象图重新附加到 EntityContext : "cannot track multiple objects with the same key"