Lesson 23 of 93 · 6 min read · Updated

IClassFixture in xUnit: Sharing Expensive Setup Across Tests in One Class

xUnit creates a new instance of the test class for every test. That isolation is a good default, but it becomes a cost when the setup is slow, such as loading reference data or creating a database schema. IClassFixture<T> lets all tests in one class share a single, expensive object. This lesson shows how a class fixture is created, injected and disposed, and the one rule you must follow to keep shared state from breaking your tests.

Technical Requirements

  1. .NET 11 SDK
  2. xunit 2.9.3
  3. xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0

Why xUnit Creates a New Instance per Test

In xUnit, the test class constructor is the setup code and Dispose is the teardown code. Because every test gets a fresh instance, fields set in the constructor never leak from one test into another. A test that changes a field cannot affect the next test.

The price is that the constructor runs once per test. If it takes 50 milliseconds and the class has 100 tests, the suite spends five seconds on setup alone. When the setup is a container start or a schema migration, the numbers get much worse. A class fixture solves this by moving the expensive work out of the constructor into an object that xUnit creates once for the whole class.

The Expensive Object

The example uses a class that stands in for slow setup. It loads a small table of city codes and then sleeps for 50 milliseconds to simulate real work. In a real project, this could be parsing a large file, starting a container or building a database.

M03.DataDriven/ReferenceDataStore.cs

/// <summary>
/// A stand-in for EXPENSIVE SETUP: reference data that takes time to load.
/// In real life: creating a database schema, starting a container,
/// parsing a large file.
/// </summary>
public sealed class ReferenceDataStore : IDisposable
{
/// <summary>Counting how many times it was created proves that the fixture works.</summary>
public static int InstanceCount;

private readonly Dictionary<string, string> _cityCodes;

public ReferenceDataStore()
{
Interlocked.Increment(ref InstanceCount);

// An artificial delay that represents expensive setup.
var stopwatch = Stopwatch.StartNew();
_cityCodes = new Dictionary<string, string>
{
["34"] = "İstanbul",
["06"] = "Ankara",
["35"] = "İzmir",
["16"] = "Bursa",
};
Thread.Sleep(50);
LoadDuration = stopwatch.Elapsed;
}

public TimeSpan LoadDuration { get; }

public bool IsDisposed { get; private set; }

public string? CityFor(string plateCode) => _cityCodes.GetValueOrDefault(plateCode);

public void Dispose() => IsDisposed = true;
}

The class implements IDisposable. xUnit calls Dispose on a fixture when it is done with it, so this is where you would stop a container or delete a temporary database.

InstanceCount is a static field. Static mutable state is usually something to avoid in tests, and that is still true. Here it is only a teaching aid: it counts how many times the object was created, which lets you prove the fixture is shared. Do not copy this pattern into real fixtures.

Using IClassFixture

To share the store, the test class implements IClassFixture<ReferenceDataStore> and takes the fixture as a constructor parameter.

M03.DataDriven.Tests/ClassFixtureTests.cs

public class ClassFixtureTests : IClassFixture<ReferenceDataStore>
{
private readonly ReferenceDataStore _referenceData;

public ClassFixtureTests(ReferenceDataStore referenceData)
{
// The fixture is injected through the constructor.
_referenceData = referenceData;
}

[Fact]
public void CityFor_KnownPlateCode_ReturnsCityName()
{
Assert.Equal("İstanbul", _referenceData.CityFor("34"));
}

[Fact]
public void CityFor_UnknownPlateCode_ReturnsNull()
{
Assert.Null(_referenceData.CityFor("99"));
}

[Fact]
public void Fixture_IsNotDisposedWhileTestsRun()
{
// The fixture lifetime spans the whole test class.
Assert.False(_referenceData.IsDisposed);
}
}

IClassFixture<T> is a marker interface. It has no members to implement. It tells xUnit: "before running the tests in this class, create one T, and pass it to every instance of the class."

The test class itself is still created once per test. Three tests mean three instances of ClassFixtureTests. All three receive the same ReferenceDataStore, so the 50 millisecond setup runs once instead of three times.

The Fixture Lifecycle

xUnit manages the fixture for you:

  1. Before the first test in the class runs, xUnit creates the fixture by calling its constructor.
  2. For each test, xUnit creates a new test class instance and passes the same fixture to its constructor.
  3. After the last test in the class finishes, xUnit calls Dispose on the fixture if it implements IDisposable.

The test Fixture_IsNotDisposedWhileTestsRun checks step 3 from the inside: while tests are still running, the fixture has not been disposed yet.

If the fixture needs asynchronous setup or teardown, for example starting a container, implement IAsyncLifetime on the fixture. xUnit then awaits InitializeAsync before the first test and DisposeAsync after the last one.

xUnit creates the fixture itself, not a dependency injection container. Apart from a few framework types such as IMessageSink, the fixture constructor takes no parameters. If the fixture needs configuration, build or read it inside the fixture constructor.

Pitfall: Shared Mutable State

A class fixture is shared state by design. If one test changes it, every later test in the class sees the change. Tests start to depend on the order in which they run, and a test that passes alone fails when run with the others.

Follow one of these two rules:

  1. Keep the fixture read-only. ReferenceDataStore only exposes a lookup method and properties with private setters. Tests can read from it but cannot change its data.
  2. Reset it in each test. If the fixture must hold state, such as a database, the test class constructor cleans or resets that state before each test. Tools like Respawn exist for exactly this purpose with databases.

Also keep in mind that the fixture is shared only within one class. Another test class that implements IClassFixture<ReferenceDataStore> gets its own instance. Sharing one instance across several classes needs a collection fixture, which the next lesson covers.

Summary

  1. xUnit creates a new test class instance per test, so expensive constructor setup runs every time.
  2. IClassFixture<T> creates one T for all tests in a class and injects it through the constructor.
  3. The fixture is created before the first test and disposed after the last test of the class.
  4. Use IAsyncLifetime on the fixture for asynchronous setup and teardown.
  5. Keep the fixture read-only, or reset its state in each test, so tests do not affect each other.