skip to content

In xUnit.net, why do you put per-test setup in the test class constructor and teardown in Dispose instead of attributes?

level: middleimportance: must knowfreq 66%

answer

  1. no setup or teardown attributes
  2. a new class instance for every test
  3. each theory row counts as a test
  4. IDisposable.Dispose after each test
  5. DisposeAsync wins when both exist

basics

~20 s

xUnit.net creates a new instance of the test class for every test, including each theory row, so the constructor is per-test setup and Dispose or DisposeAsync is per-test teardown. Instance fields start fresh for every test without any attributes.

solid answer

~50 s

xUnit.net has no `[SetUp]`/`[TearDown]` attributes because it does not need them: the runner builds a fresh instance of the test class for every test, and every theory row counts as a test. The constructor is the setup and `IDisposable.Dispose` the teardown; if the class implements `IAsyncDisposable`, the runner calls `DisposeAsync` instead, and only that one when both exist. The payoff is isolation: instance fields such as a calculator or a bracket table cannot leak from one test to the next, and `readonly` fields make the setup explicit. Anything `static` is still shared. Rules to know: the class may define only one public constructor, its parameters can only be supplied by xUnit.net itself (fixtures and framework services such as `ITestOutputHelper`), a constructor exception fails that test and skips `Dispose`, and a constructor cannot `await`, so async setup needs a different hook. Expensive setup repeated per test belongs in a fixture instead.

code

csharp · 24 lines
csharp
public sealed class BracketTableTests : IDisposable
{
    private readonly TaxBracketTable _table;
    private readonly TaxCalculator _calculator;

    public BracketTableTests()                 // runs before every test
    {
        _table = TaxBracketTable.Load2026();
        _calculator = new TaxCalculator(_table);
    }

    [Fact]
    public void Raising_the_top_rate_changes_high_incomes()
    {
        _table.SetTopRate(0.45m);              // changes this instance's table only
        Assert.Equal(10_500m, _calculator.Calculate(50_000m));
    }

    [Fact]
    public void Default_top_rate_is_forty_percent() =>
        Assert.Equal(10_000m, _calculator.Calculate(50_000m)); // sees a fresh table

    public void Dispose() => _table.Dispose(); // runs after every test, pass or fail
}

go deeper

for a junior

Remember the rule: a new instance per test, constructor = setup, Dispose = teardown, and every theory row is its own test.

for a middle

Walk through the order (constructor, method, DisposeAsync or Dispose), what happens when the constructor throws, and why only DisposeAsync runs when both interfaces exist.

for a senior

Spot order-dependent suites caused by static state, constructors that block on async work, and per-test setup costly enough to belong in a shared fixture.

for a principal

Weigh isolation against cost: fresh state per test buys order-independence, and a team should decide deliberately which expensive resources are shared and how that sharing is made visible.

## One instance per test The single most important fact about an xUnit.net test class is its lifetime: **the runner creates a new instance for every test it runs**. Three facts in a class mean three constructions; a theory with five data rows means five more, because each row is its own test. When the test finishes, pass or fail, that instance is disposed and thrown away. With that lifetime, ordinary C# already provides setup and teardown: - the **constructor** runs immediately before the test method, so it is per-test setup; - `IDisposable.Dispose` (or `IAsyncDisposable.DisposeAsync`) runs immediately after, so it is per-test teardown; - **instance fields** hold the per-test state, and `readonly` lets the compiler confirm they are set. ## Mapping the lifecycle from other .NET frameworks | Purpose | NUnit | MSTest | xUnit.net | |---|---|---|---| | before each test | `[SetUp]` method | `[TestInitialize]` method | constructor | | after each test | `[TearDown]` method | `[TestCleanup]` method | `Dispose` / `DisposeAsync` | | state between the two | fields on a shared instance | fields | fields on a fresh instance | The xUnit.net column needs no framework attribute at all, and nothing in the class can depend on a previous test having run. ## What runs, in what order For each test the runner: 1. Skips construction entirely if the test method is `static`; there is no instance to build. 2. Calls the single public constructor. If it throws, the test fails with that exception and the method body never runs. 3. Invokes the test method on the new instance. 4. Disposes the instance: `DisposeAsync` if the class implements `IAsyncDisposable`, otherwise `Dispose` if it implements `IDisposable`. An exception here is reported as a cleanup failure for that test. Two consequences of step 2 and step 4 catch people out. When the constructor throws, no instance exists, so `Dispose` is not called and anything the constructor acquired before failing must be released by the constructor itself. And when a class implements **both** disposal interfaces, the runner calls `DisposeAsync` only; cleanup written solely in `Dispose` is silently skipped. ## What the design buys - **Isolation by default**: a test that mutates the bracket table cannot change what the next test sees, because the next test has a different table. - **No hidden ordering**: since every test starts from a constructed state, tests can run in any order. - **Plain C#**: setup is visible in one place, tooling such as nullable analysis understands it, and there is no attribute-discovery convention to learn. ## Rules and traps - **One public constructor only.** A second public constructor fails the class with "A test class may only define a single public constructor." - **Constructor parameters are not dependency injection.** xUnit.net satisfies them only from its own fixtures and a few framework services such as `ITestOutputHelper`; anything else fails with "The following constructor parameters did not have matching fixture data". - **Static state is shared.** A `static` field lives for the whole run, so changing it in one test leaks into the next exactly as a shared instance would. - **Constructors cannot await.** Blocking on `.Result` or `.Wait()` in a constructor to load async data is a smell; xUnit.net's `IAsyncLifetime` interface is the dedicated hook, and it is its own topic. - **Cost multiplies.** Whatever the constructor does is repeated for every test and every theory row. Loading a large bracket file or starting a server per test is the signal to move that work into a fixture shared across tests. - **Skipped tests build nothing.** A test skipped with `Skip = "..."` is reported without running, so its constructor and `Dispose` do not run either; do not rely on a skipped test to release resources. - **Field initialisers count as setup.** `private readonly TaxCalculator _calculator = new(...);` runs as part of construction, so a one-line fixture-free setup needs no constructor body at all. ## In the tax-bracket suite Each test gets its own table and calculator, so a test that raises the top rate cannot break the test that checks the default rate. If those two facts shared one instance, as `[SetUp]`-style frameworks can encourage, their outcome would depend on execution order.

  • If a test class implements both IDisposable and IAsyncDisposable, which one does xUnit.net call?
    Only `DisposeAsync`. The runner checks for `IAsyncDisposable` first and falls back to `Dispose` only when the class does not implement it, so cleanup that lives only in `Dispose` never runs. Put all cleanup in `DisposeAsync`, or have `DisposeAsync` call the synchronous cleanup itself.
  • What happens when the test class constructor throws?
    The test fails with the constructor's exception and the test method never runs. Because no instance was created, `Dispose` is not called either, so a constructor that acquired a resource before failing must release it itself, for example in a try/catch around the risky step.
  • Why does a static field undo the isolation the per-test constructor gives you?
    The fresh instance resets instance fields only. A static field belongs to the type and lives for the whole test run, so a value one test writes is still there for the next test, and the outcome starts to depend on execution order. Keep per-test state in instance fields and make any deliberate sharing explicit through a fixture.

A hotel room turned over for each guest: every guest (test) gets a freshly made room (constructor), housekeeping cleans it after checkout (Dispose), and nothing a guest leaves behind reaches the next one. The lobby (static fields) is shared by everybody, so a mess there is seen by all.

  • xUnit.net creates one instance per test class and reuses it for every test in it.
  • In xUnit.net you mark setup methods with [SetUp] and cleanup methods with [TearDown].
  • xUnit.net calls Dispose only when the test passed.
  • When a class implements IDisposable and IAsyncDisposable, xUnit.net calls both.
  • Static fields are reset between tests just like instance fields.
  • The test class constructor can take any service registered in the app's DI container.