Lesson 89 of 93 · 6 min read · Updated

Resetting Database State Between Tests with Respawn and Testcontainers

A shared database container is fast, but it is dirty: a row one test writes is still there when the next test starts. To keep tests independent, the database must return to a known state before every test. This lesson shows how to do that with Respawn, compares it with a hand-written TRUNCATE, and shows one measured difference between the two that can break tests in a quiet way.

Technical Requirements

  1. .NET 11 SDK
  2. Docker
  3. Respawn 7.0.0 (Apache-2.0)
  4. Testcontainers.PostgreSql 4.17.0 and Npgsql
  5. xUnit 2.9.3 and FluentAssertions 7.2.2

Three Ways to Get a Clean Database

OptionSpeedMaintenance
A new container per testSlowestNone, but the suite takes minutes
Hand-written TRUNCATEFastYou update the SQL for every new table
RespawnFastFinds the tables and the foreign key order itself

Respawn connects to the database, reads the schema, and works out which tables to clear and in which order, so foreign keys never block a delete. It removes rows only; the schema stays as it is.

Setting Up Respawn Once per Fixture

The respawner is created in the fixture's InitializeAsync, after the migrations have run. At that point the schema exists, and Respawn can inspect it once and cache the result.

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

// The Respawner is created AFTER the MIGRATIONS, ONCE per fixture.
// The schema is ready now; Respawn works out which tables to clear and in
// which order. The migration history table must NEVER be deleted, otherwise EF
// tries to rebuild the schema on the next MigrateAsync.
_respawnConnection = new NpgsqlConnection(PostgresConnectionString);
await _respawnConnection.OpenAsync();

_respawner = await Respawner.CreateAsync(_respawnConnection, new RespawnerOptions
{
DbAdapter = DbAdapter.Postgres,
SchemasToInclude = ["public"],
TablesToIgnore = ["__EFMigrationsHistory"],
});
public Task ResetDatabaseAsync() => _respawner.ResetAsync(_respawnConnection);

Three options matter here. DbAdapter.Postgres tells Respawn which SQL dialect to generate. SchemasToInclude limits it to the application's schema. TablesToIgnore protects the EF Core migration history.

Pitfall: creating the respawner before MigrateAsync(). Respawn reads the table list when it is created, so it would see an empty database. Respawn 7 then stops with "No tables found. Ensure your target database has at least one non-ignored table to reset." If you see this message, check the order of the steps in the fixture.

Each test class calls the reset before every test from its own IAsyncLifetime.InitializeAsync:

M10.ContainerApi.Tests/RespawnResetTests.cs

[Collection(InfrastructureCollection.Name)]
public class RespawnResetTests(InfrastructureFixture fixture) : IAsyncLifetime
{
public Task InitializeAsync() => fixture.ResetDatabaseAsync();

public Task DisposeAsync() => Task.CompletedTask;

Resetting before the test, not after it, has a practical benefit. If a test fails, its data stays in the database until the next test starts, so you can still inspect it while debugging. It also protects each test from whatever an earlier test left behind, even if that test crashed halfway.

The same idea applies to the other shared resource in the fixture. Redis is reset with FLUSHDB, which is why the connection was opened with AllowAdmin = true:

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

/// <summary>Resets Redis.</summary>
public async Task ResetCacheAsync()
{
var endpoint = Redis.GetEndPoints().First();
await Redis.GetServer(endpoint).FlushDatabaseAsync();
}

The cache test class calls both ResetDatabaseAsync() and ResetCacheAsync() in its InitializeAsync, so a cached ticket from one test can never answer a query in the next.

Testing the Reset Itself

The reset is part of your test infrastructure, and it deserves tests of its own. The first two check that rows are deleted and the schema is kept:

M10.ContainerApi.Tests/RespawnResetTests.cs

[Fact]
public async Task Respawn_DeletesAllRows()
{
// Arrange
await using (var db = fixture.CreateDbContext())
{
db.Tickets.AddRange(NewTicket("DST-5001"), NewTicket("DST-5002"));
await db.SaveChangesAsync();
}

// Act
await fixture.ResetDatabaseAsync();

// Assert
await using var check = fixture.CreateDbContext();
(await check.Tickets.CountAsync()).Should().Be(0);
}

[Fact]
public async Task Respawn_KeepsSchemaAndMigrationHistory()
{
// Act
await fixture.ResetDatabaseAsync();

// Assert: the migration history is kept thanks to TablesToIgnore.
// If it were deleted, EF would think the schema was never created and retry the migrations.
await using var db = fixture.CreateDbContext();
(await db.Database.GetAppliedMigrationsAsync()).Should().NotBeEmpty();
(await db.Database.GetPendingMigrationsAsync()).Should().BeEmpty();
}

The Measured Difference: Identity Counters

The fixture also keeps a hand-written alternative for comparison:

M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs

public async Task TruncateDatabaseAsync()
{
await using var db = CreateDbContext();
await db.Database.ExecuteSqlRawAsync("TRUNCATE TABLE tickets RESTART IDENTITY CASCADE;");
}

RESTART IDENTITY resets the table's identity sequence to 1, and CASCADE also clears tables that reference tickets. Respawn 7 removes the rows with DELETE statements in foreign key order, and a DELETE never touches the sequence. The next insert continues from the last value. A separate test, Truncate_RestartsIdentitySequence, checks that the manual alternative really restarts the counter, so the comparison below starts from a known value. This test proves the difference on a real PostgreSQL server:

M10.ContainerApi.Tests/RespawnResetTests.cs

[Fact]
public async Task Respawn_DoesNotRestartIdentity_WhileTruncateRestartIdentityDoes()
{
// Arrange: a clean start, so the identity counter begins at 1.
await fixture.TruncateDatabaseAsync();
int firstId;
await using (var db = fixture.CreateDbContext())
{
var ticket = NewTicket("DST-5101");
db.Tickets.Add(ticket);
await db.SaveChangesAsync();
firstId = ticket.Id;
}

// Act 1: reset with Respawn and add a new row.
await fixture.ResetDatabaseAsync();
int idAfterRespawn;
await using (var db = fixture.CreateDbContext())
{
var ticket = NewTicket("DST-5102");
db.Tickets.Add(ticket);
await db.SaveChangesAsync();
idAfterRespawn = ticket.Id;
}

// Act 2: reset with TRUNCATE ... RESTART IDENTITY and add a new row.
await fixture.TruncateDatabaseAsync();
int idAfterTruncate;
await using (var db = fixture.CreateDbContext())
{
var ticket = NewTicket("DST-5103");
db.Tickets.Add(ticket);
await db.SaveChangesAsync();
idAfterTruncate = ticket.Id;
}

// Assert. LESSON: Respawn deletes the rows, but the counter continues where it left off.
// So tests must NOT rely on fixed ids such as "Id == 1";
// look rows up by the business key (Reference).
firstId.Should().Be(1);
idAfterRespawn.Should().Be(firstId + 1);
idAfterTruncate.Should().Be(1);
}

Common mistake: writing db.Tickets.Find(1) or asserting Id == 1 in a test. It passes when the test runs first, and fails when another test inserted a row earlier in the same run. The result depends on test order, which is the definition of a flaky test. Look rows up by the business key instead, here the Reference column, which the test controls.

So why use Respawn at all if TRUNCATE also resets identities? Because the TRUNCATE statement names every table. Each new table means another edit to that SQL, and a forgotten table leaks data between tests. Respawn finds new tables automatically. Respawn also has an opt-in WithReseed option, but this fixture keeps the default, because the safer habit is to not depend on ids at all. Choose Respawn for the reset and write tests that do not depend on generated ids.

Summary

  1. A shared container needs a deterministic reset before every test; Respawn does this without touching the schema.
  2. Create the respawner once, after MigrateAsync(), and exclude __EFMigrationsHistory.
  3. Reset before each test so a failed test's data is still there for debugging.
  4. By default Respawn 7 does not restart identity sequences; TRUNCATE ... RESTART IDENTITY does, but needs manual upkeep.
  5. Never rely on generated ids such as Id == 1; query by a business key the test controls.