Lesson 24 of 93 · 5 min read · Updated

Collection Fixtures in xUnit: Sharing One Context Across Multiple Test Classes

A class fixture shares an expensive object between the tests of one class. Real suites often need more: several test classes that all use the same database, container or reference data set. Creating that object once per class wastes time. xUnit solves this with collection fixtures. This lesson shows the three steps to set one up, and the side effect on parallel execution that comes with it.

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
  4. The ReferenceDataStore class from the previous lesson

The Problem with IClassFixture Across Classes

In the previous lesson, ClassFixtureTests implemented IClassFixture<ReferenceDataStore>. If two more classes do the same, xUnit creates three separate stores, one per class. Each one pays the setup cost. With a real database or container, that can mean three schema migrations or three container starts for one test run.

A collection fixture creates the object once for a named group of classes, called a test collection, and gives the same instance to all of them.

Step 1 and 2: Define the Collection

A collection is defined by an empty class with two markers: the [CollectionDefinition] attribute, which gives the collection a name, and the ICollectionFixture<T> interface, which names the type to share.

M03.DataDriven.Tests/CollectionFixtureTests.cs

[CollectionDefinition(ReferenceDataCollection.Name)]
public sealed class ReferenceDataCollection : ICollectionFixture<ReferenceDataStore>
{
public const string Name = "Reference Data";

// The body of this class stays EMPTY; it exists only to carry the attributes.
}

The class has no tests and no logic. xUnit discovers it through the attribute and reads the fixture type from the interface. A collection can declare more than one fixture by implementing ICollectionFixture<T> several times.

The collection name is stored in a const field. Both the definition and every class that joins the collection use ReferenceDataCollection.Name instead of a string literal. If the names do not match exactly, xUnit treats them as two different collections, and the class that misspelled the name does not get the fixture. With a constant, a typo becomes a compile error.

The collection definition class must be in the same assembly as the tests that use it. xUnit does not look for definitions in referenced libraries.

Step 3: Join the Collection

Each test class that should share the fixture gets [Collection] with the same name, and takes the fixture in its constructor.

M03.DataDriven.Tests/CollectionFixtureTests.cs

[Collection(ReferenceDataCollection.Name)]
public class AnkaraLookupTests(ReferenceDataStore referenceData)
{
[Fact]
public void CityFor_06_ReturnsAnkara() => Assert.Equal("Ankara", referenceData.CityFor("06"));
}

[Collection(ReferenceDataCollection.Name)]
public class IzmirLookupTests(ReferenceDataStore referenceData)
{
[Fact]
public void CityFor_35_ReturnsIzmir() => Assert.Equal("İzmir", referenceData.CityFor("35"));

[Fact]
public void SharedStore_IsTheSameInstanceAcrossClasses()
{
// Two classes in the same collection see the SAME instance.
// (InstanceCount can be greater than 1 because of the ClassFixture example;
// what matters here is that the resource exists and is usable.)
Assert.True(ReferenceDataStore.InstanceCount >= 1);
Assert.False(referenceData.IsDisposed);
}
}

These classes use C# primary constructors. The referenceData parameter is available in every test method, which keeps short test classes compact. A regular constructor that assigns a field works the same way.

Notice that the test classes do not implement any interface. Joining the collection through [Collection] is enough. If you also add IClassFixture<ReferenceDataStore> to one of them, that class gets a second, separate instance as its class fixture, which is rarely what you want.

The Collection Fixture Lifecycle

xUnit creates the collection fixture before the first test of any class in the collection runs. It disposes the fixture after the last test of the last class in the collection finishes. In between, every test in every participating class receives the same instance.

The comment in SharedStore_IsTheSameInstanceAcrossClasses explains a detail about the static counter. The class fixture from the previous lesson also creates a ReferenceDataStore, so the counter can be one or two when this test runs, depending on which class xUnit starts first. An exact check would be flaky, so the assertion only checks for >= 1. The counter is a teaching aid, not a pattern for real code. A more direct check would store the instance in one class and compare references in another, but that would depend on test order, which you should avoid.

Side Effect: Classes in a Collection Do Not Run in Parallel

xUnit runs different test collections in parallel by default. By default, each test class is its own collection. When you put several classes into one named collection, xUnit runs them one after another, not in parallel with each other.

This is deliberate. The classes share one object, and running them at the same time against shared state could cause race conditions. But it also has a cost: a large collection turns part of your suite into a serial queue.

ScopeToolCost
A single test classIClassFixture<T>none
Several test classes[CollectionDefinition] with ICollectionFixture<T>those classes do not run in parallel

Keep collections focused. Put only the classes that really need the shared resource into the collection. A common mistake is to put every integration test class into one big collection "to be safe". The suite then runs serially, and the time saved by sharing setup is lost to the lack of parallelism.

As with class fixtures, the shared object should be read-only or reset before each test. Sequential execution protects you from race conditions, but not from one test leaving data behind for the next.

Summary

  1. A collection fixture shares one object across several test classes, not just the tests of one class.
  2. Define the collection with an empty class that has [CollectionDefinition("Name")] and implements ICollectionFixture<T>.
  3. Mark each participating class with [Collection("Name")] and take the fixture in its constructor.
  4. Store the collection name in a constant so a typo cannot silently create a second collection.
  5. Classes in the same collection do not run in parallel with each other, so keep collections small.