【问题标题】:Running Migrations in Startup.cs not working with tests using WebApplicationFactory<Startup>在 Startup.cs 中运行迁移不适用于使用 WebApplicationFactory<Startup> 的测试
【发布时间】:2021-09-24 17:06:31
【问题描述】:

我使用 XUnit 和 WebApplicationFactory&lt;Startup&gt; 类为我的 ASP .NET Core 应用程序编写了一些集成测试。在花了很长时间弄清楚为什么我在第一次运行时会得到很多SqlServerExceptions(即当数据库还不存在时),我发现问题是在我的Startup.cs 中运行context.Database.Migrate()在工厂里表现不佳。我认为这可能是因为并行运行的测试和竞争条件导致两个工厂认为还没有数据库并尝试运行相同的迁移。

我收到如下错误:

Microsoft.Data.SqlClient.SqlException : Database 'MyApplicationDB' already exists. Choose a different database name.
...
Microsoft.Data.SqlClient.SqlException : There is already an object named 'AspNetRoles' in the database.
...
Microsoft.Data.SqlClient.SqlException : There is already an object named '__EFMigrationsHistory' in the database.

等等

我已经“解决”了这个问题,方法是在启动时删除迁移步骤,而是使用dotnet cli 运行迁移并运行dotnet test

我的问题:当Startup 类中有迁移步骤时,有没有办法配置WebApplicationFactorys 以使其相互配合?还是在启动时迁移完全是个坏主意?

【问题讨论】:

标签: c# asp.net-core testing entity-framework-core integration-testing


【解决方案1】:

也许您可以使用InMemoryDatabase? 在这种情况下,您可以在派生的WebApplicationFactory 中执行类似的操作:

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    builder.ConfigureServices(services =>
    {
        services.AddDbContext<IdentityContext>(o =>
        {
            // Make sure that every test has its own database to prevent concurrency issues in tests.
            var inMemoryDbName = Guid.NewGuid().ToString();
            o.UseInMemoryDatabase(inMemoryDbName);
        });
    });
}

【讨论】:

  • 谢谢,有机会我会试试看的。
猜你喜欢
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 2018-01-06
  • 2017-04-05
  • 2013-06-22
  • 2022-06-16
  • 1970-01-01
  • 2012-11-21
相关资源
最近更新 更多