Lesson 89 of 93 · 6 min read · Updated
Resetting Database State Between Tests with Respawn and Testcontainers
On this page
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
- .NET 11 SDK
- Docker
Respawn7.0.0 (Apache-2.0)Testcontainers.PostgreSql4.17.0 andNpgsql- xUnit 2.9.3 and FluentAssertions 7.2.2
Three Ways to Get a Clean Database
| Option | Speed | Maintenance |
|---|---|---|
| A new container per test | Slowest | None, but the suite takes minutes |
Hand-written TRUNCATE | Fast | You update the SQL for every new table |
| Respawn | Fast | Finds 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
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
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
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
The Measured Difference: Identity Counters
The fixture also keeps a hand-written alternative for comparison:
M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs
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
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
- A shared container needs a deterministic reset before every test; Respawn does this without touching the schema.
- Create the respawner once, after
MigrateAsync(), and exclude__EFMigrationsHistory. - Reset before each test so a failed test's data is still there for debugging.
- By default Respawn 7 does not restart identity sequences;
TRUNCATE ... RESTART IDENTITYdoes, but needs manual upkeep. - Never rely on generated ids such as
Id == 1; query by a business key the test controls.