Lesson 10 of 93 · 6 min read · Updated
The xUnit Test Lifecycle: Constructor, IDisposable and IAsyncLifetime
On this page
NUnit and MSTest use attributes such as [SetUp] and [TearDown] to run code before and after each test. xUnit has none of these. Instead, it creates a new instance of the test class for every test, so plain C# features do the job: the constructor for setup, IDisposable for cleanup and IAsyncLifetime for asynchronous work. This lesson shows each one and proves that tests cannot leak state into each other through instance fields.
Technical Requirements
- .NET 11 SDK
- xunit 2.9.3 (with xunit.runner.visualstudio and Microsoft.NET.Test.Sdk)
A New Instance for Every Test
The test class below has an instance field _counter. Two tests increment it, and both assert that the value is 1. If the tests shared one object, the second test to run would see 2 and fail. Both tests pass.
M02.XUnitBasics.Tests/LifecycleTests.cs
For each test, xUnit does the same three steps:
- Call the constructor to create a new
LifecycleTestsobject. - Run one test method on that object.
- Call
Dispose()on that object if the class implementsIDisposable.
Then the object is thrown away. The next test gets its own object with its own _counter. The line _counter = 0; in the constructor is not strictly needed, because a new int field is already zero. It is there to show where setup code goes.
This design is deliberate. With a shared instance, a test that forgets to reset a field can make an unrelated test pass or fail depending on the order the runner picks. Those bugs are hard to find because each test passes when you run it alone. xUnit removes that class of problem by default.
The Constructor and Dispose
Use the constructor for setup that every test in the class needs, such as creating the object under test or a fake dependency. Store the result in a private readonly field. Use Dispose() to release anything that the constructor opened, such as a temporary file or a stream.
Keep the constructor small. If a reader has to scroll up to the constructor to understand why a test expects a certain value, that value belongs in the test itself. Shared setup is for plumbing, not for the inputs that decide the result.
The Pitfall: Static State
A new instance protects instance fields only. A static field lives as long as the test assembly and is shared by every test. The DisposeLog field above is static on purpose: it is the only way to collect a trace across several instances. That is also exactly why static fields are dangerous in real tests.
The same rule applies to static state in the code under test, such as a static cache or a singleton. xUnit cannot reset it for you. Also note that xUnit runs test classes in parallel by default, which is why the example uses a thread-safe ConcurrentBag<string> rather than a List<string>. If your tests touch shared static state, they will eventually interfere with each other. Prefer designs where that state is an injected dependency, so each test can create its own.
Asynchronous Setup with IAsyncLifetime
A constructor cannot be async, and Dispose() cannot await. When setup needs I/O, such as starting a container, running a database migration or opening a connection, implement IAsyncLifetime. xUnit awaits InitializeAsync() after the constructor and before the test, and awaits DisposeAsync() after the test.
M02.XUnitBasics.Tests/LifecycleTests.cs
The test sees "Open", which proves that the runner awaited InitializeAsync() before calling the test method. Avoid the common workaround of calling .Result or .Wait() on a task inside the constructor. It blocks a thread, can deadlock, and hides the real error inside an AggregateException.
This project uses xUnit 2.x, where both methods return Task. In xunit.v3 the interface changed: the methods return ValueTask and IAsyncLifetime extends IAsyncDisposable. The idea is the same, but you need to update the signatures when you migrate.
Per-test setup is the right default. When setup is expensive, such as a real database in a container, running it once per test becomes slow. xUnit has class and collection fixtures for sharing one setup across many tests. They are a separate topic, and you should only reach for them when per-test setup has a measurable cost.
Summary
- xUnit creates a new instance of the test class for every test, so instance fields never leak between tests.
- The constructor replaces
[SetUp], andIDisposable.Dispose()replaces[TearDown]. IAsyncLifetimegives you awaitedInitializeAsync()andDisposeAsync()for I/O-bound setup and cleanup.- Static fields and static state in the code under test are shared across all tests. Avoid them.
- In xunit.v3,
IAsyncLifetimemethods returnValueTaskinstead ofTask.