【发布时间】:2021-07-14 09:59:20
【问题描述】:
我有一个使用 EF Core 的项目,我正在尝试运行单元测试。目前他们在运行“所有测试”时失败,因为显然数据库在测试之间没有正确重置。
- 通常列表中的第一个测试成功
- 其他测试失败并出现以下错误:
- 唯一键约束失败(播种数据时...数据已存在)
- “创建”的行多于测试的预期(因为来自其他测试的其他行仍然存在)
- 当我手动运行测试时,它们都成功了。
我正在使用这段代码来创建测试中使用的上下文:
public class SampleDbContextFactory : IDisposable
{
private DbConnection _connection;
private DbContextOptions<SampleDbContext> CreateOptions()
{
return new DbContextOptionsBuilder<SampleDbContext>()
.UseSqlite(_connection).Options;
}
public SampleDbContext CreateContext()
{
if (_connection == null)
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
var options = CreateOptions();
using (var context = new SampleDbContext(options))
{
context.Database.EnsureCreated();
}
}
return new SampleDbContext(CreateOptions());
}
public void Dispose()
{
if (_connection != null)
{
_connection.Dispose();
_connection = null;
}
}
}
在测试中,我这样称呼它:
using (var factory = new SampleDbContextFactory())
{
using (var context = factory.CreateContext())
{
...
}
}
我已经尝试过将 _connection 设为静态,在 EnsureCreated 之前使用 EnsureDeleted,..
可能是什么问题?
【问题讨论】:
-
你在什么类型的项目中使用这个类?它是一个网络项目吗?如果是,您是否使用 WebApplicationFactory?如果是,您如何为每个测试重置数据库?
标签: sqlite unit-testing entity-framework-core