skip to content

Class & Collection Fixtures

IClassFixture<T>, ICollectionFixture<T> and assembly fixtures share costly setup across xUnit tests, and test collections decide what runs in parallel. Interviewers probe fixture scope.

on this pageshow

explore

questions

5

In xUnit.net, how does IClassFixture<T> share an expensive search index across one test class's tests, and when is it created and disposed?

level: middleimportance: must knowfreq 64%

answer

  1. per-test instance versus shared context
  2. IClassFixture<T> is a marker interface
  3. fixture arrives through the test constructor
  4. built before the class's first test
  5. DisposeAsync or Dispose after its last test

basics

~20 s

Mark the test class with IClassFixture<SearchIndexFixture> and take SearchIndexFixture in its constructor. xUnit.net builds the fixture once, before the class's first test, passes that same instance to every test's fresh class instance, and disposes it after the class's last test.

solid answer

~50 s

xUnit.net builds a new test-class instance per test, so expensive state cannot live in the test class itself. `IClassFixture<SearchIndexFixture>` is a marker interface with no members: it tells the runner to create one `SearchIndexFixture` just before the first test of that class, inject the same instance into every test's constructor, and clean it up after the last test, with `DisposeAsync` if the fixture implements `IAsyncDisposable`, otherwise `Dispose`. The fixture needs a single public constructor; it may ask for collection or assembly fixtures, an `IMessageSink` for diagnostics or `ITestContextAccessor`, but not `ITestOutputHelper`, which belongs to one test. If the fixture's constructor throws, every test in the class fails with "Class fixture type ... threw in its constructor". Because all tests see one instance, keep the index read-only, or a test that mutates it makes the others order-dependent.

code

csharp · 26 lines
csharp
using Xunit.Sdk;   // IMessageSink
using Xunit.v3;    // DiagnosticMessage

public sealed class SearchIndexFixture : IDisposable
{
    public SearchIndexFixture(IMessageSink diagnostics)
    {
        Index = CatalogSearchIndex.Build(SeedCatalog.Load("catalog-50k.json"));
        diagnostics.OnMessage(new DiagnosticMessage("Indexed {0} documents", Index.Count));
    }

    public CatalogSearchIndex Index { get; }

    public void Dispose() => Index.Dispose();
}

public class ProductSearchTests(SearchIndexFixture fixture) : IClassFixture<SearchIndexFixture>
{
    [Fact]
    public void Exact_title_ranks_first() =>
        Assert.Equal("sku-1042", fixture.Index.Search("trail running shoe").First().Sku);

    [Fact]
    public void Unknown_term_returns_nothing() =>
        Assert.Empty(fixture.Index.Search("zzqx"));
}

go deeper

for a junior

Remember the pattern: IClassFixture<T> on the class, T in the constructor, one fixture shared by all tests of that class.

for a middle

Explain the lifecycle (built before the first test, disposed after the last), what the fixture's constructor may receive, and why a class fixture failure turns every test in the class red.

for a senior

Judge scope and safety: keep shared fixtures read-only, recognise order-dependent failures caused by mutation, and move up to collection or assembly scope when several classes rebuild the same object.

for a principal

Balance suite speed against independence: decide which expensive resources a team may share, at what scope, and the conventions that keep shared state immutable.

## Two lifetimes in one test class xUnit.net constructs a **new instance of the test class for every test**, which makes the constructor a per-test setup step. That is exactly wrong for a search index that takes eight seconds to build from 50,000 catalogue documents: a class with twelve tests would build it twelve times. A **class fixture** adds a second, longer lifetime: one object created for the whole test class and handed to each of those short-lived test instances. ## Declaring a class fixture 1. Write the fixture as an ordinary class, `SearchIndexFixture`, that builds the index in its constructor and releases it in `Dispose`. 2. Add `IClassFixture<SearchIndexFixture>` to the test class's interface list. The interface has no members; it is metadata the runner reads. 3. Add a `SearchIndexFixture` parameter to the test class constructor and store it in a field. The parameter type must match the fixture type exactly. 4. Use the field in each test. Forgetting step 2 while keeping step 3 fails each test with "The following constructor parameters did not have matching fixture data". ## Lifecycle | Moment | What xUnit.net does | |---|---| | before the first test of the class | constructs the fixture, then calls `InitializeAsync` if it implements `IAsyncLifetime` | | before each test | constructs a new test-class instance, passing the same fixture | | after each test | disposes that test-class instance only | | after the last test of the class | calls the fixture's `DisposeAsync`, or `Dispose` if it has no async disposal | The fixture is created once **per test class**, not per assembly: two classes that both implement `IClassFixture<SearchIndexFixture>` each get their own index. Sharing across classes needs a collection or assembly fixture instead. ## What a fixture's constructor may ask for A fixture must have exactly one public constructor, otherwise the class fails with "Class fixture type ... may only define a single public constructor." Its parameters can be: - **collection fixtures** and **assembly fixtures** in scope, so a per-class view can be built from a larger shared object; - **`IMessageSink`**, a sink for diagnostic messages, the fixture-level way to log the build, for example `sink.OnMessage(new DiagnosticMessage("Indexed {0} documents", count))`; - **`ITestContextAccessor`**, to reach the current context. `ITestOutputHelper` is not on the list: it captures one test's output, and a class fixture outlives every individual test. Anything else fails with "Class fixture type ... had one or more unresolved constructor arguments". ## Failure modes - A fixture constructor that throws fails **every** test in the class with "Class fixture type 'SearchIndexFixture' threw in its constructor" and the inner exception, so one broken data file shows up as twelve red tests with the same cause. - A failure in `InitializeAsync` is reported the same way, naming `InitializeAsync`. - An exception from the fixture's disposal is reported as a cleanup failure for the class, after its tests have run. - `ICollectionFixture<T>` placed on a test class instead of a collection definition is rejected: "A test class may not be decorated with ICollectionFixture<>". ## Keeping shared state safe The price of sharing is that the tests are no longer independent through that object: - **Treat the fixture as read-only.** Query the index; never add or delete documents in a test. - **Copy before mutating.** A test that needs a modified index builds a small one of its own or takes a copy, rather than editing the shared instance. - **Keep per-test state on the test class.** Counters, captured results and fakes belong in fields of the test-class instance, which is fresh for each test. - **Make cleanup idempotent.** Disposal runs once, after all tests, even if some tests failed. Tests inside one class run one after another by default, so a class fixture is not read concurrently by tests of the same class unless the assembly opts into full parallelism. The risk it does carry is **order dependence**: a test that mutates the index makes later tests pass or fail depending on the order they happen to run in. ## When a class fixture is the wrong tool A class fixture is the right scope when one test class owns the expensive object. When ten classes need the same index, ten class fixtures still mean ten builds; that is the point to move up to a collection fixture or an assembly fixture.

  • How can a class fixture log how long the index build took if it cannot take ITestOutputHelper?
    Take an `IMessageSink` constructor parameter and send `new DiagnosticMessage("Index built in {0} ms", elapsed)` through `OnMessage`. Diagnostic messages are a runner-level channel that is off unless enabled, for example with `"diagnosticMessages": true` in `xunit.runner.json`. `ITestOutputHelper` is tied to one running test, which a class fixture outlives.
  • Two test classes both implement IClassFixture<SearchIndexFixture>. How many indexes are built?
    Two. A class fixture's scope is the test class, so each class gets its own instance even though the type is the same. To build one index for both, place the classes in one collection with an `ICollectionFixture<SearchIndexFixture>`, or register the type as an assembly fixture.

A class fixture is the projector set up once for a whole lecture series in one room: each session (test) brings fresh handouts (the new test-class instance), the projector stays put until the last session ends, and a different room needs its own projector.

  • An IClassFixture<T> fixture is created again for every test in the class.
  • A class fixture can take ITestOutputHelper in its constructor to log its setup.
  • Two test classes that implement IClassFixture<T> for the same T share one instance.
  • The test class must dispose the fixture in its own Dispose method.
  • Each test gets its own copy of the fixture, so mutating it is harmless.
open as a page

In xUnit.net, how do you write diagnostic output from a test with ITestOutputHelper, and why does Console.WriteLine not appear in the test result?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Take ITestOutputHelper in the test class constructor and call WriteLine; the text is attached to that test's result. Console output is not attached because tests run in parallel and share one console, unless the xunit.v3 assembly opts in with [assembly: CaptureConsole].

open as a page

In xunit.v3, why do tests in one class run one after another while different classes run in parallel, and how do you change that?

level: middleimportance: should knowfreq 52%

basics

~10 s

xUnit.net parallelises test collections, and by default each class is its own collection whose tests run serially. Regroup with [Collection] or [CollectionBehavior]; set mode and thread count with [assembly: Parallelization(...)] or xunit.runner.json.

open as a page

In xunit.v3, how does IAsyncLifetime let a fixture or test class build a search index asynchronously, and what changed from xUnit.net v2?

level: middleimportance: should knowfreq 48%

basics

~10 s

Implement IAsyncLifetime: xUnit.net awaits InitializeAsync right after constructing the fixture or test class, and awaits DisposeAsync at cleanup. In xunit.v3 InitializeAsync returns ValueTask and IAsyncLifetime extends IAsyncDisposable; in v2 both methods returned Task.

open as a page

Twelve xunit.v3 test classes each rebuild the same eight-second search index; how do you share one instance, and what does each option do to parallelism?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Put the classes in one test collection whose definition implements ICollectionFixture<SearchIndexFixture>: one index, but those classes run serially. Or register an assembly fixture: one index, classes stay parallel, so it must tolerate concurrent reads.

open as a page