在 ASP.NET Core WebApplicationFactory 中覆盖 EF Core DbContext

Override EF Core DbContext in ASP.NET Core WebApplicationFactory

我有一个 ASP.NET Core 2.2 WebApi 项目,它也使用 EF Core 2.2。该项目通过 WebApplicationFactory<T>.

的集成测试进行测试

我尝试将 Web api 项目迁移到 netcore/aspnetcore 3,效果非常好。我偶然发现的是迁移测试。

我有以下在 aspnetcore 2.2 中工作的代码:

    public class MyServiceWebHostFactory : WebApplicationFactory<Service.Startup>
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {   
            builder.ConfigureServices(services =>
            {
                var serviceProvider = new ServiceCollection()
                                   .AddEntityFrameworkInMemoryDatabase()
                                   .BuildServiceProvider();

                services.AddDbContext<MyContext>((options, context) =>
                {
                    context.UseInMemoryDatabase("MyDb")
                           .UseInternalServiceProvider(serviceProvider);
                });

                var sp = services.BuildServiceProvider();

                using var scope = sp.CreateScope();

                var scopedServices = scope.ServiceProvider;

                // try to receive context with inmemory provider:
                var db = scopedServices.GetRequiredService<MyContext>();

                // more code...

                // Ensure the database is created.
                //db.Database.EnsureCreated();

                // more code...
            });
        }
    }

它使用 InMemoryProvider 将 EF Core DbContext 替换为 DbContext。

迁移到 3.0 后,它不再被替换。我总是收到配置了 SQL 服务器的 DBContext。

如果我在应用程序 (Service.Startup) 的 ConfigureServices 中删除 services.AddDbContext<MyContext>(options => options.UseSqlServer(connectionString)) 调用,它可以工作,但这不是解决方案。

我在注册内存上下文之前也尝试了 services.RemoveAll(typeof(MyContext)),但它也不起作用。

https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1 上的更新文档可能会有所帮助。关键片段改动是去掉之前的上下文服务注册:

// Remove the app's ApplicationDbContext registration.
var descriptor = services.SingleOrDefault(
    d => d.ServiceType ==
        typeof(DbContextOptions<ApplicationDbContext>));

if (descriptor != null)
{
    services.Remove(descriptor);
}

// Add ApplicationDbContext using an in-memory database for testing.
services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseInMemoryDatabase("InMemoryDbForTesting");
});

// Build the service provider.
var sp = services.BuildServiceProvider();