The Analogy: The Test Kitchen
A test kitchen exists so that a recipe can be tried without risking the dinner service. Every trial batch gets a clean bowl and clean utensils, because a trace of yesterday's salt would make today's result meaningless — and worse, would make it inconsistently meaningless, passing on Tuesday and failing on Wednesday for reasons nobody can reconstruct.
That is xUnit's central design decision, and it surprises people coming from other frameworks: the harness constructs a new instance of your test class for every single test. Fields initialised in the constructor are therefore fresh each time, and there is no "setup method" attribute because the constructor already is one. Two tests cannot contaminate each other through instance state, which means the order they run in cannot change the result.
Some equipment is too expensive to duplicate per batch — the proving oven takes forty minutes to reach temperature. Those are fixtures: built once, shared across every test in a class or a collection, and therefore required to be read-only in practice. And when two batches genuinely need exclusive use of the same oven, you put them in the same collection so they queue rather than collide; separate collections run at the same time on different benches.
The last piece is the recipe card with variations. One procedure, several ingredient quantities, each tried separately and reported separately — that is a theory. The value of reporting them separately is that a failure names the exact quantities that broke, so you read (netMinorUnits: 103, expectedVat: 21) in the output rather than "the rounding test failed" and a guess about which input did it.
Syntax or Core Structure
A test project is a normal class library with a test SDK, a runner and the framework. The template wires all three:
dotnet new xunit -o Shop.Tests
cd Shop.Tests
dotnet add reference ../Shop/Shop.csproj
dotnet test
The system under test is ordinary code — nothing about it knows it is being tested:
// Shop/Basket.cs
public sealed class Basket
{
private readonly List<(string Sku, int UnitMinorUnits, int Quantity)> _lines = new();
public int TotalMinorUnits => _lines.Sum(line => line.UnitMinorUnits * line.Quantity);
public void Add(string sku, int unitMinorUnits, int quantity)
{
if (quantity < 1)
{
throw new ArgumentOutOfRangeException(nameof(quantity), "quantity must be 1 or more");
}
_lines.Add((sku, unitMinorUnits, quantity));
}
public int TotalAfterDiscount(int percent) =>
TotalMinorUnits - TotalMinorUnits * percent / 100;
}
And the tests. Note that there is no [SetUp] and no [TestInitialize] — the constructor runs once per test, so a field initialiser is the setup:
// Shop.Tests/BasketTests.cs
using Xunit;
public class BasketTests
{
// A brand-new Basket for every test below. No sharing, no ordering dependency.
private readonly Basket _basket = new Basket();
[Fact]
public void An_empty_basket_totals_zero()
{
Assert.Equal(0, _basket.TotalMinorUnits);
}
[Fact]
public void Adding_lines_sums_quantity_times_price()
{
_basket.Add("bolt", 250, 3);
_basket.Add("nut", 100, 2);
Assert.Equal(950, _basket.TotalMinorUnits);
}
[Theory]
[InlineData(0, 1000)]
[InlineData(10, 900)]
[InlineData(100, 0)]
public void A_discount_reduces_the_total_by_a_percentage(int percent, int expected)
{
_basket.Add("plank", 1000, 1);
Assert.Equal(expected, _basket.TotalAfterDiscount(percent));
}
[Fact]
public void A_quantity_below_one_is_rejected()
{
ArgumentOutOfRangeException error = Assert.Throws<ArgumentOutOfRangeException>(
() => _basket.Add("bolt", 250, 0));
Assert.Equal("quantity", error.ParamName);
}
}
Output: (dotnet test, abridged — the build banner, the assembly path and all durations are removed, since those vary by machine and SDK)
Passed! - Failed: 0, Passed: 6, Skipped: 0, Total: 6
Six, from four methods. The three [InlineData] rows on A_discount_reduces_the_total_by_a_percentage are three separate tests with three separate results, not one test that loops. That distinction is the whole reason to prefer a theory over a foreach inside a fact: a loop stops at the first failure and reports one line, while a theory reports every case and names the arguments of each.
Two habits are visible in the assertions. Assert.Equal(expected, actual) takes expected first — get it backwards and a failure message reads inside out, claiming your correct value was wrong. And Assert.Throws<T> returns the exception it caught, so the test can go on to check ParamName or Message; asserting only that "something threw" would still pass if the code threw a NullReferenceException for entirely the wrong reason.
Assert.Throws<T> also insists on the exact type. Pass it ArgumentException when the code throws ArgumentOutOfRangeException and the test fails despite being morally right — use Assert.ThrowsAny<ArgumentException> when a base type is genuinely what you mean.
Technical Depth: What The Harness Guarantees
The lifecycle, in order
| Hook | When | Notes |
|---|---|---|
| Constructor | Before every test | The setup method. Throwing here fails that test |
IDisposable.Dispose | After every test | Teardown, even when the test failed |
IAsyncLifetime.InitializeAsync | Before every test, after the constructor | For setup that must await |
IAsyncLifetime.DisposeAsync | After every test | For teardown that must await |
IClassFixture<T> | Once per test class | T is constructed once, injected into the constructor |
ICollectionFixture<T> | Once per collection | Shared across every class in the collection |
[CollectionDefinition] | Declares a collection | Also the unit of parallelism |
Constructors cannot be async, which is why IAsyncLifetime exists. Any setup involving a database, an HTTP call or a file goes in InitializeAsync, never in a constructor that blocks on .Result.
Parallelism, and the state that breaks it
xUnit runs test collections in parallel and the tests within a collection sequentially. By default every test class is its own collection, so classes run concurrently. Three consequences follow:
- Tests in different classes touching the same static field, the same file, or the same database row will interleave and fail intermittently.
- Putting classes in a named collection serialises them — the correct fix for a shared resource, at the cost of speed.
Console.WriteLinefrom parallel tests interleaves unreadably, which is why xUnit gives youITestOutputHelperinstead.
[Collection("database")] // these classes queue behind each other
public class OrderRepositoryTests { }
// Or turn parallelism off for the whole assembly, as a last resort:
[assembly: CollectionBehavior(DisableTestParallelization = true)]
Static mutable state is the single most common cause of a suite that passes locally and fails in CI, because CI machines have a different core count and therefore a different interleaving. If a test needs to set a static, it needs a collection.
Feeding a theory
| Source | Shape | Use it when |
|---|---|---|
[InlineData(...)] | Compile-time constants | Two to five simple cases, right above the method |
[MemberData(nameof(Cases))] | static property or method returning IEnumerable<object[]> | Cases need computing, or are shared between methods |
[ClassData(typeof(Cases))] | A class implementing IEnumerable<object[]> | A large set worth naming and reusing across classes |
TheoryData<T1, T2> | Strongly typed collection | Always — it type-checks the cases at compile time |
[Theory(Skip = "...")] | Skips every case | A whole scenario is blocked |
TheoryData<T1, T2> is worth the extra keystrokes: IEnumerable<object[]> will happily supply a string where the method wants an int and only fail at run time.
public static TheoryData<int, int> DiscountCases => new TheoryData<int, int>
{
{ 0, 1000 },
{ 10, 900 },
{ 100, 0 }
};
[Theory]
[MemberData(nameof(DiscountCases))]
public void A_discount_reduces_the_total(int percent, int expected) { }
Theory arguments appear in the test name, so they must be serialisable — primitives, strings, enums, and types implementing IXunitSerializable. Pass an arbitrary object and the cases collapse into one badly-named entry in the runner.
The assertions worth knowing
| Assertion | Checks |
|---|---|
Assert.Equal(expected, actual) | Value equality; overloads add tolerance for double and a custom IEqualityComparer<T> |
Assert.Same / NotSame | Reference identity, not equality |
Assert.Throws<T> / ThrowsAsync<T> | Exact exception type; returns the exception |
Assert.ThrowsAny<T> | T or a subclass |
Assert.Collection(items, i => ..., i => ...) | Count and each element in order |
Assert.Contains / DoesNotContain | Substrings, sequences, dictionary keys |
Assert.Empty / Single | Zero items; exactly one, and returns it |
Assert.Raises<T> | An event fired with the expected args |
Record.Exception(() => ...) | Returns the exception or null — for asserting nothing threw |
Prefer Assert.Collection over asserting Count and then indexing: it fails with the element that differed rather than an index-out-of-range in your own test code.
Traits, skipping and filtering
[Fact(Skip = "reduced-rate table for 2027 is not published yet")]
[Trait("Category", "Fast")]
public void Placeholder() { }
dotnet test --filter "Category=Fast"
dotnet test --filter "FullyQualifiedName~Basket"
dotnet test --logger "console;verbosity=detailed"
A Skip reason is a message to the next person; Skip = "broken" tells them nothing, while a reason naming the blocker tells them when it can be deleted. Commented-out tests, by contrast, are invisible to the runner and to everyone reading the report — skip them instead so the count stays honest.
Getting output out of a test
Console.WriteLine is swallowed. Inject ITestOutputHelper and write to that; the runner attaches the text to the test's result, and it is shown for failures:
public class VatTests
{
private readonly ITestOutputHelper _output;
public VatTests(ITestOutputHelper output) => _output = output;
}
v2 versus v3
xUnit v3 (packages named xunit.v3) turns test projects into executables, runs on Microsoft.Testing.Platform, and adds conveniences such as Assert.Skip for deciding to skip at run time and TestContext.Current.CancellationToken. The concepts in this lesson — facts, theories, per-test construction, fixtures, collections — are unchanged; assertion failure messages were reworded, so do not assert on them.
Real World Example: The Suite That Caught A Rounding Bug
VAT on 103p at 20% is 20.6p. Integer division says 20. The tax authority says 21. This is the shape of bug that survives code review, ships, and is eventually found by an accountant reconciling a month of invoices — and it is trivially catchable by a theory with the right case in it.
// Shop/Vat.cs
public sealed class RateTable
{
private readonly Dictionary<string, int> _percentByRegion = new();
public RateTable(IEnumerable<string> lines)
{
foreach (string line in lines)
{
string[] parts = line.Split(',');
_percentByRegion[parts[0]] = int.Parse(parts[1]);
}
}
public int PercentFor(string region) =>
_percentByRegion.TryGetValue(region, out int percent) ? percent : 20;
}
public sealed class VatCalculator
{
private readonly RateTable _rates;
public VatCalculator(RateTable rates) => _rates = rates;
public int VatMinorUnits(int netMinorUnits, string region)
{
if (netMinorUnits < 0)
{
throw new ArgumentOutOfRangeException(
nameof(netMinorUnits), "net must not be negative");
}
int percent = _rates.PercentFor(region);
return netMinorUnits * percent / 100; // truncates: the bug
}
public int GrossMinorUnits(int netMinorUnits, string region) =>
netMinorUnits + VatMinorUnits(netMinorUnits, region);
}
The rate table is expensive to build in real life — a file, or a call to a tax service — so it is a collection fixture, constructed once and shared:
// Shop.Tests/VatTests.cs
using Xunit;
using Xunit.Abstractions;
public sealed class RateTableFixture
{
public RateTableFixture()
{
// Built once for the whole collection. Read-only afterwards, by discipline.
Table = new RateTable(new[] { "standard,20", "reduced,5", "zero,0" });
}
public RateTable Table { get; }
}
[CollectionDefinition("rate table")]
public sealed class RateTableCollection : ICollectionFixture<RateTableFixture>
{
// No code. This class exists only to associate the name with the fixture type.
}
[Collection("rate table")]
public sealed class VatTests
{
private readonly VatCalculator _calculator;
private readonly ITestOutputHelper _output;
// The fixture and the output helper are both injected by the harness.
public VatTests(RateTableFixture fixture, ITestOutputHelper output)
{
_calculator = new VatCalculator(fixture.Table);
_output = output;
}
public static TheoryData<int, int> StandardRateCases => new TheoryData<int, int>
{
{ 100, 20 }, // exact
{ 103, 21 }, // 20.6 rounds up
{ 0, 0 }, // nothing owed on nothing
{ 2, 0 } // 0.4 rounds down
};
[Theory]
[MemberData(nameof(StandardRateCases))]
[Trait("Category", "Fast")]
public void Vat_at_the_standard_rate_rounds_half_up(int netMinorUnits, int expectedVat)
{
int actual = _calculator.VatMinorUnits(netMinorUnits, "standard");
_output.WriteLine("net=" + netMinorUnits + " vat=" + actual);
Assert.Equal(expectedVat, actual);
}
[Theory]
[InlineData("reduced", 5)]
[InlineData("zero", 0)]
[InlineData("atlantis", 20)] // unknown region falls back to the standard rate
[Trait("Category", "Fast")]
public void Vat_uses_the_rate_for_the_region(string region, int expectedVat)
{
Assert.Equal(expectedVat, _calculator.VatMinorUnits(100, region));
}
[Fact]
[Trait("Category", "Fast")]
public void Gross_is_net_plus_vat()
{
Assert.Equal(120, _calculator.GrossMinorUnits(100, "standard"));
}
[Fact]
[Trait("Category", "Fast")]
public void A_negative_net_amount_is_rejected()
{
ArgumentOutOfRangeException error = Assert.Throws<ArgumentOutOfRangeException>(
() => _calculator.VatMinorUnits(-1, "standard"));
Assert.Equal("netMinorUnits", error.ParamName);
}
[Fact(Skip = "reduced rate for 2027 has not been published yet")]
public void The_reduced_rate_changes_in_2027()
{
}
}
Output: (dotnet test, abridged — durations, stack traces, file paths and the build banner removed; xUnit v3 words assertion failures slightly differently)
Failed Vat_at_the_standard_rate_rounds_half_up(netMinorUnits: 103, expectedVat: 21)
Error Message:
Assert.Equal() Failure: Values differ
Expected: 21
Actual: 20
Standard Output Messages:
net=103 vat=20
Failed! - Failed: 1, Passed: 8, Skipped: 1, Total: 10
One line of the calculator changes:
return (netMinorUnits * percent + 50) / 100; // half up
Passed! - Failed: 0, Passed: 9, Skipped: 1, Total: 10
And the fast subset, for the pre-commit hook:
dotnet test --filter "Category=Fast"
Passed! - Failed: 0, Passed: 9, Skipped: 0, Total: 9
The failing line names its inputs: (netMinorUnits: 103, expectedVat: 21). That is the payoff for writing four cases as a theory instead of a loop inside one fact — the report identifies the case, the other three still ran and still passed, and the ITestOutputHelper line is attached to that test rather than mixed into a shared console. Note also that the output helper's text appeared only for the failure; passing tests keep their output unless you ask the logger for detailed verbosity.
Ten tests from five methods, and the arithmetic of the summary is worth checking against the code: four theory cases plus three plus two facts is nine runnable tests, of which one failed and eight passed, plus one skipped that is still counted. A skipped test is visible in every run, which is exactly why skipping beats commenting out — the number cannot quietly drift, and Skipped: 1 in CI is a standing reminder with a reason attached to it.
The fix, (net * percent + 50) / 100, encodes a policy: round half away from zero. There is no universally correct rounding rule for money — some jurisdictions and some contracts require half-even, and a decimal pipeline would say Math.Round(value, 2, MidpointRounding.AwayFromZero) explicitly rather than relying on an arithmetic trick. The important part is that the policy is now written down in a test, so the next person who "simplifies" the expression back to plain division gets a red build instead of a quiet undercharge.
Two costs came with the fixture, and both are deliberate. Sharing RateTable across the collection means any test that mutated it would change the results of its neighbours — fixtures must be treated as read-only, and if one needs modifying, it belongs in IClassFixture or in the constructor instead. And every class in the "rate table" collection runs sequentially with the others in it, so a collection should hold the classes that genuinely share the resource and no more.
Common Mistakes
- Expecting a setup method. xUnit has no
[SetUp]. The constructor runs before each test andDisposeafter it; async setup goes inIAsyncLifetime.InitializeAsync, never in a constructor blocking on.Result. - Sharing state through static fields or a mutable fixture. Classes run in parallel, so shared mutable state produces failures that depend on core count and appear only in CI.
- Arguments backwards in
Assert.Equal. Expected comes first. Reversed, every failure message accuses your correct value of being wrong, and the habit costs minutes on every future failure. - Looping inside a fact instead of writing a theory. The loop stops at the first bad case and hides which input caused it; a theory reports each case with its arguments.
Console.WriteLinein tests. It is swallowed by the runner and, from parallel tests, would interleave anyway. InjectITestOutputHelper.- Asserting on framework message text.
Assert.Equal("Assert.Equal() Failure...", ...)or matching an exception'sMessagebreaks on the next framework or locale update. Assert on types,ParamName, and your own error codes. - Non-deterministic tests.
DateTime.Now,Randomwithout a seed,Guid.NewGuid,Task.Delayraces and real network calls all produce tests that fail once a fortnight and get retried rather than fixed. Inject a clock and a seeded generator. - Commenting out a failing test. It disappears from the report. Mark it
Skipwith a reason, or delete it if the behaviour is genuinely gone.
Best Practices
- Name the behaviour, not the method.
Vat_at_the_standard_rate_rounds_half_uptells a reader of a CI log what broke;TestVat1sends them to the source. - One behaviour per test. Several assertions about one outcome are fine; two unrelated scenarios in one method means the second never runs once the first fails.
- Arrange, act, assert — in that order, with blank lines between. The shape makes an unfamiliar test readable in seconds, and makes a missing act step obvious.
- Use
TheoryData<...>and put the interesting cases in it. Boundaries, zero, the rounding midpoint, the empty collection and the value that used to be a bug are worth more than ten variations of the happy path. - Keep the fixture read-only and as small as possible.
IClassFixturewhen one class needs it,ICollectionFixturewhen several genuinely share a resource, and a plain constructor otherwise. - Make every test deterministic and independent. Inject clocks and random seeds, never depend on run order, and never depend on another test having run first.
- Tag the fast tests and run them constantly.
[Trait("Category", "Fast")]plusdotnet test --filtergives a sub-second loop while you work, with the slow suite reserved for CI. - Treat a flaky test as a bug in the test. Retrying it teaches the team to ignore red builds, which costs far more than the hour spent finding the shared state or the timing assumption.
Practice Exercises
- Boundaries, as a theory. Write a
Quantityvalidator that accepts 1 to 100 inclusive, then cover it with aTheoryData<int, bool>containing 0, 1, 2, 99, 100 and 101. Confirm each case appears separately in the runner output, then break the implementation toquantity < 100and check which cases go red. - Constructor and Dispose, observed. Write a test class with two facts, a constructor and
Dispose, each writing toITestOutputHelper. Run withdotnet test --logger "console;verbosity=detailed"and confirm from the output that the class was constructed twice. Then add a static counter and explain in a comment why its value is not a safe thing to assert on. - A shared, expensive fixture. Build a fixture that parses a thousand-line rate table in its constructor and exposes it read-only, share it with
IClassFixtureacross two test classes, and measure the difference against constructing it per test. Then move it toICollectionFixtureand note what you gave up. - Deterministic time. Take a method that expires a token using
DateTime.UtcNowand make it testable by injectingTimeProvider. Write tests proving the just-before, exactly-at and just-after cases using a fake time source, with noTask.Delayanywhere in the suite.