A senior code review of a brittle .NET test suite: tests that cannot fail, shared static state, Thread.Sleep waits, real clock usage, over-mocking and log-text assertions, ranked by severity, with a rewrite using FakeTimeProvider, FakeLogger, real infrastructure and deterministic waits.
Ranked by severity:
async void test and a try/catch that swallows the assertion exception give false greens.Thread.Sleep(3000): slow (3 s each) and still flaky on a busy CI agent. Await a completion signal instead.DateTime.Now: time-dependent logic is untestable at boundaries. Inject TimeProvider and use FakeTimeProvider.DbContext: tests check call sequences, not behaviour, and break on every refactor.FakeLogger and assert on level, event id and structured state.The rewrite tests behaviour through real collaborators, controls time and concurrency deterministically, and fakes only the true boundaries.
"I'd review a test suite the same way I review production code: first anything that makes the result wrong, then things that make it unreliable, then slow, then brittle. The worst problem here isn't the sleep, it's tests that can't fail. One test is
async void, so the runner doesn't await it and an assertion thrown after the first await is lost; another wraps the act in atry/catch (Exception)that also catches the assertion exception. Both report green regardless. Next is the shared staticList<Order>: xUnit runs classes in parallel, so one test reads orders another test added, and the result depends on scheduling.Then the
Thread.Sleep(3000)waiting for the background processor. It costs three seconds per test, and on a loaded CI agent three seconds still isn't always enough, so it's slow and flaky. I'd make the worker signal completion, or have the test await a channel being drained with a timeout.DateTime.Nowin the code under test means the 'orders older than 24 hours expire' rule is only tested by whatever time CI happens to run; injectTimeProviderand useFakeTimeProvider.Advance. For example, at [company] [a suite like this failed every night around midnight UTC], and the cause was exactly this kind of time dependency.Finally the design issues. Mocking the
DbContextand every collaborator means the tests verify the order of calls, so a harmless refactor broke [N] tests. I'd use a real database through Testcontainers and only fake the email sender and payment gateway. And asserting\"Order 42 processed in 120ms\"through a mockedILoggerbreaks when someone edits wording;FakeLoggerfromMicrosoft.Extensions.Diagnostics.Testinglets me assert on level, event id and structured properties. A test suite that lies is worse than none, so the first two items block the merge."
public class OrderProcessorTests
{
private static readonly List<Order> Orders = new(); // 1
[Fact]
public async void Processes_pending_orders() // 2
{
var db = new Mock<OrdersDbContext>(); // 3
var repo = new Mock<IOrderRepository>();
var clock = DateTime.Now; // 4
var logger = new Mock<ILogger<OrderProcessor>>();
Orders.Add(new Order(1, clock.AddHours(-1)));
repo.Setup(r => r.GetPendingAsync()).ReturnsAsync(Orders);
var processor = new OrderProcessor(repo.Object, logger.Object);
processor.Start();
Thread.Sleep(3000); // 5
try
{
repo.Verify(r => r.GetPendingAsync(), Times.Once);
repo.Verify(r => r.MarkProcessedAsync(1), Times.Once); // 6
logger.Verify(l => l.Log(LogLevel.Information, It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, _) => v.ToString() == "Order 1 processed"), // 7
null, It.IsAny<Func<It.IsAnyType, Exception?, string>>()));
}
catch (Exception) { /* flaky on CI, ignore */ } // 8
}
}
| # | Severity | Finding | Fix |
|---|---|---|---|
| 2, 8 | Blocking: false green | async void test isn't awaited; catch (Exception) swallows assertion failures |
async Task; delete the catch |
| 1 | Blocking: wrong data / flaky | Static list shared across tests and parallel classes | Per-test state; data created in the test |
| 5 | Blocking: flaky and slow | Thread.Sleep(3000) guesses at completion |
Await a completion signal with a timeout |
| 4 | Major: untestable logic | DateTime.Now in code and test |
Inject TimeProvider; FakeTimeProvider in tests |
| 3, 6 | Major: tests the mocks | DbContext mocked, every call verified |
Real DB (Testcontainers) or in-memory fake repository; assert outcomes |
| 7 | Minor: brittle diagnostics | Log message text asserted via Mock<ILogger> |
FakeLogger: assert level, event id, structured state |
See the code example: the processor takes TimeProvider and exposes a completion signal, the repository is a small in-memory fake (or Testcontainers for the EF implementation), and logs are checked with FakeLogger.
TimeProvider injection, removing DbContext mocks.FakeLogger, and a LoggerMessage source-generated event id per log.async void tests and blocking task operations such as .Result and .Wait()), add a banned-API analyser rule for Thread.Sleep and DateTime.Now in test and production projects, and add these to the PR checklist.A nightly order-processing suite of 180 tests took 11 minutes, 9 of them in Thread.Sleep, and failed about one night in five. After the rewrite it ran in 70 seconds; turning the swallowed exceptions into real failures exposed 4 genuine bugs that had been hidden for months.
Checks whether the candidate can review tests critically, prioritise by real impact and knows modern .NET tools for deterministic tests.
Green flags
Red flags
runner calls Test() async void Test()
| |-- runs synchronously to first await
|<-- returns immediately --|
marks test PASSED |-- (later) assertion throws on thread pool
v
exception goes to SynchronizationContext / crashes or vanishes
The runner can only observe a Task. xUnit installs a context that tries to catch async void exceptions, but behaviour is fragile and the analyser (xUnit1048) flags these tests. Always async Task.
Static fields live for the whole test run in one AppDomain/AssemblyLoadContext. With xUnit running classes in parallel, two tests mutating a static List<T> can corrupt it (List<T> isn't thread-safe) or read each other's items. The symptom is tests that pass alone and fail together.
Background work should expose a way to observe completion:
TaskCompletionSource set when a batch finishes.Channel<T> the test reads from.IHostedService.StopAsync that waits for in-flight work.The test then takes as long as the work does (milliseconds) and fails clearly on timeout.
TimeProvider (.NET 8+) abstracts GetUtcNow(), timers and Task.Delay overloads. FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing lets a test set the time and Advance(TimeSpan), which fires due timers synchronously. Boundary tests (exactly 24 hours, end of month, AEST/AEDT changeover) become one-liners.
Microsoft.Extensions.Diagnostics.Testing provides FakeLogger<T> and FakeLogCollector. Each record has Level, Id, Message, Exception and StructuredState (the template values). Assert on what the log means (an event id and properties) rather than how it is worded. Mocking ILogger is awkward because LogInformation is an extension method over the generic Log<TState> call.
Mock or fake at architectural boundaries: email, payment, clocks, message brokers. Use real implementations for in-process collaborators, and real infrastructure (Testcontainers) for the database. A test that verifies MarkProcessedAsync(1) was called proves the code calls a method; a test that reads the order back and sees Processed proves the behaviour.
async void test that fails after await Task.Delay(10) and see what the runner reports; then enable the xUnit analysers.Thread.Sleep with a TaskCompletionSource signal and compare run times.FakeTimeProvider.Advance to test a 24-hour expiry at 23:59:59 and 24:00:00.Mock<ILogger> assertion to FakeLogger and assert on StructuredState.The rewritten processor and tests: injected TimeProvider, a completion signal instead of sleeping, an in-memory fake repository and FakeLogger:
// OrderProcessor.cs (code under test, after the refactor)
using Microsoft.Extensions.Logging;
namespace Orders.Processing;
public sealed record Order(int Id, DateTimeOffset CreatedAt, string Status = "Pending");
public interface IOrderRepository
{
Task<IReadOnlyList<Order>> GetPendingAsync(CancellationToken ct);
Task SaveAsync(Order order, CancellationToken ct);
}
public sealed partial class OrderProcessor(IOrderRepository repo, TimeProvider time, ILogger<OrderProcessor> logger)
{
private static readonly TimeSpan Expiry = TimeSpan.FromHours(24);
// Runs one batch and completes when it is done: tests await it instead of sleeping.
public async Task<int> ProcessBatchAsync(CancellationToken ct)
{
var now = time.GetUtcNow();
var pending = await repo.GetPendingAsync(ct);
foreach (var order in pending)
{
var status = now - order.CreatedAt >= Expiry ? "Expired" : "Processed";
await repo.SaveAsync(order with { Status = status }, ct);
LogOrderHandled(order.Id, status);
}
return pending.Count;
}
[LoggerMessage(EventId = 1001, Level = LogLevel.Information, Message = "Order {OrderId} handled as {Status}")]
private partial void LogOrderHandled(int orderId, string status);
}
// OrderProcessorTests.cs (xunit.v3, Microsoft.Extensions.TimeProvider.Testing, Microsoft.Extensions.Diagnostics.Testing)
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Time.Testing;
using Orders.Processing;
using Xunit;
namespace Orders.Processing.Tests;
// A tiny stateful fake: per test, thread-safe enough for one test, no static state.
public sealed class InMemoryOrderRepository(params Order[] seed) : IOrderRepository
{
private readonly Dictionary<int, Order> _orders = seed.ToDictionary(o => o.Id);
public Order this[int id] => _orders[id];
public Task<IReadOnlyList<Order>> GetPendingAsync(CancellationToken ct) =>
Task.FromResult<IReadOnlyList<Order>>(_orders.Values.Where(o => o.Status == "Pending").ToList());
public Task SaveAsync(Order order, CancellationToken ct) { _orders[order.Id] = order; return Task.CompletedTask; }
}
public sealed class OrderProcessorTests
{
private static readonly DateTimeOffset Start = new(2026, 11, 21, 9, 0, 0, TimeSpan.Zero);
private readonly FakeTimeProvider _time = new(Start);
private readonly FakeLogger<OrderProcessor> _logger = new();
[Fact]
public async Task Recent_order_is_processed()
{
var repo = new InMemoryOrderRepository(new Order(1, Start.AddHours(-1)));
var sut = new OrderProcessor(repo, _time, _logger);
await sut.ProcessBatchAsync(TestContext.Current.CancellationToken); // no sleep: await completion
Assert.Equal("Processed", repo[1].Status); // assert the outcome, not the calls
}
[Theory]
[InlineData(23 * 60 + 59, "Processed")] // 23:59 old
[InlineData(24 * 60, "Expired")] // exactly 24 hours
public async Task Expiry_boundary_is_exact(int ageMinutes, string expected)
{
var repo = new InMemoryOrderRepository(new Order(7, Start));
_time.Advance(TimeSpan.FromMinutes(ageMinutes)); // deterministic time travel
await new OrderProcessor(repo, _time, _logger).ProcessBatchAsync(TestContext.Current.CancellationToken);
Assert.Equal(expected, repo[7].Status);
}
[Fact]
public async Task Logs_a_structured_event_per_order()
{
var repo = new InMemoryOrderRepository(new Order(3, Start));
await new OrderProcessor(repo, _time, _logger).ProcessBatchAsync(TestContext.Current.CancellationToken);
var record = _logger.LatestRecord;
Assert.Equal(LogLevel.Information, record.Level);
Assert.Equal(1001, record.Id.Id);
// Structured values survive wording changes in the message template.
Assert.Contains(record.StructuredState!, kv => kv.Key == "OrderId" && kv.Value == "3");
}
}
async void test methods. Why it is wrong: The runner can't await them, so failures after the first await are lost or crash the run. Instead: async Task, enforced by the xUnit analysers as errors.try/catch to "stabilise" a flaky test. Why it is wrong: The test can never fail, so it hides real bugs. Instead: Fix the cause, or quarantine the test visibly with a tracked ticket.Thread.Sleep or Task.Delay to wait for background work. Why it is wrong: Too short is flaky, too long is slow, usually both. Instead: Await a completion signal, a channel or a hosted service's stop, with a timeout.DateTime.Now in production code. Why it is wrong: Time rules can't be tested at boundaries and tests vary by time zone and time of day. Instead: Inject TimeProvider, use UTC, test with FakeTimeProvider.DbContext or DbSet. Why it is wrong: LINQ translation, tracking and constraints aren't simulated, so tests pass on broken queries. Instead: A fake repository for unit tests and Testcontainers for the EF implementation.Mock<ILogger>. Why it is wrong: Breaks on wording changes and couples tests to the extension-method internals. Instead: FakeLogger with event ids and structured state, and only when the log is a requirement.When I review tests I ask one question first: can this test fail for the right reason, and only for that reason? False greens and nondeterminism are blockers; brittleness and slowness are strong requests. I also look at what the suite pushes the production code towards: needing Thread.Sleep and mocks of DbContext is the tests telling you the code lacks seams (TimeProvider, completion signals, a repository boundary).
| Smell | Severity | Fix | When it might be acceptable |
|---|---|---|---|
async void test, swallowed asserts |
Blocking | async Task, remove catch |
Never |
| Shared static state | Blocking | Per-test state or fixture with reset | Immutable static data only |
Thread.Sleep waits |
Blocking | Signals, polling with timeout | Never in unit tests |
DateTime.Now |
Major | TimeProvider / FakeTimeProvider |
Never in logic, fine in logs |
Mocking DbContext, verify-all |
Major | Real DB or fakes, outcome asserts | Rarely, for legacy code before a seam exists |
| Log text assertions | Minor | FakeLogger structured asserts |
Log wording is a compliance requirement |
Measure the suite's health with wall time, flaky-rate from CI retry reports, and how many tests break on a pure refactor.
Inject TimeProvider (registered as TimeProvider.System in DI) instead of calling DateTime.UtcNow or Task.Delay directly. In tests use FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing: set a start time, call Advance to move time forward, and timers, delays and PeriodicTimer created from it fire deterministically with no real waiting. Test the boundaries (exactly at expiry, one tick either side), keep business time in UTC, and cover daylight-saving rules with a fake local time zone.
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.
How to tell it (STAR)
**S:** At [company] our nightly order-processing suite took [11 minutes] and failed about one night in five, so releases kept slipping. **T:** I took on making it trustworthy. **A:** I grouped failures from the CI reports, reproduced them by running the suite in a loop, and found sleeps, static state, real time and swallowed assertions. I removed the false greens first, then introduced TimeProvider, completion signals, per-test fakes and FakeLogger, and added analysers so the patterns couldn't come back. **R:** The suite dropped to [70 seconds], flaky failures went to [near zero], and un-hiding the assertions exposed [4] real bugs we fixed before the next release.
Last updated 23 Nov 2026.