📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you share an expensive resource, such as a database container, across many xUnit test classes without starting it once per test?

Sharing an expensive test resource (such as a SQL Server container) across xUnit test classes with IAsyncLifetime, class, collection and xUnit v3 assembly fixtures, and keeping tests independent with Respawn or unique keys.

Junior Theory Beginner integration-testing respawn test-fixtures testcontainers testing xunit

🎯 Key points

  • IAsyncLifetime: start-up awaited once in InitializeAsync, cleanup in DisposeAsync
  • IClassFixture<T> = one instance per test class
  • ICollectionFixture<T> + [CollectionDefinition] = one instance per collection; those classes run serially
  • xUnit v3 [assembly: AssemblyFixture] = one instance per assembly, tests still run in parallel, so the fixture must be thread-safe
  • Shared resource, not shared state: each test owns its data
  • Respawn deletes rows (keeps schema and __EFMigrationsHistory) between tests; or unique keys per test
  • Order-dependent tests are flaky tests waiting to happen

⏱ 30-second answer

Wrap the resource in a fixture that implements IAsyncLifetime, so the container starts once in InitializeAsync and is removed in DisposeAsync. Then pick the sharing scope:

  • IClassFixture<T>: one instance per test class.
  • ICollectionFixture<T> with [CollectionDefinition]: one instance for every class in the collection, and those classes run serially.
  • xUnit v3 assembly fixture ([assembly: AssemblyFixture(typeof(T))]): one instance for the whole run, with tests still running in parallel, so the fixture must be thread-safe.

Share the resource, not the state. Each test creates its own rows with unique keys, or you reset the database between tests with Respawn. Respawn is a small library that deletes data in foreign-key order and keeps the schema. The trade-off is that a wider scope gives a faster suite, but one test can leak data into another.

🗣 Full answer (senior)

How I would answer this in an interview

"Starting a SQL Server container takes something like 5 to 15 seconds, so starting one per test makes the suite unusable. In xUnit the answer is a fixture. I put the container in a class that implements IAsyncLifetime: InitializeAsync starts it and applies migrations, and DisposeAsync stops it. Then I choose how widely to share it.

IClassFixture<T> gives one instance per test class. ICollectionFixture<T> with a [CollectionDefinition] gives one instance for every class in that collection. xUnit runs collections in parallel but the classes inside one collection serially, so this also stops tests fighting over the same database. In xUnit v3 there is also the assembly fixture: one instance for the whole test assembly, injected into any class that asks for it, while tests keep running in parallel. That's the fastest option, but the fixture has to be thread-safe and tests must not step on each other's data.

The mistake I see is people sharing the state along with the resource: test B depends on rows test A inserted, so it passes in the IDE and fails in CI when the order changes. I share the container but every test owns its data. Either it uses unique keys, like a new Guid for the customer, or I reset with Respawn before each test. Respawn deletes rows from every table in foreign-key order but keeps the schema and the __EFMigrationsHistory table, and it's far quicker than recreating the database. So: share the expensive thing, isolate the cheap thing."


The fixture scopes in xUnit

Scope How you declare it Instances Parallelism
Per test Constructor + IAsyncLifetime on the test class One per test Normal
Per class IClassFixture<T> One per class Classes in parallel
Per collection [CollectionDefinition] + ICollectionFixture<T> + [Collection("name")] One per collection Classes in the collection run serially
Per assembly (v3) [assembly: AssemblyFixture(typeof(T))] One per run Tests still run in parallel

Keeping tests independent

Technique How it works When it fits
Unique keys Each test inserts its own rows (new Guid, unique email) and only queries those Parallel tests on one database; append-only data
Respawn Respawner.ResetAsync deletes all rows except ignored tables before each test Tests that count rows or need an empty table; serial collections
Transaction rollback Open a transaction, run the test, roll back Only when the code under test doesn't manage its own transactions or use several connections
Database per class Create a new database name per class in the same container Strong isolation without a second container

When not to share

If a test changes server-level settings (collation, a database setting, a schema migration test), give it its own container. Sharing only works when the tests treat the resource as a black box.

Production example

A typical integration suite of 300 tests that started one container per class (40 classes at about 8 s each) spends around 5 minutes just on start-up. Moving to one collection fixture plus a Respawn reset (about 30 to 50 ms per test) brings that overhead down to under 30 seconds.

🔍 What the interviewer is checking

Checks whether the candidate knows xUnit's fixture scopes and can trade isolation against speed without creating order-dependent tests.

Green flags

  • Names IAsyncLifetime and explains why a constructor won't do.
  • Knows that a collection makes its classes run serially.
  • Mentions xUnit v3 assembly fixtures and that they don't serialise tests.
  • Separates sharing the resource from sharing the data, and names Respawn or unique keys.

Red flags

  • Static fields or singletons with manual locking instead of fixtures.
  • Tests that depend on execution order.
  • Doesn't know xUnit creates a new class instance per test.

📚 Learn in depth

1. How xUnit creates and shares objects

xUnit creates a new instance of the test class for every test. That's deliberate: fields on the test class can't leak between tests. Anything that must live longer has to sit outside the test class, in a fixture that xUnit owns and injects through the constructor.

Test run
 └─ Assembly fixture (v3)             one instance, shared by everything
     └─ Test collection               runs in parallel with other collections
         ├─ Collection fixture        one instance for the collection
         └─ Test class                classes inside a collection run one after another
             ├─ Class fixture         one instance for the class
             └─ Test method           new test class instance per test

2. IAsyncLifetime

Constructors can't be async, and starting a container is I/O. IAsyncLifetime gives xUnit two hooks: InitializeAsync runs (and is awaited) before the first test that uses the fixture, and DisposeAsync runs after the last. In xUnit v3 both return ValueTask, and IAsyncLifetime extends IAsyncDisposable. In v2 they returned Task.

3. Collections and parallelism

By default every test class is its own collection, and collections run in parallel (up to the number of processor cores by default). Putting classes into one named collection does two things at once: they share the collection fixture, and they run serially. That is often exactly what you want for a database, because two classes truncating the same tables at once would break each other.

4. Assembly fixtures in xUnit v3

v3 added [assembly: AssemblyFixture(typeof(SqlServerFixture))]. Any test class can take SqlServerFixture in its constructor without being in a collection. It's created once per assembly and does not serialise anything, so it suits read-mostly resources, or tests that use unique keys. The fixture is shared state, so anything mutable on it (a counter, a cached HttpClient with changing headers) must be thread-safe.

5. What Respawn actually does

Respawn (Apache 2.0 licence) reads the database's foreign-key graph once, when you call Respawner.CreateAsync, and builds an ordered list of DELETE statements. ResetAsync runs that list. It doesn't drop tables or rerun migrations, which is why it takes milliseconds. Use TablesToIgnore to keep reference data and __EFMigrationsHistory.

6. Costs

Action Typical cost
Start a SQL Server container 5 to 15 s (cold image pull: minutes)
Apply EF Core migrations 0.5 to 3 s
Respawn reset 10 to 100 ms
Insert test rows Single-digit ms

Try it yourself

  1. Write a fixture that logs a line in InitializeAsync. Use it as a class fixture in two classes, then as a collection fixture, and count the log lines.
  2. Add Thread.Sleep(2000) to tests in two classes and time the run with and without a shared [Collection]. Watch parallelism disappear.
  3. Switch to an xUnit v3 assembly fixture and confirm the classes run in parallel again.
  4. Write two tests that both assert Customers.Count() == 1. Make them fail together, then fix them with Respawn and with unique keys.
  5. Measure a Respawn reset against EnsureDeletedAsync + MigrateAsync with a Stopwatch.

💻 Code

A collection fixture that starts SQL Server once, applies the schema and resets data before each test (xUnit v3, Testcontainers.MsSql, Respawn).

#nullable enable
using Microsoft.Data.SqlClient;
using Respawn;
using Testcontainers.MsSql;
using Xunit;

namespace Orders.IntegrationTests;

// One container for every class in the "SqlServer" collection.
public sealed class SqlServerFixture : IAsyncLifetime
{
    private readonly MsSqlContainer _container = new MsSqlBuilder()
        .WithImage("mcr.microsoft.com/mssql/server:2022-latest")
        .Build();

    private Respawner _respawner = null!;

    public string ConnectionString => _container.GetConnectionString();

    public async ValueTask InitializeAsync()
    {
        await _container.StartAsync();

        // Real projects apply EF Core migrations here; a table keeps the sample self-contained.
        await using var connection = new SqlConnection(ConnectionString);
        await connection.OpenAsync();
        await using var create = new SqlCommand(
            "CREATE TABLE Customers (Id uniqueidentifier PRIMARY KEY, Email nvarchar(200) NOT NULL)",
            connection);
        await create.ExecuteNonQueryAsync();

        // Respawn reads the FK graph once; ResetAsync then only runs DELETEs.
        _respawner = await Respawner.CreateAsync(ConnectionString, new RespawnerOptions
        {
            DbAdapter = DbAdapter.SqlServer,
            TablesToIgnore = ["__EFMigrationsHistory"]
        });
    }

    public Task ResetAsync() => _respawner.ResetAsync(ConnectionString);

    public async ValueTask DisposeAsync() => await _container.DisposeAsync();
}

[CollectionDefinition("SqlServer")]
public sealed class SqlServerCollection : ICollectionFixture<SqlServerFixture>;

[Collection("SqlServer")]
public sealed class CustomerTests(SqlServerFixture db) : IAsyncLifetime
{
    // Runs before every test: a clean database, same container.
    public async ValueTask InitializeAsync() => await db.ResetAsync();
    public ValueTask DisposeAsync() => ValueTask.CompletedTask;

    [Fact]
    public async Task Inserted_customer_is_the_only_row()
    {
        await using var connection = new SqlConnection(db.ConnectionString);
        await connection.OpenAsync(TestContext.Current.CancellationToken);

        await using (var insert = new SqlCommand(
            "INSERT INTO Customers (Id, Email) VALUES (@id, @email)", connection))
        {
            insert.Parameters.AddWithValue("@id", Guid.NewGuid());
            insert.Parameters.AddWithValue("@email", "[email protected]");
            await insert.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
        }

        await using var count = new SqlCommand("SELECT COUNT(*) FROM Customers", connection);
        var rows = (int)(await count.ExecuteScalarAsync(TestContext.Current.CancellationToken))!;

        Assert.Equal(1, rows); // Only true because ResetAsync ran first.
    }
}

The xUnit v3 alternative: one instance for the whole assembly, and no serialisation.

[assembly: Xunit.AssemblyFixture(typeof(Orders.IntegrationTests.SqlServerFixture))]
// Test classes then take SqlServerFixture in their constructor without [Collection].
// Tests run in parallel, so use unique keys instead of a global Respawn reset.

⚠ Common mistakes

  • Mistake: Starting the container in the test class constructor. Why it is wrong: xUnit creates a new test class instance per test, so you pay the 5 to 15 s start-up for every test. Instead: Move it into a class, collection or assembly fixture.
  • Mistake: Blocking on StartAsync().GetAwaiter().GetResult() in a constructor. Why it is wrong: It ties up a thread and hides start-up exceptions in confusing places. Instead: Implement IAsyncLifetime and await it in InitializeAsync.
  • Mistake: Writing tests that depend on rows another test inserted. Why it is wrong: xUnit doesn't promise an order, so they pass locally and fail in CI. Instead: Each test creates its own data, or resets with Respawn first.
  • Mistake: Using an assembly fixture and a global Respawn reset together. Why it is wrong: Tests run in parallel, so one test's reset deletes another's rows mid-test. Instead: Use a serial collection with Respawn, or parallel tests with unique keys.
  • Mistake: Putting every class into one giant collection. Why it is wrong: The whole integration suite runs serially and gets slow. Instead: Use a few collections, each with its own database or container, or use unique keys.
  • Mistake: Forgetting to ignore __EFMigrationsHistory in Respawn. Why it is wrong: The next migration run thinks the database is empty and fails on existing tables. Instead: Add it to TablesToIgnore.
  • Mistake: Putting mutable shared state (counters, cached tokens) on an assembly fixture without locking. Why it is wrong: Parallel tests race on it. Instead: Make the fixture immutable after initialisation, or thread-safe.

🏛 Senior insight: trade-offs

The real decision is isolation versus speed, and it's per suite, not per project. I default to one collection per bounded area, each with its own database in a shared container, and Respawn before each test. That gives serial safety inside an area and parallelism across areas. For read-heavy tests against reference data I use an xUnit v3 assembly fixture with no reset at all.

I measure it: the test explorer or the dotnet test TRX report shows time per class. If fixture start-up is more than about 20% of the suite time, widen the scope. If flaky failures appear after widening it, the tests share state and need unique keys.

Option When it fits Cost When not to
Class fixture Few classes, each with very different setup Start-up × number of classes More than a handful of classes need the same container
Collection fixture + Respawn Tests that count rows or need empty tables Serial within the collection; 10 to 100 ms per reset A huge collection becomes the slowest part of the build
Assembly fixture (v3) + unique keys Large suites; read-mostly or well-isolated data Fixture must be thread-safe; tests must filter by their own keys Tests that assert on table-wide counts or truncate
Container per test Tests that change server config or schema Seconds per test Anything else

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions a SQL Server container shared by API tests. Why: Checks they can wire the shared container into WebApplicationFactory and migrations.
    How to answer

    Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.

    Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.

    Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me