xUnit Shared Fixture Trap — Local Pass, CI Fail
Test saw 3 instead of 2 orders when xUnit shared an in-memory database across parallel fixtures.
20+ years shipping production .NET services in enterprise systems. Lessons pulled from things that broke in production.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- xUnit runs tests via
dotnet testor Test Explorer using [Fact] and [Theory] attributes - Constructor + IDisposable replace [SetUp]/[TearDown] — each test gets a fresh class instance
- IClassFixture
shares expensive setup without sharing mutable state - Moq creates fake dependencies; always depend on interfaces in constructors
- Default parallel execution per class can cause flaky tests — use [Collection] to isolate
- Biggest mistake: writing a single [Theory] with only one InlineData — that's just a verbose [Fact]
Imagine you build a vending machine. Before shipping it to a hospital, you test every single button — does pressing B3 drop a Snickers? Does it reject a fake coin? Unit testing is exactly that: you write tiny automated 'button-press checks' for every function in your code, so you catch broken buttons before your users do. xUnit is the machine that runs all those checks for you, prints a green tick when everything works, and screams a red X when something breaks.
Every production codebase eventually reaches a tipping point where a developer changes one function and silently breaks three others. Without automated tests, you only find out when a customer tweets at you at 2am. Unit testing is not a 'nice to have' — it is the safety harness that lets your team move fast without falling off a cliff. Companies like Microsoft, Stripe, and Shopify treat untested code as unshippable code, and for good reason.
The specific pain xUnit solves is the chaos of manual regression checking. Without it, every new feature means re-clicking through the entire app to make sure nothing broke. xUnit lets you encode that mental checklist as code, run it in under a second, and get a precise pass/fail report with zero human effort. It also integrates natively into the .NET ecosystem, works beautifully with GitHub Actions and Azure DevOps pipelines, and produces machine-readable output that pull-request bots can act on automatically.
By the end of this article you will know how to structure a real xUnit test project from scratch, write both simple Fact tests and data-driven Theory tests, isolate dependencies using the Moq library, and avoid the three mistakes that waste most beginners' first week with xUnit. You will also understand why each xUnit design decision exists, so you can make smart choices on your own projects rather than blindly copying Stack Overflow snippets.
Here's the honest truth: most developers learn xUnit by copying a template, write a few tests that all pass, and then ship untested code into production because they never hit the awkward edges. This article exists to force you past that plateau. You'll leave with the mental model that separates a junior who writes tests from a senior who designs systems that are testable.
What xUnit Shared Fixtures Actually Do — And Where They Break
xUnit shared fixtures let you create a single object instance that is shared across all test methods in a class (or collection). You implement IClassFixture<T> or ICollectionFixture<T>, and xUnit injects that fixture into the test class constructor once per class, not once per test. This is the core mechanic: one setup, many tests.
In practice, shared fixtures are ideal for expensive resources like database connections, HTTP clients, or service containers. They reduce test runtime by avoiding repeated construction and teardown. But they also introduce state coupling: if a test mutates the fixture, subsequent tests see that mutation. xUnit does not reset the fixture between tests. This is the trap — tests pass locally in isolation but fail in CI when run in a different order or with more parallelism.
Use shared fixtures only for read-only or reset-safe resources. For mutable state, prefer collection fixtures with explicit cleanup in Dispose, or use the newer IAsyncLifetime for async teardown. In real systems, the cost of a shared fixture bug is a flaky CI pipeline that erodes team trust in the test suite.
Setting Up a Real xUnit Project — Structure That Scales
The number one mistake teams make is dumping tests into the same project as production code. That forces your shipping binary to carry test dependencies, and it blurs the line between what you own and what you are testing. The industry-standard layout is a separate .Tests project that references your production project.
Here is exactly how to scaffold this from the terminal. The key insight is that dotnet new xunit gives you a ready-to-run test runner — xUnit's runner is baked in via the xunit.runner.visualstudio package, which is what lets Visual Studio's Test Explorer and dotnet test both work without extra wiring.
Notice that your test project references your production project directly. xUnit discovers test classes by scanning for public classes with methods decorated with [Fact] or [Theory] — no base class, no interface, no ceremony. That is a deliberate philosophy: tests should read like plain C#, not like a framework DSL.
OrderCalculator.cs maps to OrderCalculatorTests.cs, in a matching namespace like OrderProcessing.Tests. This makes navigation instant: when you open a class, you always know exactly where its tests live without hunting.dotnet test works via CLI, but Visual Studio needs the adapter.Fact vs Theory — Writing Tests That Actually Prove Something
xUnit gives you two test primitives: [Fact] and [Theory]. Understanding the difference is the key to writing tests that are genuinely useful rather than tests that only prove one lucky path through your code.
A [Fact] is a single, unconditional assertion: 'this is always true, no arguments needed.' Use it for edge cases, boundary conditions, and single-scenario checks. A [Theory] is a parameterised test that says 'this should be true for all of these inputs.' You supply multiple data sets via [InlineData], [MemberData], or [ClassData], and xUnit runs your test method once per set, independently.
Why does this matter? Because a bug in a calculation function usually lives at an edge — zero, negative numbers, null strings, max integer. A single [Fact] with one happy-path number gives you false confidence. A [Theory] with seven representative inputs — including edge cases — is what actually catches real bugs before production does.
Below is a production-realistic example using an OrderCalculator that applies discounts. Notice the test names are descriptive English sentences — that is intentional. When a test fails in CI, the name is your first clue, so 'CalculateTotal_WhenDiscountExceedsHundredPercent_ThrowsArgumentException' tells you exactly what broke without opening the file.
Mocking Dependencies With Moq — Testing Code in Isolation
Real services talk to databases, payment gateways, and email providers. If your unit test actually hits a database, it is not a unit test — it is a slow, flaky integration test that fails whenever the DB is unreachable. The solution is dependency injection plus mocking: you inject a fake version of the dependency that behaves exactly as you dictate, so your test owns the scenario completely.
Moq is the most widely used mocking library in the .NET ecosystem. You install it into your test project only — production code never sees it. The mental model is simple: Mock creates a stand-in actor who plays the role of IEmailService. You script its lines with Setup(...), run the test, then verify it delivered those lines with Verify(...).
This pattern only works if your production class accepts its dependencies through a constructor (constructor injection). If a class creates its own new EmailService() internally, you cannot mock it. This is why dependency injection is not just an architectural nicety — it is a testability requirement.
Below we test an OrderService that sends a confirmation email after a successful order. We want to verify the email is sent exactly once with the right address, without firing off a real email during our test run.
virtual. If you try to mock a non-virtual method on a concrete class, Moq silently ignores your Setup and calls the real method — your test passes for the wrong reason. The clean solution is always to depend on interfaces, not concrete types. If you own neither, use a wrapper interface.Test Lifecycle with IClassFixture — Shared Setup Without Shared State
xUnit creates a fresh instance of your test class for every single test method. This is a deliberate design decision that eliminates a whole class of bugs caused by tests accidentally sharing state. NUnit and MSTest use [SetUp]/[TearDown] methods, which run before and after each test but on the same object — that means a dirty field from test A can corrupt test B if your setup is incomplete.
xUnit's answer is simpler: constructor and IDisposable. Anything you put in the test class constructor runs before each test. Anything you put in Dispose() runs after. No magic attributes — just C# you already know.
But sometimes setup is genuinely expensive — spinning up an in-memory database, loading a large config file — and you do not want to repeat it for every test. That is what IClassFixture<T> is for. It creates the expensive resource once per test class, shares it across all tests in that class, then disposes it when the class is done. Crucially, each test still gets a fresh test class instance — only the fixture is shared.
Here is a pattern you will see in real .NET projects using an in-memory database fixture.
databaseName: "OrderTests_" + Guid.NewGuid() in the fixture. If you use a fixed name like 'TestDb', parallel test runs share the same in-memory store and corrupt each other's data. A GUID suffix costs nothing and makes your tests perfectly isolated even under parallel execution.Guid.NewGuid() for in-memory database names.Data-Driven Testing with MemberData and ClassData — Beyond InlineData
While [InlineData] is the quickest way to parameterise a test, it has limitations: you cannot reuse data across methods, and the data is hardcoded in the attribute. For real-world scenarios where test data comes from a file, a database, or a computed set, xUnit provides [MemberData] and [ClassData].
[MemberData] points to a static property or method that returns IEnumerable. This lets you reuse the same data source across multiple test methods and even compute data dynamically (e.g., reading from a CSV file). [ClassData] points to a separate class that implements IEnumerable. This is useful when the data source is complex enough to warrant its own class, perhaps with caching or lazy loading.
A common real-world pattern: load test data from a JSON or CSV file via a static MemberData method. This decouples test logic from data, making your tests easier to read and update without recompiling. Below is an example that reads order test cases from a static method.
- InlineData: quick, simple, but couples data to the test method.
- MemberData: reusable, composable, supports lazy evaluation and external files.
- ClassData: best for complex or shared data sources that need their own class.
- Performance: MemberData and ClassData execute once per test class, not per method — but yield returns data on demand.
Parallel Test Execution — Why Your CI Pipeline Slows to a Crawl (And How to Fix It)
Here's the dirty secret most tutorials skip: xUnit runs your tests in parallel by default. Sounds great until your integration tests trash the same database and start failing in ways that make zero sense. The WHY is critical here — parallel execution is not free.
When xUnit fires up multiple test classes, each one gets its own collection unless you tell 'em to share. That's fine for pure unit tests with zero shared state. The moment you touch a file, a network socket, or — god forbid — a SQL database, you need to think about isolation.
The fix isn't to disable parallelism entirely (that's amateur hour). Use [CollectionDefinition] to group tests that must run sequentially. Mark slow infrastructure-heavy tests with [Trait("Category", "Integration")] and filter them out of your fast feedback loop. Your CI will thank you.
Senior Shortcut: Keep unit tests parallel. Sequentialize only the minimum needed. Your developer loop shouldn't wait on the same integration tests your build server runs.
Custom Test Runners — When Built-in Assertions Fail You
Standard assertions are fine until they aren't. Ever debug a failed test that says "Expected: true, Actual: false" with zero context? That's not useful. That's a waste of time.
The answer is a custom test runner. Not for everything — you're not building a framework. But when you have a repetitive assertion pattern (e.g., verifying JSON response shapes, checking business rule violations), write your own extension method that returns a meaningful message.
WHY it matters: in production incidents, every second counts. A custom assertion that spits out "Expected response code 200, got 503. Response body: {\"error\":\"timeout\"}" is worth its weight in gold. Moq's callback hell? Same thing. Wrap it in a helper that tells you exactly which setup failed.
Don't abstract for the sake of it. Write one, maybe two custom assertion methods per project. If you have more, your test design is wrong. Assertions should read like plain English, not regex obfuscation.
Shared Context Without IClassFixture — Using Lazy and Constructor Injection
IClassFixture is great for shared setup but it comes with a catch: xUnit creates one instance of your fixture per test class. If you need a singleton across multiple test classes, you're stuck.
Explicitly: When you have a test that depends on a database connection pool or a configuration object that's expensive to build, you want it created once for the entire test run. IClassFixture doesn't do that — it creates a new instance per concrete test class that implements it.
Here's the production trick: use Lazy
WHY this matters: Integration test suites that take 10 minutes can drop to 2. The lazy initialization means you don't pay for what you don't use. Just make sure your resource is thread-safe (read: connection pools are fine, file handles are not).
Why Your Test Fixtures Are Leaking State — And How to Kill It
Every senior dev has seen this mess: a test passes in isolation but fails when the whole suite runs. Nine times out of ten, it's shared state in a fixture that someone thought was read-only. xUnit reuses fixture instances across tests in the same class. If your fixture holds a mutable collection, a counter, or god forbid a static cache, you're debugging ghosts.
The fix is brutal and simple: make your fixture immutable after construction. If you must mutate, use IClassFixture with disposal that resets state. Or better yet, push mutable dependencies into mocks that you control per test. Production systems don't tolerate hidden state — neither should your test harness.
When you see a test that relies on fixture state being "just right" from a previous run, you're looking at tech debt that will bite you at 3 AM before a release. Kill it now.
IReadOnlyList<T> or AsReadOnly() to enforce immutability at the type level.Skipping the Fixture Factory — When IClassFixture Slows You Down
IClassFixture is great for expensive setup, but it's overkill when you just need a connection string or a config object. I've seen teams thread a fixture through every test class just to hold an IOptions that never changes. That's ceremony, not architecture.
For cheap, read-only dependencies, ditch the fixture. Use Lazy in a static constructor or inject your settings directly via a test constructor. No fixture registration, no IClassFixture interface, no garbage. Just a static cache that's thread-safe by default.
But watch the trap: Lazy is process-wide, not test-class-wide. If your test suite runs in parallel (and it should), a Lazy that initializes a database connection will fight itself. Use Lazy only for truly immutable data — like config strings or compiled regex patterns. For anything that touches I/O, stick with IClassFixture and accept the minor overhead.
Lazy<T> for config or static mocks that are read-only. For any fixture that allocates resources (DB, HTTP client), stick with IClassFixture so disposal is guaranteed.Lazy<T> will do — less code, same speed, zero ceremony.Anti-Pattern: Manually Iterating Over Test Data
Manually looping through test data inside a [Fact] test is a common anti-pattern. Developers write a foreach or for loop, run assertions inside the body, and assume all iterations pass. When the loop breaks early on the first failure, the test stops — leaving later data points untested. Worse, you lose visibility into which specific input failed because exceptions hide the iteration index. This approach violates the principle of “one assertion per test” and makes debugging a guessing game. Instead of manual iteration, use xUnit's [Theory] with [InlineData], [MemberData], or [ClassData]. Each data row runs as an independent test, giving you clear pass/fail per case, parallel execution, and immediate visibility into the exact failing input. Manual loops also prevent accurate test reporting in CI — a single red test can mask five failures. Stop looping; let the framework handle iteration with theories for reliable, granular results.
TheoryData, MemberData, and ClassData for Parameterized Tests
Parameterized tests in xUnit allow you to run the same test logic with multiple data sets, reducing code duplication and improving coverage. While [InlineData] is convenient for simple cases, [TheoryData], [MemberData], and [ClassData] provide more flexibility for complex or dynamic data.
TheoryData is a strongly-typed collection that you can populate manually. It's useful when you have a fixed set of test cases that are too complex for [InlineData].
```csharp public class CalculatorTheoryData : TheoryDataCalculatorTheoryData() { Add(1, 2, 3); Add(2, 3, 5); Add(10, -5, 5); } }
[Theory] [ClassData(typeof(CalculatorTheoryData))] public void Add_ReturnsSum(int a, int b, int expected) { var calculator = new Calculator(); var result = calculator.Add(a, b); Assert.Equal(expected, result); } ```
MemberData allows you to reference a static property or method that returns IEnumerable. This is ideal when test data is generated dynamically or reused across multiple tests.
```csharp public static IEnumerable
[Theory] [MemberData(nameof(AddData))] public void Add_ReturnsSum(int a, int b, int expected) { var calculator = new Calculator(); var result = calculator.Add(a, b); Assert.Equal(expected, result); } ```
ClassData uses a class that implements IEnumerable. This is best when data is complex or needs to be reused across multiple test classes.
```csharp public class CalculatorData : IEnumerableGetEnumerator() { yield return new object[] { 1, 2, 3 }; yield return new object[] { 2, 3, 5 }; yield return new object[] { 10, -5, 5 }; }
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }
[Theory] [ClassData(typeof(CalculatorData))] public void Add_ReturnsSum(int a, int b, int expected) { var calculator = new Calculator(); var result = calculator.Add(a, b); Assert.Equal(expected, result); } ```
When choosing between these, prefer [MemberData] for simple dynamic data, [ClassData] for reusable or complex data, and [TheoryData] for strongly-typed collections. Avoid using [InlineData] for more than a handful of parameters or when data is generated at runtime.
[MemberData] or [ClassData] over [InlineData] when you have many test cases or data that changes frequently. This makes tests easier to maintain and extend.ITestOutputHelper for Capturing Test Output
When debugging failing tests, especially in CI environments, having access to test output is invaluable. xUnit provides ITestOutputHelper to capture and display output from tests. This interface can be injected into test class constructors or test methods, and its WriteLine method writes to the test runner's output.
Basic Usage
```csharp public class CalculatorTests { private readonly ITestOutputHelper _output;
public CalculatorTests(ITestOutputHelper output) { _output = output; }
[Fact] public void Add_ReturnsSum() { _output.WriteLine("Starting test Add_ReturnsSum"); var calculator = new Calculator(); var result = calculator.Add(1, 2); _output.WriteLine($"Result: {result}"); Assert.Equal(3, result); } } ```
Using with Parameterized Tests
``csharp [Theory] [InlineData(1, 2, 3)] [InlineData(2, 3, 5)] public void Add_ReturnsSum(int a, int b, int expected) { _output.WriteLine($"Testing {a} + {b} = {expected}"); var calculator = new ``Calculator(); var result = calculator.Add(a, b); Assert.Equal(expected, result); }
Best Practices - Use ITestOutputHelper for diagnostic messages, not for logging large amounts of data. - Avoid using it in production code; it's only for test output. - In CI, captured output can be viewed in test reports, making it easier to diagnose failures. - Do not store ITestOutputHelper in static fields; it is per-test instance.
Common Pitfall Forgetting to inject ITestOutputHelper into the constructor will cause a test failure because xUnit cannot resolve the dependency. Always add it as a constructor parameter.
Integration with Logging You can also integrate ITestOutputHelper with logging frameworks like Serilog or NLog by creating a custom sink that writes to ITestOutputHelper. This allows you to capture application logs during tests.
```csharp public class TestOutputHelperSink : ILogEventSink { private readonly ITestOutputHelper _output;
public TestOutputHelperSink(ITestOutputHelper output) { _output = output; }
public void Emit(LogEvent logEvent) { _output.WriteLine(logEvent.RenderMessage()); } } ```
Then configure your logger to use this sink in test setup.
Parallel Test Execution Configuration in xUnit
xUnit runs tests in parallel by default to speed up execution, but this can lead to issues when tests share state or resources. Understanding and configuring parallel execution is crucial for reliable CI pipelines.
Default Behavior - xUnit runs tests within the same test collection sequentially. - Different test collections run in parallel. - By default, all tests in a class belong to the same collection (the class itself).
Controlling Parallelism You can configure parallel execution at the assembly level using the CollectionBehavior attribute.
```csharp // Disable parallelization entirely [assembly: CollectionBehavior(DisableTestParallelization = true)]
// Limit max threads [assembly: CollectionBehavior(MaxParallelThreads = 4)] ```
Test Collections Use [Collection] attribute to group tests that should not run in parallel.
```csharp [Collection("Database Tests")] public class DatabaseTests1 { // Tests that access the same database }
[Collection("Database Tests")] public class DatabaseTests2 { // Tests that access the same database } ```
Collection Fixtures Combine [CollectionDefinition] with ICollectionFixture to share setup and teardown across tests in a collection.
```csharp [CollectionDefinition("Database Tests")] public class DatabaseTestCollection : ICollectionFixture
public class DatabaseFixture : IDisposable { public DatabaseFixture() { // Initialize database connection }
public void Dispose() { // Clean up } }
[Collection("Database Tests")] public class DatabaseTests : IClassFixture
Best Practices - Keep tests independent to maximize parallelization. - Use collections for tests that must share state (e.g., database, file system). - Avoid using [Collection] unnecessarily as it reduces parallelism. - Set MaxParallelThreads to a reasonable number based on your CI environment (e.g., number of CPU cores).
Common Pitfall Forgetting to disable parallelization for tests that mutate shared static state can cause flaky tests. Always isolate shared resources.
Debugging Parallel Issues If you suspect parallel execution issues, temporarily disable parallelization and see if tests pass consistently. Then gradually re-enable while isolating problematic tests into collections.
MaxParallelThreads to match the number of CPU cores available. Use collections sparingly to maximize throughput while ensuring test isolation.CollectionBehavior and test collections to balance speed and reliability, especially in CI environments.Test Passes Locally but Fails in CI — The Shared Fixture Trap
UseInMemoryDatabase("OrderTests_" + Guid.NewGuid()).
Also added a [Collection] attribute to force those tests to run sequentially, preventing any shared state bleed across unrelated tests.- Always give in-memory databases a unique name per fixture instance using
Guid.NewGuid(). - Understand xUnit's default parallel execution model — shared resources need explicit isolation.
- A test that passes solo but fails in a batch is almost always a shared-state problem, not a logic bug.
for (int i=0; i<100; i++) { RunTest(); } inside a single [Fact].
Then check for missing awaits, shared mutable state, or non-thread-safe mocks.dotnet test runs them parallel.
Add dotnet test --settings sequential.runsettings to confirm.
Fix by adding [Collection] to isolate tests that share resources.dotnet test --list-tests to verify xUnit sees your tests.
If not, rebuild the project.dotnet test --list-testsdotnet test --verbosity detailed | findstr TestClass| File | Command / Code | Purpose |
|---|---|---|
| ProjectSetup.sh | mkdir OrderProcessingApp && cd OrderProcessingApp | Setting Up a Real xUnit Project |
| OrderCalculatorTests.cs | namespace OrderProcessing.Core | Fact vs Theory |
| OrderServiceTests.cs | namespace OrderProcessing.Core | Mocking Dependencies With Moq |
| OrderRepositoryTests.cs | namespace OrderProcessing.Core | Test Lifecycle with IClassFixture |
| OrderCalculatorTheoryTests.cs | using Xunit; | Data-Driven Testing with MemberData and ClassData |
| ParallelCollectionExample.cs | using Xunit; | Parallel Test Execution |
| CustomAssertionExample.cs | using Xunit.Sdk; | Custom Test Runners |
| LazySharedContext.cs | using Xunit; | Shared Context Without IClassFixture |
| LeakyFixture.cs | public class LeakyFixture | Why Your Test Fixtures Are Leaking State |
| LazyConfig.cs | public static class TestConfig | Skipping the Fixture Factory |
| AntiPatternTest.cs | public class CalculatorTests | Anti-Pattern |
| ParameterizedTests.cs | public class CalculatorTheoryData : TheoryData | TheoryData, MemberData, and ClassData for Parameterized Test |
| TestOutputHelperExample.cs | using Xunit; | ITestOutputHelper for Capturing Test Output |
| ParallelConfig.cs | [assembly: CollectionBehavior(DisableTestParallelization = false, MaxParallelThr... | Parallel Test Execution Configuration in xUnit |
Key takeaways
new you can't unit test it in isolation.Interview Questions on This Topic
Explain the difference between [Fact] and [Theory] in xUnit. When would you use each?
[Fact] is used for a single, unconditional test scenario — it takes no parameters. [Theory] is used for parameterised tests that run the same logic against multiple sets of data supplied via [InlineData], [MemberData], or [ClassData]. Use [Fact] for edge cases and single assertions. Use [Theory] when you want to verify behaviour across a range of inputs, like testing a discount calculator with different percentages.Frequently Asked Questions
20+ years shipping production .NET services in enterprise systems. Lessons pulled from things that broke in production.
That's Testing. Mark it forged?
12 min read · try the examples if you haven't