【发布时间】: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<IAppMarker>, IAsyncLifetime。在 AppFactory 的 InitializeAsync 中,我为数据库播种。但是,当超过 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