Lesson 83 of 93 · 5 min read · Updated

Organizing Integration Tests: Separate Projects and Shared Fixtures in xUnit

Integration tests have a different cost profile from unit tests. They start hosts, open database connections, run HTTP servers and sometimes download a browser. If they live in the same project as unit tests, every developer pays that cost on every run. This lesson shows how a Books API keeps its tests in separate projects, how one expensive WebApplicationFactory is shared across test classes with an xUnit collection fixture, and what that sharing costs you.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Microsoft.AspNetCore.Mvc.Testing 11.0.0
  4. Microsoft.Playwright.Xunit 1.65.0 (only for the end-to-end project)
  5. Docker is not required.

One Project per Cost Level

The solution has three projects for this API:

  1. M09.IntegrationApi: the application itself.
  2. M09.IntegrationApi.Tests: integration tests with WebApplicationFactory, SQLite in-memory and WireMock.Net. 27 tests, about one second.
  3. M09.IntegrationApi.E2E.Tests: 3 end-to-end tests with Playwright and a real browser. The first run downloads Chromium (about 150 MB).

The split is not about naming. It lets you run each group on its own schedule. A developer runs the integration tests on every change, while a CI pipeline can run the end-to-end project in a separate, slower stage:

# Integration tests (fast, ~1 s)
dotnet test M09.IntegrationApi.Tests

# End-to-end (E2E) Playwright tests — the first run downloads Chromium (~150 MB, ~1 min)
dotnet test M09.IntegrationApi.E2E.Tests

# Everything in the solution EXCEPT E2E
dotnet test --filter "Kapsam!=E2E"

The E2E project explains its own existence in its project file:

M09.IntegrationApi.E2E.Tests/M09.IntegrationApi.E2E.Tests.csproj

<!--
End-to-end (E2E) tests live in a SEPARATE project:
they download a browser, open a real port and are slow. They should not slow down the fast tests' pipeline.
-->

The E2E test classes also carry a trait, [Trait("Kapsam", "E2E")], where Kapsam is the trait name meaning "scope". The trait lets you exclude them with a filter when you run the whole solution, as in the third command above. Separate projects and traits work together: the project boundary keeps dependencies such as Playwright out of the fast test project, and the trait gives you a filter when you run everything at once.

Shared Build Settings for Test Projects

A Directory.Build.props file at the root of the modules folder treats every project whose name ends in .Tests as a test project and adds the common packages. Each test .csproj then lists only what is specific to it.

Directory.Build.props

<!--
Every project whose name ends with ".Tests" is automatically treated as a TEST PROJECT
and gets the shared test packages. We do not repeat them in each csproj.
-->
<PropertyGroup Condition="$(MSBuildProjectName.EndsWith('.Tests'))">
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup Condition="$(MSBuildProjectName.EndsWith('.Tests'))">
<!-- xUnit: the test framework (DEFINES the tests) -->
<PackageReference Include="xunit" />
<!-- VSTest adapter: the platform side that DISCOVERS and RUNS the tests -->
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<!-- To collect code coverage data -->
<PackageReference Include="coverlet.collector" />
</ItemGroup>

This convention matters more as the number of test projects grows. Adding a new integration test project is a new folder and a short .csproj, not a copy of package references that slowly drift apart.

Sharing the Expensive Fixture

Starting a WebApplicationFactory, opening the SQLite connection, creating the schema and starting a WireMock server takes time. Doing it once per test class would multiply that cost. xUnit's collection fixture creates one instance and shares it with every class in the collection:

M09.IntegrationApi.Tests/Infrastructure/ApiCollection.cs

/// <summary>
/// Keep integration tests separate and share the expensive resource.
///
/// WebApplicationFactory + SQLite connection are EXPENSIVE to set up.
/// With a collection fixture we share ONE INSTANCE across all test classes.
///
/// THE COST: classes in this collection do not run in parallel and they SHARE DATA.
/// That is why every test RESETS its own data with ResetDatabaseAsync.
/// </summary>
[CollectionDefinition(Name)]
public sealed class ApiCollection : ICollectionFixture<BooksApiFactory>
{
public const string Name = "Books API";
}

Each test class joins the collection with an attribute and receives the factory through its constructor:

M09.IntegrationApi.Tests/HttpPipelineTests.cs

[Collection(ApiCollection.Name)]
public class HttpPipelineTests(BooksApiFactory factory) : IAsyncLifetime
{
private HttpClient _client = null!;

public async Task InitializeAsync()
{
// A CLEAN state before each test → order independence.
await factory.ResetDatabaseAsync();
_client = factory.CreateClient();
}

HttpPipelineTests, ExternalApiTests and BackgroundServiceIntegrationTests all use the same collection, so they share one host, one database and one WireMock server.

Pitfall: Shared Fixtures Mean Shared State

The comment on ApiCollection names the price. xUnit runs test classes in the same collection one after another, not in parallel, so the suite gets no speed-up from parallelism inside the collection. Worse, the data is shared. A book created by one test is still there when the next test starts, unless something removes it.

The tests handle this with a strict rule: every test resets the state it depends on at the start, in InitializeAsync. ResetDatabaseAsync deletes all rows. ExternalApiTests also calls CurrencyServer.Reset() to drop WireMock mappings and logs. The background service tests rely on the factory's FakeTimeProvider, which never moves unless a test calls Advance, so the hosted service cannot run in the middle of another test.

Reset at the start, not at the end. A test that fails halfway never reaches its cleanup code, and the next test would inherit a dirty state. Resetting first makes each test responsible for its own starting point.

Test classes that need no shared host should stay out of the collection. EfCoreProviderTests creates its own SQLite connection per test, and BackgroundServiceUnitTests builds the service by hand. Both run in parallel with the collection.

Summary

  1. Keep integration and end-to-end tests in their own projects so the fast tests stay fast and free of heavy dependencies.
  2. Add a trait to slow tests so you can exclude them with --filter when running the whole solution.
  3. Use a Directory.Build.props convention to give every *.Tests project the same test packages.
  4. Share an expensive WebApplicationFactory with ICollectionFixture<T> and [Collection].
  5. Shared fixtures run sequentially and share state: reset data, mocks and clocks at the start of every test.