【问题标题】:.NET6 - Integration test with Entity Framework Core gives tracking error.NET6 - 与 Entity Framework Core 的集成测试给出跟踪错误
【发布时间】:2023-01-31 08:27:47
【问题描述】:

我创建了一个 AppFactory 类,所有测试类都使用它通过 IClassFixture 为所有测试类设置一致的起点。通过使用 TestContainer 包,每个测试类都有自己的 docker 数据库。

private readonly TestcontainerDatabase _dbContainer =
    new TestcontainersBuilder<PostgreSqlTestcontainer>()
        .WithDatabase(new PostgreSqlTestcontainerConfiguration
        {
            Database = "integration_test",
            Username = "integration_test",
            Password = "integration_test"
        })
        .Build();
builder.ConfigureTestServices(services =>
{
    services.RemoveAll(typeof(IHostedService));

    services.RemoveDbContext<ApplicationDbContext>();
    services.RemoveAll<DbContext>();

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(_dbContainer.ConnectionString)
    );

这个 Appfactory 继承自WebApplicationFactory&lt;IAppMarker&gt;, IAsyncLifetime。在 AppFactoryInitializeAsync 中,我为数据库播种。但是,当超过 1 个类同时进行测试时,我会遇到 Entityframework 跟踪问题。即使每个测试类都有自己的数据库。

System.InvalidOperationException The instance of entity type 'Country' cannot be tracked because
another instance with the same key value for {'Id'} is already being tracked. 
When attaching existing entities, ensure that only one entity instance with a given 
key value is attached.

我已经尝试将 context.ChangeTracker.Clear(); 添加到播种机,这减少了发生错误的机会,但它仍然可能发生。我希望实体框架为每个测试类/数据库创建一个不同的跟踪器,这样就不会发生这个错误。

我还尝试使用 AddDbContextFactory 为每个测试创建一个新的上下文,但这也没有效果。

【问题讨论】:

  • 为每个测试创建新的DbContext

标签: .net entity-framework-core integration-testing


【解决方案1】:

你能展示你是如何为数据库播种的吗?我正在尝试使用 EF Core 播种,但我总是收到错误消息,指出我的表不存在 Message:  Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while saving the entity changes. See the inner exception for details. ---- Npgsql.PostgresException : 42P01: relation "public.Worlds" does not exist

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2018-07-25
    • 1970-01-01
    • 2018-08-27
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多