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

How to ensure that Entity Framework Core InMemory database is created per test method?

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

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();


            }
        });
    }
}

i think they shared the same database instance

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

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

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