skip to content

With Respawn 7, how do you reset a Testcontainers PostgreSQL database between ASP.NET Core integration tests, and what does ResetAsync actually run?

level: seniorimportance: should knowfreq 38%

answer

  1. build the plan once, run it per test
  2. Respawner.CreateAsync after migrations
  3. ResetAsync takes an open DbConnection
  4. TablesToIgnore: __EFMigrationsHistory
  5. WithReseed defaults to false

basics

~20 s

After migrations, call Respawner.CreateAsync(openConnection, options) once; it reads the tables and foreign keys and builds a delete script. Before each test, ResetAsync(connection) runs it: one TRUNCATE ... CASCADE on PostgreSQL, ordered DELETEs on SQL Server.

solid answer

~40 s

Respawn clears rows, not schema. Once the container is migrated, I open an `NpgsqlConnection` and call `Respawner.CreateAsync(connection, new RespawnerOptions { ... })`. It queries `INFORMATION_SCHEMA` for base tables and foreign keys, orders them, and caches the SQL; it throws `InvalidOperationException` if no tables exist yet, so it must run after `MigrateAsync`. Before each test I call `ResetAsync(connection)` with an open connection, which runs the script in one transaction. On PostgreSQL that is a single `truncate table ... cascade`; on SQL Server it is a `DELETE` per table in foreign-key order. I set `SchemasToInclude = ["public"]`, put `__EFMigrationsHistory` and any reference-data tables in `TablesToIgnore`, and turn on `WithReseed` only if a test depends on identity values starting again. Respawn 7 has no `ResetAsync(string)` overload, whatever the README shows.

code

csharp · 21 lines
csharp
private Respawner _respawner = default!;

private async Task CreateRespawnerAsync()          // end of InitializeAsync, after MigrateAsync
{
    await using var conn = new NpgsqlConnection(_db.GetConnectionString());
    await conn.OpenAsync();
    _respawner = await Respawner.CreateAsync(conn, new RespawnerOptions
    {
        DbAdapter = DbAdapter.Postgres,
        SchemasToInclude = ["public"],
        TablesToIgnore = [new Table("__EFMigrationsHistory"), new Table("order_statuses")],
        WithReseed = true
    });
}

public async Task ResetDatabaseAsync()
{
    await using var conn = new NpgsqlConnection(_db.GetConnectionString());
    await conn.OpenAsync();
    await _respawner.ResetAsync(conn);
}

go deeper

for a junior

Remember the two calls: CreateAsync once with an open connection after migrations, then ResetAsync with an open connection before each test.

for a middle

Explain what the plan contains: tables and foreign keys read from INFORMATION_SCHEMA, turned into TRUNCATE CASCADE on PostgreSQL or ordered DELETEs on SQL Server, with identity values left alone by default.

for a senior

Show the production-grade setup: ignore __EFMigrationsHistory and seeded lookup tables, reset before rather than after, and keep classes that share a container from resetting under each other.

for a principal

Compare reset strategies across a large suite, Respawn against per-test transactions or a database per parallel worker, by run time, isolation and what each lets the app do.

## The problem Respawn solves One PostgreSQL container is shared by every test in a fixture, so whatever a test writes is still there for the next one. Dropping and re-migrating the database before each test is correct but slow. **Respawn** (`Respawn` on NuGet, version 7.0) deletes the **rows** and leaves the **schema** in place, in an order that respects foreign keys, so each test starts from an empty, migrated database. ## Two calls: plan once, run often 1. **`Respawner.CreateAsync(DbConnection connection, RespawnerOptions? options)`** is a static factory. It needs an **open** connection. It reads the base tables and the foreign-key relationships from `INFORMATION_SCHEMA`, builds a graph, and stores the generated SQL in the respawner's `DeleteSql` property (and `ReseedSql` when reseeding is on). This is the expensive part and happens once per fixture. 2. **`ResetAsync(DbConnection connection)`** runs that cached SQL inside a transaction on the connection you pass, which must also be open. Because the plan is built from the live schema, `CreateAsync` must run **after migrations**. Against an empty database it throws `InvalidOperationException` with the message that no tables were found. A table created after the respawner was built is not in its plan. ## What actually runs The adapter is inferred from the connection's type name (`NpgsqlConnection` gives the PostgreSQL adapter, `SqlConnection` the SQL Server one) or set explicitly with `DbAdapter = DbAdapter.Postgres`. | | PostgreSQL adapter | SQL Server adapter | |---|---|---| | Statement | one `truncate table a, b, c cascade;` | one `DELETE` per table, children first | | Cycles in foreign keys | triggers disabled on those tables around the statement | `NOCHECK CONSTRAINT ALL` on those tables | | Identity values | keep counting unless `WithReseed = true` | keep counting unless `WithReseed = true` | The README describes deleting rather than truncating, but the PostgreSQL adapter in the 7.0 source emits `TRUNCATE ... CASCADE`, which is why it is fast there. ## Options that matter - **`TablesToIgnore`** (`Table[]`): Respawn includes every base table it finds, including EF Core's `__EFMigrationsHistory`. Ignore it, and ignore lookup tables that migrations seed, or the next test sees no order statuses. A `Table` converts implicitly from a string, and `new Table("schema", "name")` qualifies it. - **`SchemasToInclude` / `SchemasToExclude`**: limit the reset to the app's schemas, for example `public`. - **`WithReseed`** (default `false`): restarts identity columns and sequences. Without it, a test asserting that the first order has id 1 passes alone and fails after another test ran. - **`CheckTemporalTables`** (default `false`): on SQL Server, switches system versioning off around the reset so history tables can be cleared. - **`CommandTimeout`**: for a large schema whose reset takes longer than the provider's default. ## Wiring it into the fixture The factory that owns the container builds the respawner at the end of its `InitializeAsync` and exposes a `ResetDatabaseAsync()` method that opens a connection and calls `ResetAsync`. Each test class calls that method in its own per-test setup, which in xunit.v3 is the test class's `InitializeAsync`. Reset **before** each test, not after: a test that crashed half-way, or a debugging session that stopped early, then cannot poison the next run. ## A version trap The README still shows `await respawner.ResetAsync("MyConnectionStringName")`. Respawn 7.0's `Respawner` has exactly one reset method, `ResetAsync(DbConnection)`, so that line does not compile; open a connection and pass it. ## A checklist for the order API 1. Start the container and run `Database.MigrateAsync()` in the fixture. 2. Open a connection and build the respawner with `SchemasToInclude = ["public"]` and `TablesToIgnore` naming `__EFMigrationsHistory` plus the seeded `order_statuses` table. 3. Decide on `WithReseed`: turn it on only if tests assert generated ids; better still, make tests read the id from the response. 4. Call the reset from every test class's per-test setup, before the test arranges its own data. 5. Keep classes that share the container in one xUnit collection, so no reset runs while another test is mid-flight. A reset on a small schema takes milliseconds, so the cost per test stays far below starting a container or re-running migrations.

  • Why is __EFMigrationsHistory worth ignoring if migrations already ran?
    Respawn clears every base table it finds, and EF Core records applied migrations in `__EFMigrationsHistory`. Clearing it does not drop the schema, but the database then claims no migrations were applied, so anything that calls `MigrateAsync()` again, such as a second factory or a start-up migration in the app, tries to create tables that exist and fails. Ignoring it keeps the database's own record correct.
  • Two test classes share one container and run in parallel. Is Respawn enough?
    No. Respawn empties the whole database, so one class's reset deletes rows another class is using at that moment. Either put every class that shares the container in one xUnit collection so they run one after another, give each parallel group its own container or its own database, or switch those tests to per-test rolled-back transactions.
  • Why does Respawn throw when the fixture creates it right after StartAsync?
    `CreateAsync` builds its plan from the tables it finds, and a freshly started container has none until migrations run. With nothing to reset it throws `InvalidOperationException` saying no tables were found. Create the respawner after `Database.MigrateAsync()` has completed.

  • Call await respawner.ResetAsync("Orders") with the connection string name.
  • Create the Respawner right after StartAsync, before migrations have run.
  • Respawn drops and recreates the schema, so migrations must run again after each reset.
  • Rebuild the Respawner with CreateAsync before every single test.
  • Identity values restart at 1 after ResetAsync without any option.
  • Reset only after each test, trusting the previous run finished cleanly.

Assumes Respawn 7.0 on .NET 10: Respawner.CreateAsync(DbConnection, RespawnerOptions) and ResetAsync(DbConnection) are the whole API, and the connection-string ResetAsync the README shows is not in the 7.0 source.