Lesson 87 of 93 · 5 min read · Updated
Async Fixture Lifecycle in xUnit: IAsyncLifetime and ICollectionFixture for Containers
On this page
Starting a container is asynchronous, and so is stopping it. A constructor cannot await, and IDisposable.Dispose cannot either, so a container fixture needs a different hook. xUnit provides IAsyncLifetime for this, and ICollectionFixture lets many test classes share one expensive fixture. This lesson shows how the two work together and what you trade when you share a container.
Technical Requirements
- .NET 11 SDK
- Docker
- xUnit 2.9.3
Testcontainers.PostgreSqlandTestcontainers.Redis4.17.0Respawn7.0.0 (used for the reset step)
IAsyncLifetime: Async Setup and Guaranteed Teardown
In xUnit 2.x, IAsyncLifetime has two methods: Task InitializeAsync() and Task DisposeAsync(). xUnit calls InitializeAsync after it creates the fixture and before any test uses it, and calls DisposeAsync when the fixture is no longer needed. In xUnit v3 the same interface returns ValueTask, but the idea is identical.
The fixture does all its async work in InitializeAsync: start the containers, connect to Redis, apply migrations and prepare the database reset.
M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs
The excerpt leaves out the field declarations for the two containers. The order in DisposeAsync is the reverse of the order in InitializeAsync. Client connections close first, then the containers stop. Closing a container while a connection is still open can produce noisy errors in the test output.
Why does disposal matter so much? On a laptop, a forgotten container wastes memory until you notice it. On a self-hosted CI agent that runs many builds a day, leaked containers pile up until the agent runs out of memory or ports. DisposeAsync together with WithCleanUp(true) on the builders makes sure the containers go away even when tests fail.
ICollectionFixture: One Container for Many Test Classes
A class fixture (IClassFixture<T>) is created once per test class. With three database test classes, that means three PostgreSQL containers. A collection fixture is created once per collection, and every class in the collection receives the same instance.
M10.ContainerApi.Tests/Infrastructure/InfrastructureFixture.cs
A test class joins the collection with the [Collection] attribute and receives the fixture through its constructor. Here it uses a primary constructor:
M10.ContainerApi.Tests/PostgresBehaviourTests.cs
Note that the test class also implements IAsyncLifetime. xUnit creates a new instance of the test class for every test, so this InitializeAsync runs before each test. That is where the shared database is reset. The fixture's InitializeAsync runs once for the whole collection; the test class's InitializeAsync runs once per test.
| Hook | Runs | Used for |
|---|---|---|
InfrastructureFixture.InitializeAsync | Once per collection | Start containers, migrate, build the Respawner |
Test class InitializeAsync | Before every test | Reset database rows (and the cache) |
Test class DisposeAsync | After every test | Nothing here |
InfrastructureFixture.DisposeAsync | Once, after the last test | Close connections, remove containers |
Choosing the Lifecycle Scope
There are three common ways to scope a container. They trade isolation against cost:
| Scope | Isolation | Cost |
|---|---|---|
| A new container per test | Strongest | Very slow |
| Collection fixture plus reset (this example) | Depends on the reset | Reasonable |
| One container per suite, no reset | Tests pollute each other | Fastest |
A new container per test gives perfect isolation, but a PostgreSQL start costs a few seconds, and fifty tests would cost minutes. A shared container without a reset is fast, but a row written by one test leaks into the next, and the results start to depend on the order the tests run in. The middle option keeps one container and makes isolation explicit with a deterministic reset before each test.
Pitfall: the shared collection has a real cost. xUnit runs the classes of one collection one after another, not in parallel. That is the correct behaviour here, because the classes share one database and would otherwise reset it while another class is using it. But it means you should not put unrelated tests into this collection just for convenience. Tests that do not touch the shared database belong in their own classes outside it, where they can still run in parallel.
Summary
- Use
IAsyncLifetimefor container fixtures: constructors andDisposecannot await. - Dispose in reverse order and make cleanup unconditional; leaked containers break CI agents.
ICollectionFixtureshares one container across many test classes;IClassFixturecreates one per class.- The test class's own
InitializeAsyncruns before every test and is the place for the reset. - A shared collection runs its classes sequentially; keep only tests that need the shared resource in it.