c# - 仅向 DbContext 添加数据一次

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

我创建了一个 XUnit fixture 来定义 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 被调用一次。

我该如何解决这个问题?

最佳答案

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

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

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

关于c# - 仅向 DbContext 添加数据一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58877478/

相关文章:

c# - 显示/隐藏其他下拉列表值的下拉列表值已更改

entity-framework - ASP.Net.Core 2.2 身份更改 ID 从字符串到 int

c# - 如何解决下面 @role.Name 出现的 null 错误?

C# Linq 查询执行顺序

c# - 字符串参数 'migrationId' 不能为空

c# - 为什么我不能从 long 派生?

c# - 使用 Firefox 在 Silverlight 中执行 javascript

c# - 单元测试代码的最佳位置

.net - 如何使用区域在 razor 组件库中使用 blazor 服务器端?

asp.net-core - ASP.Net 5类库包中的EntityFramework命令?