如何在 DbContext - 主键中并行运行 Xunit 而不会发生冲突?

4 c# entity-framework xunit .net-core asp.net-core

我正在使用内存数据库创建 Xunit 测试。如果单独运行,测试将正确执行。但是,如果并行运行,它们会由于 dbcontext 中的主键问题而发生冲突。

解决这个问题的最佳选择是什么?

  1. Xunit有拆解能力吗?听说xunit不支持这个。
  2. 我应该按顺序运行测试吗?
  3. 应该继续使用不同的密钥 ID 吗?

尝试研究xunit文档,刚刚开始学习.net编程。

错误:

"System.ArgumentException : An item with the same key has already been added. Key: 2"
Run Code Online (Sandbox Code Playgroud)

代码:

2为主键,使用两次

public class ProductAppServiceTest
{
    public TestContext context;
    public IMapper mapper;
    public ProductAppServiceTest()
    {
        var options = new DbContextOptionsBuilder<TestContext>()
            .UseInMemoryDatabase(databaseName: "TestDatabase")
            .Options;
        context = new TestContext(options);

        ApplicationServicesMappingProfile applicationServicesMappingProfile = new ApplicationServicesMappingProfile();
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(applicationServicesMappingProfile);
        });
        mapper = config.CreateMapper();
    }

    [Fact]
    public async Task Get_ProductById_Are_Equal()
    {
        context.Product.Add(new Product { ProductId = 2, ProductCode = "123", ProductName = "ABC" });
        context.SaveChanges();

        var ProductRepository = new ProductRepository(context);
        var ProductAppService = new ProductAppService(ProductRepository, mapper);
        var ProductDto = await ProductAppService.GetProductById(2);

        Assert.Equal("123", ProductDto.ProductCode);
    }

    [Fact]
    public async Task Get_ProductPrice_Are_Equal()
    {
        context.Product.Add(new Product { ProductId = 2, ProductCode = "123", ProductName = "ABC" });
        context.SaveChanges();

        var ProductRepository = new ProductRepository(context);
        var ProductAppService = new ProductAppService(ProductRepository, mapper);
        var ProductDto = await ProductAppService.GetProductById(2);
        //Goes into Enum table to validate price is 5
        Assert.Equal("5", ProductDto.Price);
    }
Run Code Online (Sandbox Code Playgroud)

N M*_*ead 6

这里的问题是您为每个测试使用相同的内存数据库。虽然您可以为每个测试拆除并创建数据库,但通常为每个测试使用唯一的数据库更容易。

注意:每个测试使用相同数据库的原因是因为您使用的是静态数据库名称。

guidXUnit 在每次测试之前调用测试类构造函数,因此您可以通过使用数据库名称为每个测试创建唯一的内存数据库。

var options = new DbContextOptionsBuilder<TestContext>()
                      .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                      .Options;
context = new TestContext(options);
Run Code Online (Sandbox Code Playgroud)