Lesson 51 of 93 · 7 min read · Updated
Diagnosing Flaky Tests in .NET: Time, Culture, Randomness and Fixed Waits
On this page
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
- .NET 11 SDK
- xUnit 2.9.3
- FluentAssertions 7.2.2 (Apache-2.0; 8.x is commercial)
- 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:
- Repeat. Run the single test in a loop, for example with
dotnet test --filter "FullyQualifiedName~CampaignWindow", until you see it fail. - Pin. Fix the seed, the clock and the culture. If the failure disappears, the root cause is in what you pinned.
- 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).
- Fix. Use
TimeProvider, isolation and bounded waits. - Quarantine if you cannot fix it yet. Do not silently skip it and do not delete it.
| Root cause | Flaky version | Stable version |
|---|---|---|
| Time and time zone | DateTime.Now | TimeProvider + FakeTimeProvider |
| Culture | ToString("N2") | ToString("N2", culture) |
| Random data | new Random() | new Random(seed), with the seed logged |
| Fixed wait | await Task.Delay(100) | an observable condition + WaitAsync(timeout) |
| Shared state | a mutable static field | fresh 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
The first test proves why the flaky version cannot work everywhere: one instant falls on two different calendar days.
M06.BestPractices.Tests/FlakyTestDiagnosisTests.cs
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
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
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
The stable test advances the fake clock and then waits on the condition, with an upper bound:
M06.BestPractices.Tests/FlakyTestDiagnosisTests.cs
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
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
- Flaky tests destroy trust in the suite; treat each one as a bug with a root cause.
- Diagnose by repeating, pinning seed/clock/culture, and comparing isolated and parallel runs.
- Inject
TimeProviderand useFakeTimeProviderinstead ofDateTime.Now; pass an explicitCultureInfoto formatting. - Inject
Randomand log the seed so failures can be reproduced. - Replace fixed delays with an observable condition and
WaitAsync(timeout). - Quarantine an unfixable test with a trait and a tracked issue; do not skip it, delete it or hide it behind retries.