Debugging flaky .NET tests: reproducing with repeat runs and constrained resources, classifying causes (time, ordering, shared state, parallelism, async races, external dependencies), xUnit collections and parallelism, blame-hang diagnostics, quarantine policy and permanent fixes.
Flaky tests are a measurement problem first. I collect results from every CI run (TRX or JUnit reports) and rank tests by failure rate, so I know which tests flake and how often; a pass on re-run means flaky, not fixed. Then I reproduce by repetition: run the suspect test or class hundreds of times, on a constrained agent, in random order. The causes are nearly always one of a few: wall-clock time, shared state (statics, a shared database row), test order, parallelism across xUnit collections, async races with sleep-based waits, or a real external dependency. Diagnostics come from ITestOutputHelper logs and --blame-hang-timeout dumps. Tests I can't fix quickly get quarantined with an owner, an issue and a deadline, never blanket retries. The trade-off: a few days of focused work versus a team that has stopped trusting red builds.
"When people start clicking re-run, the real damage is that a red build no longer means anything, so a genuine regression gets re-run too. My first step is data, not guesses. I make sure every CI run publishes test results, TRX or JUnit, and I pull a report of failures per test over the last few hundred runs. Azure DevOps has flaky-test detection built in; with GitHub Actions I aggregate the reports myself. Usually it's a handful of tests causing most of the pain.
Then I reproduce. 'Passes locally' usually means 'passes on a fast, idle machine, alone'. So I run the test in a loop five hundred times, then the whole class, then the whole assembly with parallelism, on a container limited to two CPUs. For example, at [company] we had [a dozen] tests failing about [8%] of runs. Repetition showed three patterns. Some read
DateTime.UtcNowand failed near midnight UTC, which is 11 am in Sydney, so they failed every morning. Some shared a static in-memory cache between two test classes that xUnit ran in parallel. And a few usedTask.Delay(200)to wait for a background handler. We fixed them withTimeProvider, by isolating the cache per test, and by awaiting a signal instead of sleeping. Failure rate went from [8%] to under [0.5%] in [two weeks].The mistake I see is turning on automatic retries for the whole suite. That hides flakiness instead of fixing it, and it hides real intermittent bugs in the product too, like race conditions. I quarantine individual tests, each with an owner and an issue, and the rule is it's fixed or deleted within a sprint. A flaky test is a bug, either in the test or in the code."
| Pattern in the data | Likely cause | First check |
|---|---|---|
| Fails at certain times of day or month | Wall-clock time, time zones | DateTime.Now / UtcNow usage |
| Fails only when run with others | Shared state, order dependence | Statics, shared DB rows, fixtures |
| Fails more on busy agents | Async race, timing assumptions | Task.Delay / Thread.Sleep waits |
| Fails with "address in use" / file locked | Fixed ports, shared temp files | Hard-coded ports and paths |
| Hangs then times out | Deadlock, unawaited task, missing cancellation | --blame-hang-timeout dump |
| Fails with network errors | Real external dependency | Calls to real third-party services |
| Product race condition | Genuine concurrency bug | Reproduce outside tests |
| Technique | How |
|---|---|
| Repeat a single test | Loop dotnet test --filter "FullyQualifiedName~X" or a [Theory] with many rows |
| Repeat with neighbours | Run the class or assembly repeatedly |
| Constrain resources | docker run --cpus=2 for the test run |
| Change order | Randomise or reverse test order; run classes alone |
| Turn parallelism off | xunit.runner.json "parallelizeTestCollections": false; if it stops failing, it's shared state |
| Capture hangs | dotnet test --blame-hang-timeout 2m --blame-hang-dump-type full |
| Rule | Why |
|---|---|
| Quarantine per test, never per suite | Keeps the rest of the signal |
| Owner, issue link and deadline | Prevents a permanent graveyard |
| Quarantined tests still run and report | You can see when they are fixed |
| Fix or delete within a sprint | Flaky coverage is worse than honest absence |
A [120-developer] .NET monorepo had a [9%] pipeline failure rate from flaky tests and an average of [1.6] re-runs per PR. Ranking by failure rate showed [14] tests caused [90%] of it. After fixing time, shared-state and sleep-based waits, the flaky failure rate fell below [0.5%] and median PR time to merge dropped by [40] minutes.
Checks whether the candidate debugs flaky tests systematically from data, knows the common technical causes in .NET test suites, and sets a quarantine policy that keeps the build trustworthy.
Green flags
--blame-hang-timeout, test output logging and Testcontainers logsRed flags
A test is deterministic only if everything it depends on is controlled. Flakiness comes from anything uncontrolled:
+--------------------+
| the test |
+---------+----------+
|
+--------+--------+---------+-----------+------------+
| | | | | |
clock threads shared order resources network
/timing state (ports, (real
(statics, files, services)
DB rows) CPU)
The fix is always to bring one of those under control.
In xUnit (v2 and v3), each test class is a test collection by default. Collections run in parallel; tests inside a collection run sequentially. Consequences:
[Collection("Database")] on several classes puts them in one collection so they run sequentially and can share an ICollectionFixture<T>.IClassFixture<T> is created once per class; mutable state inside it leaks between that class's tests.NUnit and MSTest default to no parallelism unless configured ([Parallelizable], [assembly: Parallelize]), so moving frameworks can expose hidden shared state.
test: trigger -> sleep(200ms) -> assert
product: trigger -> queue -> (busy agent: 350 ms) -> handled
The sleep encodes a guess about scheduling. On a loaded agent the guess is wrong. Replace with an awaited signal (TaskCompletionSource, channel) or a polling assertion with a timeout for genuinely eventual systems.
DateTime.UtcNow.Date changes at 10 or 11 am in Sydney, so a test comparing "today" computed twice can fail during that second. Month-end, leap days and daylight-saving changes produce rare failures. Inject TimeProvider; use FakeTimeProvider in tests.
WebApplicationFactory uses an in-memory TestServer (no port). If you need Kestrel, bind to port 0 and read the assigned port.Path.GetTempFileName() or a per-test directory, never a fixed path.ITestOutputHelper (xUnit) or TestContext.Current.TestOutputHelper in v3 captures logs per test; route ILogger to it so the app's logs appear with the failure.dotnet test --blame-hang-timeout 2m kills a hung test host and collects a dump plus the sequence of tests that ran; --blame-crash does the same for crashes. Open with dotnet-dump analyze (clrstack -all) or Visual Studio.Microsoft.Testing.Platform has a retry extension and many CI systems can re-run failed tests. Used narrowly (a quarantined test, a known infrastructure blip with tracking) it is pragmatic. Used globally it turns a 10% flaky test into a green build and hides product race conditions. Always record the retry so the data still shows the flake.
[Collection] or by removing the static.TaskCompletionSource.docker run --cpus=1 and compare failure rates.--blame-hang-timeout 30s and write a test that deadlocks with .Result; open the dump and find the blocked thread.Three typical flaky tests and their fixes, in one xUnit v3 file with the code under test.
// Shop/FlakySources.cs (code under test)
namespace Shop;
public sealed class PriceCache
{
// FLAKY CAUSE 1 (before): public static readonly Dictionary<string, decimal> Prices = new();
// Shared across parallel test classes. Fixed: instance state, one cache per test.
private readonly Dictionary<string, decimal> _prices = new();
public void Set(string sku, decimal price) => _prices[sku] = price;
public int Count => _prices.Count;
}
public sealed class DailyReport(TimeProvider time)
{
// FLAKY CAUSE 2 (before): DateTime.UtcNow.Date read twice could cross midnight UTC (10-11 am Sydney).
public string FileName() => $"report-{time.GetUtcNow():yyyy-MM-dd}.csv";
}
public sealed class OrderEvents
{
public event Func<Guid, Task>? OrderPlaced;
// Fire-and-forget dispatch, like many in-process event buses.
public void Publish(Guid orderId) => _ = Task.Run(() => OrderPlaced?.Invoke(orderId) ?? Task.CompletedTask);
}
// Shop.Tests/FlakyFixedTests.cs
using Microsoft.Extensions.Time.Testing;
using Shop;
using Xunit;
namespace Shop.Tests;
public sealed class PriceCacheTests
{
[Fact]
public void Set_AddsOneEntry()
{
var cache = new PriceCache(); // new instance per test: nothing shared with other classes
cache.Set("SKU-1", 9.95m);
Assert.Equal(1, cache.Count);
}
}
public sealed class DailyReportTests
{
[Fact]
public void FileName_UsesUtcDate()
{
// Controlled clock, set one second before midnight UTC: the old version failed here.
var time = new FakeTimeProvider(new DateTimeOffset(2026, 11, 21, 23, 59, 59, TimeSpan.Zero));
Assert.Equal("report-2026-11-21.csv", new DailyReport(time).FileName());
}
}
public sealed class OrderEventsTests
{
[Fact]
public async Task Publish_InvokesHandler()
{
var events = new OrderEvents();
var handled = new TaskCompletionSource<Guid>(TaskCreationOptions.RunContinuationsAsynchronously);
events.OrderPlaced += id => { handled.TrySetResult(id); return Task.CompletedTask; };
var orderId = Guid.NewGuid();
events.Publish(orderId);
// FLAKY CAUSE 3 (before): await Task.Delay(200); Assert.True(called);
// Fixed: await the effect, with a real-time guard so a bug fails rather than hangs.
var received = await handled.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
Assert.Equal(orderId, received);
}
}
// xunit.runner.json: temporarily turn off parallel collections to confirm a shared-state diagnosis.
{
"$schema": "https://xunit.net/schema/current/xunit.runner.schema.json",
"parallelizeTestCollections": false
}
# Reproduce: loop one test 500 times on 2 CPUs and count failures; capture a dump if it hangs.
for i in $(seq 1 500); do
docker run --rm --cpus=2 -v "$PWD":/src -w /src mcr.microsoft.com/dotnet/sdk:10.0 \
dotnet test --filter "FullyQualifiedName~OrderEventsTests" --blame-hang-timeout 2m || echo FAIL >> fails.txt
done
wc -l fails.txt
Task.Delay from 200 ms to 2 seconds. Why it is wrong: the suite gets slower and the race still exists. Instead: await a signal or poll with a timeout.[Collection] when sharing is intended.Flakiness is an organisational problem as much as a technical one. Each flaky test teaches the team to ignore red builds, and that cost compounds: reviewers stop looking at failures, real regressions get re-run into green. The senior response is to make flakiness visible (a failure-rate report everyone can see), give it an owner, set a policy (quarantine with a deadline, no global retries), and then fix the handful of tests causing most of the pain.
I also prevent new ones: a repeat-run job for new or changed tests (run them 50–200 times before merge or nightly), analyser rules against DateTime.Now and blocking waits, and a testing guideline that bans sleep-based waits. That moves the cost from incident to review.
| Response | When it fits | Cost | When not to |
|---|---|---|---|
| Fix the root cause | Always the goal | Engineer time | Never skip it |
| Quarantine one test | Cause not found within a day | Temporary lost coverage | Without owner and deadline |
| Narrow, recorded retry | Known infrastructure blip being worked on | Hides some signal | As a permanent global setting |
| Delete the test | Low-value test, costly to fix | Lost coverage | Tests guarding critical paths |
| Repeat-run gate for new tests | Large suites with recurring flakiness | CI minutes | Tiny suites |
I measure it by flaky failure rate per run, re-runs per PR and the size of the quarantine list over time.
Measure first. Collect TRX or JUnit reports from every CI run. A test that fails and then passes on the same commit is flaky. Rank tests by flaky rate.
Reproduce the failure: run the test in a loop (50 to 200 times), run it in parallel with its neighbours, run it on limited CPU, and use --blame-hang-timeout for hangs. The usual causes are time (DateTime.Now, Task.Delay waits), shared state, test order, parallelism, culture or time zone, and real network calls.
Quarantine visibly: tag the test so the release gate filters it out, but keep running and reporting it. Give it an owner, a ticket and a deadline, or delete it.
Prevent new ones with TimeProvider, banned-API analysers, the xUnit analysers and a flaky-rate dashboard. The trade-off is that quarantine unblocks releases but lowers coverage, so it must be temporary.
I inject TimeProvider instead of reading DateTime.UtcNow. It is the built-in clock abstraction since .NET 8: GetUtcNow(), GetTimestamp(), CreateTimer() and LocalTimeZone. Production registers TimeProvider.System; tests use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing, where I call SetUtcNow or Advance(TimeSpan.FromDays(14)) to move virtual time instantly. Timers and delays also take the provider (Task.Delay(delay, time, ct), new PeriodicTimer(period, time)), so a one-hour schedule is tested in milliseconds.
Advance fires timers synchronously but continuations may run on another thread, so await a signal from a fake, not Thread.Sleep.The trade-off: one more constructor parameter, in exchange for tests that are fast, deterministic and independent of the day they run.
Async tests should be async Task methods that await the code under test; blocking with .Result or .Wait() hides exceptions inside AggregateException and can deadlock, and async void can't be awaited at all. I test cancellation by cancelling a token and asserting with Assert.ThrowsAnyAsync<OperationCanceledException> (which also catches TaskCanceledException). For background work I never sleep: fakes signal through a TaskCompletionSource or Channel, and the test awaits that signal. Every async test has a guard timeout linked to xUnit v3's TestContext.Current.CancellationToken, so a bug fails in seconds instead of hanging the pipeline. For a BackgroundService, I call StartAsync, feed the channel, await the effect, then StopAsync.
The trade-off: slightly more test plumbing (gated fakes, signals) in exchange for tests that are deterministic on any CI agent.
How to tell it (STAR)
**S:** At [company], about one CI run in eleven failed on random tests and people had got used to re-running; two real regressions slipped through that way in a month. **T:** I took ownership of getting the build trustworthy again. **A:** I aggregated results from 300 runs and found 14 tests caused 90% of failures, quarantined them with owners, then reproduced them by looping in a throttled container. The causes were midnight-UTC date comparisons, a static cache shared across parallel classes, sleep-based waits and a `.Result` deadlock. We fixed each and added a nightly repeat-run check plus analyser rules. **R:** Flaky failures dropped from [9%] to under [0.5%], re-runs per PR fell from [1.6] to [0.1], and the quarantine list was empty in two weeks.
Last updated 23 Nov 2026.