A team-level approach to flaky tests in .NET: measuring flakiness from CI test reports, reproducing failures (loops, parallelism, limited CPU, blame options), the common root causes, a visible quarantine with an owner and deadline, and prevention with TimeProvider, banned-API analysers, xUnit analysers and a flaky-rate dashboard.
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.
"A flaky test is one that passes and fails on the same code. The real damage isn't the red build, it's that people learn to click re-run and stop trusting failures, including real ones. So I treat it as a reliability problem with data. I publish TRX results from every CI run (
dotnet test --logger trx) into Azure DevOps Test Analytics, or a test reporter on GitHub. A test that failed and then passed on the same commit is flagged, and I rank tests by flaky rate. Usually five or six tests cause most of the pain.For example, at [company] our [service] pipeline was failing about [x]% of runs with no code change. I took the worst offender and ran it 200 times in a loop: it passed every time on its own. Run with its class in parallel on one CPU, it failed about one time in thirty. The cause was a static list shared by two test classes, plus a
Thread.Sleep(500)waiting for a background worker that took longer on a loaded agent. We moved the state into a per-test fixture, replaced the sleep with awaiting aTaskCompletionSourcesignalled by the worker, and usedFakeTimeProviderfor the timer. Re-runs dropped from [x]% to [y]%.While a fix is in progress, I quarantine visibly. The test gets
[Trait("Category", "Quarantine")], the release gate runs with--filter Category!=Quarantine, and a separate non-blocking job still runs and reports the quarantined tests. Every one has an owner, a ticket and a two-week deadline, after which it's fixed or deleted. The mistake I see is turning on automatic retries and calling it solved. That hides real race conditions that will also happen in production. Then I stop new ones: banned-API analysers forDateTime.NowandThread.Sleepin test projects, the xUnit analysers, and a flaky-rate number on the team dashboard with a target, say under 1% of runs. Flakiness is a bug in the test or in the product, and both are worth finding."
| Cause | Typical symptom | Fix |
|---|---|---|
| Time | Fails near midnight, month end or daylight-saving changes; timeouts on slow agents | Inject TimeProvider; FakeTimeProvider.Advance in tests |
| Sleeps as synchronisation | Fails only on loaded agents | Await a signal (TaskCompletionSource, channel), or poll with a deadline |
| Shared state (static fields, one database) | Fails only when run with other tests | Per-test data, fixtures, Respawn or a database per class |
| Order dependence | Passes alone, fails in the suite | Each test arranges its own state |
| Parallelism | Fails with more cores or fewer | Proper fixture scopes; unique ports and file names |
| Culture or time zone | Fails on one agent image | Set culture explicitly; use UTC; test time zones on purpose |
| Real network or third parties | Fails in bursts | WireMock.Net, Testcontainers |
Unawaited tasks, async void |
Random exceptions in other tests | Await everything; the xUnit analysers flag blocking calls |
| Rule | Why |
|---|---|
| Tagged, not deleted or skipped silently | It keeps running and reporting, so you know when it's fixed |
| Owner + ticket + deadline | Quarantine with no deadline becomes permanent lost coverage |
| Cap, e.g. at most 10 tests | Forces fixing over hiding |
| Product bug found? Fix the product | Some "flaky tests" are real races |
A pipeline where about 15% of runs needed a manual re-run (around 40 minutes lost per developer per day) can usually get below 2% within a sprint by fixing the top five flaky tests. The common culprits are time, sleeps and shared state.
Checks whether the candidate can lead a systematic, data-driven response to flaky tests at team level, not just fix a single test.
Green flags
TimeProvider, signals, fixtures, WireMock.Net).Red flags
A test is a function of code, test data, environment and timing. When only the code is fixed, any variation in the other three can change the result.
result = f(code, data, environment, timing)
fixed shared? agent CPU, thread scheduling,
order? culture, clock, network
time zone
Flakiness is non-determinism you didn't control. The fix is always to take control of the varying input, not to retry.
dotnet test --logger "trx" (or JUnit through a logger package) per run, published to Azure DevOps (Test Analytics shows pass rate per test and can flag flaky tests) or to a GitHub test reporter action.for i in $(seq 200); do dotnet test --filter "FullyQualifiedName~OrderWorkerTests" || break; done.docker run --cpus=1 ..., or run two suites at once. Timing bugs appear quickly.dotnet test --blame-hang-timeout 2m collects a dump of the hung test host. Open it with dotnet-dump analyze and run clrstack -all.TZ=Australia/Sydney, or a different culture, and fake the date to the October or April daylight-saving change.TimeProvider (built into .NET 8 and later). In tests, FakeTimeProvider.Advance(TimeSpan) fires due timers and completes Task.Delay(delay, timeProvider) straight away.BannedSymbols.txt in test projects: P:System.DateTime.Now, P:System.DateTime.UtcNow, M:System.Threading.Thread.Sleep(System.Int32).async void tests and bad fixture use.BackgroundService with Thread.Sleep(100). Run it 200 times under --cpus=1 and count the failures.TaskCompletionSource signal and FakeTimeProvider, then rerun the loop.DateTime.Now. Fix what lights up.--blame-hang-timeout on a deliberately deadlocked test and find the deadlock in the dump.A flaky test (sleep plus wall-clock time) and its deterministic rewrite (xUnit v3, FakeTimeProvider).
#nullable enable
using Microsoft.Extensions.Time.Testing;
using Xunit;
namespace Orders.Tests;
// ----- Code under test: expires unpaid orders after 30 minutes -----
public sealed class OrderExpiryWorker(TimeProvider clock)
{
private readonly TaskCompletionSource _firstSweep = new(TaskCreationOptions.RunContinuationsAsynchronously);
public List<Guid> Expired { get; } = [];
public Task FirstSweepCompleted => _firstSweep.Task; // a signal tests can await
public async Task RunAsync(IReadOnlyDictionary<Guid, DateTimeOffset> unpaidSince, CancellationToken ct)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1), clock);
while (await timer.WaitForNextTickAsync(ct))
{
var now = clock.GetUtcNow();
foreach (var (id, since) in unpaidSince)
if (now - since >= TimeSpan.FromMinutes(30) && !Expired.Contains(id))
Expired.Add(id);
_firstSweep.TrySetResult();
}
}
}
public sealed class OrderExpiryWorkerTests
{
// FLAKY (kept as a comment): real clock and a sleep.
// It depends on agent speed and would need to wait 30 real minutes to be meaningful.
// var worker = new OrderExpiryWorker(TimeProvider.System);
// _ = worker.RunAsync(orders, ct);
// Thread.Sleep(1500);
// Assert.Contains(id, worker.Expired);
[Fact]
public async Task Unpaid_order_expires_after_30_minutes()
{
var ct = TestContext.Current.CancellationToken;
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 11, 21, 0, 0, 0, TimeSpan.Zero));
var id = Guid.NewGuid();
var orders = new Dictionary<Guid, DateTimeOffset> { [id] = clock.GetUtcNow() };
var worker = new OrderExpiryWorker(clock);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var run = worker.RunAsync(orders, cts.Token);
clock.Advance(TimeSpan.FromMinutes(31)); // fires the timer: no waiting in real time
await worker.FirstSweepCompleted.WaitAsync(TimeSpan.FromSeconds(5), ct); // signal, with a safety deadline
Assert.Contains(id, worker.Expired);
await cts.CancelAsync();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => run);
}
}
# BannedSymbols.txt in the test project (Microsoft.CodeAnalysis.BannedApiAnalyzers)
P:System.DateTime.Now;Use TimeProvider / FakeTimeProvider
P:System.DateTime.UtcNow;Use TimeProvider / FakeTimeProvider
M:System.Threading.Thread.Sleep(System.Int32);Await a signal instead of sleeping
# Release gate skips quarantined tests; a separate non-blocking job still runs them
dotnet test --filter "Category!=Quarantine" --logger trx --blame-hang-timeout 5m
dotnet test --filter "Category=Quarantine" --logger trx || true
Skip with no owner or deadline. Why it is wrong: The coverage is gone for good and nobody notices. Instead: Use a visible quarantine trait that is still run and reported, with a ticket and an expiry.FakeTimeProvider.DateTime.Now and culture-dependent formatting in tests. Why it is wrong: They fail at midnight, around daylight-saving changes or on agents with a different locale. Instead: Use TimeProvider, UTC and an explicit culture, enforced with BannedApiAnalyzers.Flaky tests are a trust problem before they are a technical one. Once people re-run by reflex, real failures get re-run too, and the suite stops protecting releases. My approach is to make flakiness visible (a number on the dashboard), make it someone's job (an owner per quarantined test), and make the right fix the easy one (TimeProvider, fixtures, WireMock.Net, analysers). I'd also put a cap on quarantine, so it can't become a dumping ground.
I measure success by the re-run rate of the release pipeline and the median time to green. If those improve, the team's trust in the suite comes back.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Fix immediately | Cause is clear (sleep, time, shared static) | An hour or two | Never skip it when the cause is known |
| Visible quarantine | Cause unknown and releases are blocked | Temporary coverage loss; tracking | No owner or deadline available |
| Retry and report | Detection phase, to measure flaky rate | Slower runs; can hide races | As a permanent "fix" |
| Delete the test | Low value, duplicated by better tests | Lost coverage | It guards a critical path |
Wrap the resource in a fixture that implements IAsyncLifetime, so the container starts once in InitializeAsync and is removed in DisposeAsync. Then pick the sharing scope:
IClassFixture<T>: one instance per test class.ICollectionFixture<T> with [CollectionDefinition]: one instance for every class in the collection, and those classes run serially.[assembly: AssemblyFixture(typeof(T))]): one instance for the whole run, with tests still running in parallel, so the fixture must be thread-safe.Share the resource, not the state. Each test creates its own rows with unique keys, or you reset the database between tests with Respawn. Respawn is a small library that deletes data in foreign-key order and keeps the schema. The trade-off is that a wider scope gives a faster suite, but one test can leak data into another.
Choose the data strategy per test level:
Build edge cases in on purpose: Unicode names, boundary amounts, Australian daylight-saving changes. Never copy production PII into lower environments. Under the Privacy Act 1988 (APP 11), a test copy is still personal information you must protect, and a leak can be a notifiable data breach. The trade-off is that synthetic data takes effort to make realistic, but it removes a whole class of privacy risk.
How to tell it (STAR)
**S:** Our release pipeline failed on about [x]% of runs with no code change, and people had started re-running without looking. One real regression slipped through that way. **T:** I took ownership of getting the suite trustworthy again without blocking releases. **A:** I ranked tests by fail-then-pass rate, reproduced the worst ones by looping them with their neighbours on one CPU, and found sleeps, wall-clock time and shared statics. I quarantined five tests visibly with owners and deadlines, fixed them with TimeProvider, completion signals and fixtures, and added banned-API analysers and a flaky-rate dashboard. **R:** Re-runs dropped from [x]% to [y]%, median time to green fell by [n] minutes, and quarantine has stayed under [n] tests since.
Last updated 23 Nov 2026.