Lesson 51 of 93 · 7 min read · Updated

Diagnosing Flaky Tests in .NET: Time, Culture, Randomness and Fixed Waits

A flaky test passes and fails on the same code. One flaky test is enough to damage trust in the whole suite: the team learns to ignore red builds and re-run the pipeline until it turns green. This lesson walks through the most common root causes of flakiness in .NET, proves each one with a deterministic test, and shows the stable version. It ends with how to quarantine a test you cannot fix yet, and why automatic retries are not a fix.

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)

How to Diagnose a Flaky Test

None of the tests in this lesson is actually flaky. Each BAD_ test proves the root cause in a deterministic way, for example "the same instant is two different days in two time zones". Each GOOD_ test is the stable version. That way you can study flakiness without putting flaky tests in your suite.

When a test fails now and then, work through these steps:

  1. Repeat. Run the single test in a loop, for example with dotnet test --filter "FullyQualifiedName~CampaignWindow", until you see it fail.
  2. Pin. Fix the seed, the clock and the culture. If the failure disappears, the root cause is in what you pinned.
  3. Isolate. Run the test alone and then in parallel with the rest. If the results differ, there is shared state (see the previous lesson on order dependence).
  4. Fix. Use TimeProvider, isolation and bounded waits.
  5. Quarantine if you cannot fix it yet. Do not silently skip it and do not delete it.
Root causeFlaky versionStable version
Time and time zoneDateTime.NowTimeProvider + FakeTimeProvider
CultureToString("N2")ToString("N2", culture)
Random datanew Random()new Random(seed), with the seed logged
Fixed waitawait Task.Delay(100)an observable condition + WaitAsync(timeout)
Shared statea mutable static fieldfresh state per test

Root Cause 1: Time

A campaign window that reads DateTime.Now gives a result that depends on the moment the test runs, the machine's time zone and daylight saving time. A CI job that runs near midnight passes one day and fails the next. The stable class takes the clock as a dependency:

M06.BestPractices/Flaky/FlakyProneCode.cs

public sealed class CampaignWindow(DateTimeOffset startsAt, DateTimeOffset endsAt, TimeProvider time)
{
// FLAKY VERSION (do not do this):
// public bool IsOpen => DateTime.Now >= startsAt.LocalDateTime && DateTime.Now < endsAt.LocalDateTime;
public bool IsOpen
{
get
{
var now = time.GetUtcNow();
return now >= startsAt && now < endsAt;
}
}
}

The first test proves why the flaky version cannot work everywhere: one instant falls on two different calendar days.

M06.BestPractices.Tests/FlakyTestDiagnosisTests.cs

private static readonly DateTimeOffset CampaignStart = new(2026, 11, 1, 0, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset CampaignEnd = new(2026, 11, 8, 0, 0, 0, TimeSpan.Zero);

[Fact]
public void BAD_SameInstant_IsADifferentCalendarDay_InDifferentTimeZones()
{
// Proof of the root cause: the same instant is 1 November in Istanbul and 31 October in UTC.
var instant = new DateTimeOffset(2026, 10, 31, 22, 30, 0, TimeSpan.Zero);
var istanbul = TimeZoneInfo.FindSystemTimeZoneById("Europe/Istanbul");

var utcDay = instant.UtcDateTime.Date;
var istanbulDay = TimeZoneInfo.ConvertTime(instant, istanbul).Date;

istanbulDay.Should().NotBe(utcDay);
}

[Theory]
[InlineData(-1, false)] // 1 tick before the start: closed
[InlineData(0, true)] // exactly at the start: open (boundary included)
public void GOOD_CampaignWindow_UsesControlledClock_AtTheStartBoundary(long ticksFromStart, bool expected)
{
// Arrange: the TEST sets the clock; the machine and time zone do not matter.
var clock = new FakeTimeProvider(CampaignStart.AddTicks(ticksFromStart));
var sut = new CampaignWindow(CampaignStart, CampaignEnd, clock);

// Act + Assert
sut.IsOpen.Should().Be(expected);
}

With a fake clock you can test the exact boundary, one tick before the start, which is impossible with the real clock.

Root Causes 2 and 3: Culture and Randomness

amount.ToString("N2") uses CultureInfo.CurrentCulture. It produces 1.234,50 on a developer machine set to Turkish and 1,234.50 on an English CI agent. The stable version takes the culture as a parameter:

M06.BestPractices.Tests/FlakyTestDiagnosisTests.cs

[Fact]
public void BAD_SameAmount_FormatsDifferently_PerCulture()
{
// Proof of the root cause: the same number, two cultures, two different strings.
var turkish = PriceLabel.Format(1_234.5m, CultureInfo.GetCultureInfo("tr-TR"));
var english = PriceLabel.Format(1_234.5m, CultureInfo.GetCultureInfo("en-US"));

turkish.Should().Be("1.234,50");
english.Should().Be("1,234.50");
turkish.Should().NotBe(english);
}

Randomness causes the worst kind of flakiness: a bug that shows up only for one value fails once in a thousand runs and cannot be reproduced. The coupon generator therefore receives its Random from outside, so a test can pass a fixed seed:

M06.BestPractices.Tests/FlakyTestDiagnosisTests.cs

[Fact]
public void GOOD_SameSeed_ReproducesTheSameSequence()
{
// Arrange: two generators, the SAME seed.
const int seed = 20261118;
var first = new CouponCodeGenerator(new Random(seed));
var second = new CouponCodeGenerator(new Random(seed));

// Act
var firstRun = Enumerable.Range(0, 20).Select(_ => first.Next()).ToList();
var secondRun = Enumerable.Range(0, 20).Select(_ => second.Next()).ToList();

// Assert: a failing scenario can be reproduced exactly by logging the seed.
secondRun.Should().Equal(firstRun);
}

If you want the breadth of random inputs, keep them, but use a seed and write it to the test output. When a run fails, you rerun with the same seed and get the same data.

Root Cause 4: Fixed Waits

The classic flaky async test starts a background job, sleeps for 100 ms "because that should be enough", and then checks the result. On a loaded CI machine the job takes 150 ms and the test fails. The job in this example exposes its completion as an observable Task:

M06.BestPractices/Flaky/FlakyProneCode.cs

public sealed class ReportExportJob(TimeProvider time, TimeSpan processingTime)
{
private readonly TaskCompletionSource _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);

public bool IsCompleted => _completion.Task.IsCompleted;

/// <summary>Completes when the job ends: the "observable condition" a test waits on.</summary>
public Task Completion => _completion.Task;

public void Start() => _ = RunAsync();

private async Task RunAsync()
{
// A delay instead of real work; with TimeProvider the test advances the clock itself.
await Task.Delay(processingTime, time);
_completion.TrySetResult();
}
}

The stable test advances the fake clock and then waits on the condition, with an upper bound:

M06.BestPractices.Tests/FlakyTestDiagnosisTests.cs

[Fact]
public async Task GOOD_WaitOnObservableCondition_WithABoundedTimeout()
{
// Arrange
var clock = new FakeTimeProvider(CampaignStart);
var job = new ReportExportJob(clock, processingTime: TimeSpan.FromSeconds(2));
job.Start();

// Act: the test advances the clock; no sleeping.
clock.Advance(TimeSpan.FromSeconds(2));

// Assert: wait for the observable condition (Completion) for a LIMITED time.
// If the condition never arrives, the test does not hang forever; it fails after 5 s with a clear error.
await job.Completion.WaitAsync(TimeSpan.FromSeconds(5));
job.IsCompleted.Should().BeTrue();
}

WaitAsync returns as soon as the job completes, so the test is fast when things work, and it fails with a TimeoutException instead of hanging when they do not.

Quarantine, Not Skip or Retry

Sometimes you cannot fix a flaky test today. Do not delete it and do not mark it Skip, because skipped tests are forgotten. Tag it with the number of the issue that tracks it and filter it out of the main pipeline:

M06.BestPractices.Tests/FlakyTestDiagnosisTests.cs

[Fact]
[Trait("Quarantine", "ISSUE-123")]
public async Task Quarantined_ExportJob_CompletesUnderLoad()
{
var clock = new FakeTimeProvider(CampaignStart);
var jobs = Enumerable.Range(0, 20)
.Select(_ => new ReportExportJob(clock, TimeSpan.FromMilliseconds(500)))
.ToList();
jobs.ForEach(j => j.Start());

clock.Advance(TimeSpan.FromMilliseconds(500));

await Task.WhenAll(jobs.Select(j => j.Completion)).WaitAsync(TimeSpan.FromSeconds(5));
jobs.Should().OnlyContain(j => j.IsCompleted);
}
# Main pipeline: everything except quarantined tests
dotnet test M06.BestPractices.Tests --filter "Quarantine!=ISSUE-123"

# Separate quarantine job: only quarantined tests
dotnet test M06.BestPractices.Tests --filter "Quarantine=ISSUE-123"

The test still runs and its results stay visible in a separate job. When the issue is closed, remove the trait. (The example test is stable on purpose; it only demonstrates the mechanism.)

A common mistake is to configure automatic retries, such as "rerun failed tests three times in CI". A retry reports the symptom but does not fix it. Worse, it also paints a real race condition in production code green: if the code fails one time in three, the retry hides exactly the bug the test was trying to tell you about.

Summary

  1. Flaky tests destroy trust in the suite; treat each one as a bug with a root cause.
  2. Diagnose by repeating, pinning seed/clock/culture, and comparing isolated and parallel runs.
  3. Inject TimeProvider and use FakeTimeProvider instead of DateTime.Now; pass an explicit CultureInfo to formatting.
  4. Inject Random and log the seed so failures can be reproduced.
  5. Replace fixed delays with an observable condition and WaitAsync(timeout).
  6. Quarantine an unfixable test with a trait and a tracked issue; do not skip it, delete it or hide it behind retries.