Lesson 88 of 93 · 5 min read · Updated

Migrations as Part of the Test: Applying EF Core Migrations in a Testcontainers Fixture

A test database has to get its schema from somewhere. The quick option is EnsureCreated(), which builds the tables straight from the current EF Core model. It works, but it skips the path your production database actually takes: the migrations. This lesson shows how to apply real migrations inside the container fixture, how to check them with a test, and how to keep seed data small.

Technical Requirements

  1. .NET 11 SDK
  2. Docker
  3. Testcontainers.PostgreSql 4.17.0
  4. Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3 and Microsoft.EntityFrameworkCore.Design 10.0.15
  5. The dotnet-ef tool, installed as a local tool with dotnet tool restore
  6. xUnit 2.9.3 and FluentAssertions 7.2.2

Apply Migrations, Not EnsureCreated

The fixture applies the migrations right after the PostgreSQL container starts:

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

// APPLY THE MIGRATIONS.
// We use Migrate, NOT EnsureCreated: this way the tests also verify
// the DEPLOYMENT PATH. An incompatible schema change fails right here.
await using var db = CreateDbContext();
await db.Database.MigrateAsync();

The difference between the two calls matters more than it looks:

EnsureCreated()MigrateAsync()
Schema sourceThe current model snapshotThe migration files in the repository
Writes __EFMigrationsHistoryNoYes
Catches a missing or broken migrationNoYes
Matches how production is deployedNoYes

Common mistake: a developer changes the entity, forgets to add a migration, and runs the tests. With EnsureCreated() every test passes, because the tables are built from the new model directly. The deployment then fails, or worse, the production schema silently differs from what the code expects. With MigrateAsync(), the test database is built exactly the way production will be, so the gap shows up in the test run. Since EF Core 9, MigrateAsync() also throws when the model has changes that no migration covers, so the failure points straight at the cause.

Here is the migration the fixture applies. It was generated by dotnet-ef from the TicketDbContext model and contains PostgreSQL-specific types:

M10.ContainerApi/Data/Migrations/20260906221047_InitialCreate.cs

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "tickets",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Reference = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false),
Subject = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
CustomerEmail = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
Priority = table.Column<int>(type: "integer", nullable: false),
CreatedAt = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
Tags = table.Column<List<string>>(type: "text[]", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_tickets", x => x.Id);
});

migrationBuilder.CreateIndex(
name: "IX_tickets_Reference",
table: "tickets",
column: "Reference",
unique: true);
}

The text[] column, the timestamp with time zone column and the identity column only work on PostgreSQL. Running this migration against SQLite would fail, which is one more reason the tests need the real engine.

A Test That Guards the Schema

Applying migrations in the fixture already fails the whole run if a migration throws. One small test makes the intent explicit and checks a second condition: nothing is left pending.

M10.ContainerApi.Tests/PostgresBehaviourTests.cs

[Fact]
public async Task Migrations_CreateTheExpectedSchema()
{
// Were the migrations really applied?
// This test catches a "the schema change is broken" bug EARLY in CI.
await using var db = fixture.CreateDbContext();

var applied = await db.Database.GetAppliedMigrationsAsync();

applied.Should().NotBeEmpty();
(await db.Database.GetPendingMigrationsAsync()).Should().BeEmpty();
}

GetAppliedMigrationsAsync() reads the __EFMigrationsHistory table in the container. GetPendingMigrationsAsync() compares that table with the migrations compiled into the assembly. If someone adds a migration file that the fixture did not apply, this test fails with a clear name instead of a confusing error in some unrelated query test.

This is also why the database reset must never delete the history table. The reset is configured with TablesToIgnore = ["__EFMigrationsHistory"]. If the history were wiped, EF Core would believe no migration had ever run, and the next MigrateAsync() would try to create tables that already exist.

Generating Migrations

Migrations are created with the dotnet-ef tool, which is pinned as a local tool in .config/dotnet-tools.json. After a model change, run this from the folder that contains the module:

dotnet dotnet-ef migrations add YeniMigration \
--project Modul10-Testcontainers/M10.ContainerApi/M10.ContainerApi.csproj \
--output-dir Data/Migrations

The next test run applies the new migration to a fresh container automatically. You do not need a shared development database, and you do not need to reset anything by hand: every run starts from an empty PostgreSQL and replays the full migration history.

Seed Only Reference and Scenario Data

The fixture has a hook for seed data, and in this example it is intentionally empty:

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

/// <summary>
/// "Load ONLY REFERENCE and SCENARIO data".
/// Loading a copy of the production database makes tests slow and hard to understand.
/// </summary>
private Task SeedReferenceDataAsync() => Task.CompletedTask;

There are two kinds of test data. Reference data is the small, stable set the application needs to work at all, such as a list of countries or ticket categories. It belongs in the fixture, or better in a migration. Scenario data is what a single test is about, such as "two tickets, one tagged as urgent". It belongs in the test itself, in the Arrange step, where a reader can see it.

Pitfall: restoring a dump of production data into the test container. The suite becomes slow, the data contains personal information, and no reader can tell which rows a test depends on. When a test fails, you cannot see why from the test alone.

Summary

  1. Use MigrateAsync() in the fixture so the tests exercise the same deployment path as production.
  2. EnsureCreated() hides missing or broken migrations because it builds the schema from the current model.
  3. A small test with GetAppliedMigrationsAsync() and GetPendingMigrationsAsync() guards the schema in CI.
  4. Never delete __EFMigrationsHistory during a reset.
  5. Seed only reference data in the fixture; put scenario data in the test's Arrange step.