内存中的EF Core SQLite DB未重置



我有一个使用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,。。

可能是什么问题?

对于其他有此问题的人:

我有一些被声明为静态的种子对象。这使数据库在多次测试中保持活动状态。因此,请确保所有种子行都是新实例。

最新更新