【发布时间】:2021-09-24 17:06:31
【问题描述】:
我使用 XUnit 和 WebApplicationFactory<Startup> 类为我的 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 以使其相互配合?还是在启动时迁移完全是个坏主意?
【问题讨论】:
-
是的...不要并行运行测试。
-
你用的是什么版本的.net core,可以看这篇文章,有很好的例子和解释,可能对你有帮助:andrewlock.net/converting-integration-tests-to-net-core-3/
-
@Chaodeng 你的超链接出了点问题。 andrewlock.net/converting-integration-tests-to-net-core-3
标签: c# asp.net-core testing entity-framework-core integration-testing