【发布时间】:2018-04-01 17:32:27
【问题描述】:
我想在每个单元测试中创建干净的内存数据库。 当我运行多个测试时,以前测试的数据仍保留在数据库中。如何处置现有的内存数据库?
我使用以下代码初始化每个测试:
[TestInitialize]
public void TestInitialize()
{
Services = new ServiceCollection();
Services.AddScoped<DbContextOptions<MyDbContext>>(sp => new DbContextOptionsBuilder<TacsDbContext>()
.UseInMemoryDatabase("MyTestDbContext")
.Options);
Services.AddTransient<InMemoryMyDbContext>();
Services.AddTransient<MyDbContext>(sp => sp.GetService<InMemoryTacsDbContext>());
ServiceProvider = Services.BuildServiceProvider();
}
[TestMethod]
public void Test1()
{
using (var dbContext = ServiceProvider.GetService<MyDbContext>()) ...
}
[TestMethod]
public void Test2()
{
using (var dbContext = ServiceProvider.GetService<MyDbContext>()) ...
}
我使用 .NET Core 2.0 和 Entity Framework Core 2.0
编辑
我无法使用标准注册:Services.AddDbContext<InMemoryMyDbContext>(...),因为
public class InMemoryMyDbContext : MyDbContext
{
public InMemoryMyDbContext(DbContextOptions<InMemoryMyDbContext> options)
: base(options) { } //compiler error
public InMemoryMyDbContext(DbContextOptions<MyDbContext> options)
: base(options) { } //runtime IoC error
}
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options) { }
}
【问题讨论】:
-
你真的需要所有的 DI 包装吗?为什么不在你的测试函数中调用
new MyDbContext。 -
我确实做到了。我的测试更复杂,我在集成测试中使用这种方法。此外,我使用 IoC 作为auto mocking container
标签: entity-framework unit-testing dependency-injection .net-core entity-framework-core