【问题标题】:Add data to DbContext only once只将数据添加到 DbContext 一次
【发布时间】:2019-11-15 12:53:05
【问题描述】:

我创建了一个 XUnit 夹具来定义 EF Core 上下文初始数据:

public class ServiceProviderFixture : IDisposable {

  public IServiceProvider Provider { get; private set; }

  public ServiceProviderFixture() {
    IServiceCollection services = new ServiceCollection();
    services.AddDbContext<Context>(x => { x.UseInMemoryDatabase("Database"); });
    Provider = services.BuildServiceProvider();
    BuildContext();
  }

  private void BuildContext() { 
    Context context = Provider.GetService<Context>();
    context.Countries.Add(new Country { Code = "fr", Name = "France" });
    context.SaveChanges();
  }

  public void Dispose() { } 

} 

然后在一些测试中我使用它如下:

 public class TestMethod1 : IClassFixture<ServiceProviderFixture> {

   public Test(ServiceProviderFixture fixture) {
    _fixture = fixture;
   } 

  [Fact]
  public async Task Test1() {

    IServiceProvider provider = _fixture.Provider;

    Context context = provider.GetService<Context>();

    // Add test data to context
    // Test some method

  }

} 

当我运行一项测试时,它运行良好......但是当我使用 dotnet test 运行所有测试时,我得到:

An item with the same key has already been added. Key: fr
The following constructor parameters did not have matching fixture data:
ServiceProviderFixture fixture)

我相信 BuildContext() 在同一上下文中的每个 TestClass 都会被调用一次。

我该如何解决这个问题?

【问题讨论】:

    标签: c# asp.net-core entity-framework-core xunit xunit.net


    【解决方案1】:

    因为您总是以相同的方式命名内存数据库,所以您总是会再次获得相同的数据库。

    您必须为每个测试用例命名不同的名称(例如Guid.NewGuid().ToString())。

    services.AddDbContext<Context>(x => 
        x.UseInMemoryDatabase($"Database{Guid.NewGuid()}")
    );
    

    【讨论】:

      【解决方案2】:

      只要检查你的 BuildContext 是否有任何数据,如果没有创建它,否则什么都不做。或者您可以在测试完成后清理创建的数据。

        private void BuildContext() { 
          Context context = Provider.GetService<Context>();
          if(!context.Countries.Any())
          {
              context.Countries.Add(new Country { Code = "fr", Name = "France" });
              context.SaveChanges();
          }
        }
      

      【讨论】:

        猜你喜欢
        • 2015-08-17
        • 2019-05-15
        • 1970-01-01
        • 2020-03-19
        • 2019-06-29
        • 1970-01-01
        • 2013-08-11
        • 1970-01-01
        • 2019-03-07
        相关资源
        最近更新 更多