Wor*_*hy7 5 entity-framework-core .net-core
在开发 .net 应用程序时,我们会定期更改模型,并且可能会简单地运行内存中动态创建的数据库的单元测试。
一切都可以正常工作,一切都很好,然后我们进行部署,突然一切都停止工作,因为我们忘记了我们需要迁移数据库。
如果模型已更改但没有针对该更改的迁移,我如何编写一个会失败的单元测试?
像这样
using MyProject.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Migrations.Design;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xunit;
namespace MyProject.Tests.Migrations
{
public class MissingMigrationsTest : MyProjectTestBase
{
/// <summary>
/// Sometimes we change the model, but forget to create a migration for it (with dotnet ef migrations add)
/// We do this test to detect a missing migration.
/// </summary>
/// <returns></returns>
[Fact]
public async Task ShouldCreateABlankMigration()
{
var db = new MyProjectDbContextFactory();
// Create design-time services
var serviceCollection = new ServiceCollection();
serviceCollection.AddEntityFrameworkDesignTimeServices();
serviceCollection.AddDbContextDesignTimeServices(db);
var serviceProvider = serviceCollection.BuildServiceProvider();
// Create a migration
var migrationsScaffolder = serviceProvider.GetService<IMigrationsScaffolder>();
Microsoft.EntityFrameworkCore.Migrations.Design.ScaffoldedMigration migration = migrationsScaffolder.ScaffoldMigration("test", "MyProject");
var rs = Regex.Replace(migration.MigrationCode, @"\s+", string.Empty);
//crude but, lets just remove all whitespace, and then check it has a blank Up() function
rs.Contains("Up(MigrationBuildermigrationBuilder){}").ShouldBeTrue();
}
}
}
Run Code Online (Sandbox Code Playgroud)
感谢:https: //learn.microsoft.com/nl-be/ef/core/cli/services#using-services 和正则表达式。
| 归档时间: |
|
| 查看次数: |
976 次 |
| 最近记录: |