如何确保每个测试方法创建Entity Framework Core InMemory数据库?

问题描述 投票:0回答:1

亲爱的,我正在尝试创建集成测试,使用实体框架核心内存数据库提供程序测试我的API控制器。我根据official documentation guideline创建了配置我的服务的CustomWebApplicationFactory,包括我的数据库上下文,我在我的xunit测试类中使用了这个工厂作为IClassFixture,但我们的测试在并行运行时被破坏,因为我认为他们共享相同的数据库实例。这是我的配置

protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            // Create a new service provider.
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkInMemoryDatabase()
                .BuildServiceProvider();

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

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

            // Create a scope to obtain a reference to the database
            // context (ApplicationDbContext).
            using (var scope = sp.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db = scopedServices.GetRequiredService<ApplicationDbContext>();


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


            }
        });
    }
}
asp.net-core entity-framework-core integration-testing in-memory-database
1个回答
1
投票

我认为他们共享相同的数据库实例

你是对的,IClassFixture是跨多个测试的共享对象实例。

你可以做些什么来重用ConfigureWebHost而是使用测试类的构造函数。这样,所有测试都将运行配置,但不会共享对象实例。您可能还需要更改options.UseInMemoryDatabase("InMemoryDbForTesting");以使用随机内存中的数据库名称(例如options.UseInMemoryDatabase(Guid.NewGuid().ToString());

官方的xunit文档也可能有所帮助:https://xunit.net/docs/shared-context

© www.soinside.com 2019 - 2024. All rights reserved.