Lesson 50 of 93 · 6 min read · Updated

Removing Order Dependence from Unit Tests: Fresh State, Fake Clocks and Unique Names

A test that passes only when it runs after another test is a time bomb. It works on your machine, then fails in CI when the runner picks a different order or runs classes in parallel. This lesson states the rule every unit test should follow, shows the four conditions that make it possible, and compares a design that needs no workarounds with a legacy class whose static state forces you to reset counters and turn off parallelism.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2 (Apache-2.0; 8.x is commercial)
  4. Microsoft.Extensions.TimeProvider.Testing 11.0.0 (provides FakeTimeProvider)

The Rule and Its Four Conditions

Every test must pass when it runs:

  1. on its own,
  2. in any order relative to other tests,
  3. in parallel with other tests, wherever parallelism is allowed.

You should not rely on the order the runner happens to use today. xUnit gives no ordering guarantee between tests, and by default it runs different test classes in parallel. A suite that depends on order will break when someone adds a test, renames one, or runs a single test from the IDE.

Four conditions make order independence possible:

  1. Fresh state in every test.
  2. No shared mutable globals, such as static fields that tests change.
  3. Unique names for shared resources: database keys, file names, queue names.
  4. A controlled clock and controlled randomness.

Fresh State Through Design

The ReportGenerator class builds report lines from a title, a total, the current date and a sequence number. It takes its two dependencies, the clock and the sequence, through the constructor:

M06.BestPractices/ReportGenerator.cs

public interface IReportSequence
{
int Next();
}

/// <summary>Counter used in production; increments per instance.</summary>
public sealed class InMemoryReportSequence : IReportSequence
{
private int _current;
public int Next() => Interlocked.Increment(ref _current);
}

public sealed class ReportGenerator(TimeProvider timeProvider, IReportSequence sequence)
{
private static readonly CultureInfo ReportCulture = CultureInfo.GetCultureInfo("tr-TR");

public string Generate(string title, decimal total)
{
ArgumentException.ThrowIfNullOrWhiteSpace(title);

var stamp = timeProvider.GetLocalNow().ToString("yyyyMMdd", CultureInfo.InvariantCulture);
var number = sequence.Next();

return string.Create(
ReportCulture,
$"{stamp}-{number:D4} | {title.ToUpper(ReportCulture)} | {total:0.00}");
}
}

The sequence counter lives in an instance, not in a static field. A new InMemoryReportSequence always starts at zero. That one design choice means each test can build its own generator and get a predictable result:

M06.BestPractices.Tests/OrderIndependenceTests.cs

[Fact]
public void GOOD_FreshStatePerTest_A()
{
// Each test builds its own ReportGenerator, so there is no order dependence.
var sut = new ReportGenerator(
new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, 9, 0, 0, TimeSpan.Zero)),
new InMemoryReportSequence());

sut.Generate("Aylık Satış", 1_500m).Should().Be("20260314-0001 | AYLIK SATIŞ | 1500,00");
}

[Fact]
public void GOOD_FreshStatePerTest_B()
{
// This test gives the same result whether it runs BEFORE or AFTER A.
var sut = new ReportGenerator(
new FakeTimeProvider(new DateTimeOffset(2026, 3, 14, 9, 0, 0, TimeSpan.Zero)),
new InMemoryReportSequence());

sut.Generate("Aylık Satış", 1_500m).Should().Be("20260314-0001 | AYLIK SATIŞ | 1500,00");
}

Both tests expect sequence number 0001. Run A alone, B alone, A then B, B then A, or both at the same time: the result is the same. The report culture is fixed to tr-TR, which is why the total prints as 1500,00 with a comma and why the title uses Turkish upper-casing. Because the culture is set in code, the output does not depend on the machine's regional settings.

Unique Names and a Controlled Clock

Tests that touch shared resources, such as files, tables or queues, collide when two tests use the same name. Generate a unique name per test instead of hard-coding one:

M06.BestPractices.Tests/OrderIndependenceTests.cs

[Fact]
public void GOOD_UniqueResourceNamesPreventCollisions()
{
// Generate unique names for shared resources such as files, tables and queues.
var first = $"report-{Guid.NewGuid():N}.csv";
var second = $"report-{Guid.NewGuid():N}.csv";

first.Should().NotBe(second);
}

The clock is the other hidden shared resource. A test that reads the real time can pass all day and fail when it runs at midnight, at the end of a month, or during a daylight saving change. FakeTimeProvider lets the test choose the time and move it forward:

M06.BestPractices.Tests/OrderIndependenceTests.cs

[Fact]
public void GOOD_ControlledClockRemovesTimeFlakiness()
{
// A test using the real clock breaks at midnight or at a daylight saving change.
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 12, 31, 23, 59, 59, TimeSpan.Zero));
var sut = new ReportGenerator(clock, new InMemoryReportSequence());

var before = sut.Generate("Year End", 10m);
clock.Advance(TimeSpan.FromSeconds(1));
var after = sut.Generate("Year Start", 10m);

before.Should().StartWith("20261231");
after.Should().StartWith("20270101");
}

The test crosses a year boundary on purpose, one second before midnight on 31 December. With the real clock you could never test this reliably. With a fake clock it is a two-line setup. The fake clock's local time zone is UTC by default, so the result does not depend on where the CI agent runs.

The Smell: Static State Forces Workarounds

Now compare a legacy version of the same generator. Its counter is a static field:

M06.BestPractices/Legacy/LegacyReportGenerator.cs

public sealed class LegacyReportGenerator
{
// static mutable state: the number one source of order dependence.
private static int _runCount;

public string Generate(string title, decimal total)
{
_runCount++;

// Hidden time dependency.
var stamp = DateTime.Now.ToString("yyyyMMdd");

return $"{stamp}-{_runCount:D4} | {title.ToUpperInvariant()} | {total:0.00}";
}

/// <summary>A temporary door opened so tests can reset the counter.</summary>
public static void ResetCounterForTests() => _runCount = 0;
}

Every instance shares one counter. If one test calls Generate twice, the next test starts at 3, not 1. To keep the tests stable, the test class has to reset the counter before and after each test, and it has to opt out of parallel execution:

M06.BestPractices.Tests/OrderIndependenceTests.cs

[CollectionDefinition("Legacy Static State", DisableParallelization = true)]
public sealed class LegacyStaticCollection;

[Collection("Legacy Static State")]
public class LegacyStaticStateTests : IDisposable
{
public LegacyStaticStateTests() => Legacy.LegacyReportGenerator.ResetCounterForTests();

public void Dispose()
{
Legacy.LegacyReportGenerator.ResetCounterForTests();
GC.SuppressFinalize(this);
}

[Fact]
public void FirstCall_UsesSequenceNumberOne()
{
var sut = new Legacy.LegacyReportGenerator();

sut.Generate("Report", 1m).Should().Contain("-0001 |");
}

[Fact]
public void SecondCall_UsesSequenceNumberTwo()
{
var sut = new Legacy.LegacyReportGenerator();

sut.Generate("Report", 1m);

sut.Generate("Report", 1m).Should().Contain("-0002 |");
}
}

xUnit creates a new instance of the test class for every test, so the constructor and Dispose run around each test. That is where the reset happens. DisableParallelization = true stops this collection from running alongside other collections, because any other test that uses LegacyReportGenerator at the same time would change the shared counter.

Both workarounds are a code smell. ResetCounterForTests is a production method that exists only for tests. Disabling parallelism makes the whole suite slower. And the reset only protects tests that know about it: a new test in another class that forgets the reset will fail randomly. The fix belongs in the design, not in the tests. Moving the counter into an injected IReportSequence, as ReportGenerator does, removes the need for both workarounds. The last lesson in this section shows how to make that change safely.

Summary

  1. Every test must pass alone, in any order and in parallel; never rely on the runner's current order.
  2. Fresh state per test, no shared mutable globals, unique resource names and a controlled clock make that possible.
  3. Inject dependencies such as counters and clocks so each test can build an isolated instance.
  4. FakeTimeProvider lets tests set and advance time, including across midnight and year boundaries.
  5. Resetting static fields and disabling parallelism are workarounds that signal a design problem; fix the design.