目前,我正在为ASP.NET Core WebAPI开发设置团队环境,结合使用xUnit进行单元测试以及GitLab CI。对于数据库通信,我们使用EF Core。
对于EF Core,我们将使用代码优先迁移,我们担心开发人员可能只会更新模型,而不会为模型更改创建迁移。因此,我们希望CI运行代码库中存在的所有迁移,将它们与代码优先模型的当前状态进行比较,并在代码优先模型状态与运行所有迁移所导致的状态不相等时失败。
有没有办法做到这一点?我在EF Core文档中找不到关于此的任何信息。
感谢@ErikEJ的示例代码,我能够编写出完全符合我想要的以下测试:
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Xunit;
/// <summary>
/// Contains a test that verifies that the
/// model does not contain any changes that are not included
/// in the migrations.
/// </summary>
public class NoPendingModelChangesTest
{
private static readonly string DummyConnectionString = @"Server=localhost;Database=DoesNotExist;Trusted_Connection=True;";
/// <summary>
/// Tests that the current model does not contain any changes
/// that are not contained in the database migrators.
/// In other words: tests that the current model state equals the
/// state that results from all the migrations combined.
/// </summary>
[Fact]
public void ModelDoesNotContainPendingChanges()
{
// Do not use the test database, the SQL Server model provider must be
// used as that is the model provider that is used for scaffolding migrations.
using var ctx = new MyDatabase(
new DbContextOptionsBuilder<MyDatabase>()
.UseSqlServer(DummyConnectionString)
.Options);
var modelDiffer = ctx.GetService<IMigrationsModelDiffer>();
var migrationsAssembly = ctx.GetService<IMigrationsAssembly>();
var pendingModelChanges = modelDiffer
.GetDifferences(
migrationsAssembly.ModelSnapshot?.Model,
ctx.Model);
pendingModelChanges
.Should()
.BeEmpty(
because:
"the current model state should be equal to the state that results from all the migrations combined (try scaffolding a migration)");
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句