Xav*_*ohn 1 c# integration-testing entity-framework asp.net-core
场景是.net core 5 Web API,Startup.cs的ConfigureServices中使用services.AddDbContext添加SQL server。测试使用MVC测试提供的WebApplicationFactory,我想用InMemory替换DbContext或指向测试数据库。
我尝试在 WebApplicationFactoryConfigureWebHost 中删除它,但 SQL DbContext 上有一些东西,因为当测试运行时,它会访问 SQL 服务器而不是 InMemory 数据库,即使 SQL DbContext 不存在于 DI 中。
builder.ConfigureTestServices(
services =>
{
var serviceDescriptor = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(DbContext));
if (serviceDescriptor != null)
{
services.Remove(serviceDescriptor);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有正确的方法来替换测试项目中Startup.cs中添加的DbContext?
找到了解决方案。您必须删除从 DbContext 派生的类和所有 DbContextOptions。
例子
services =>
{
var context = services.FirstOrDefault(descriptor => descriptor.ServiceType == typeof(MyDbContext));
if (context != null)
{
services.Remove(context);
var options = services.Where(r => (r.ServiceType == typeof(DbContextOptions))
|| (r.ServiceType.IsGenericType && r.ServiceType.GetGenericTypeDefinition() == typeof(DbContextOptions<>))).ToArray();
foreach (var option in options)
{
services.Remove(option);
}
}
services.AddDbContext<MyDbContext>(opt => opt.UseInMemoryDatabase(@"TestDB"));
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1427 次 |
最近记录: |