📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: a test project for an order-processing service mocks every class including the repository and DbContext, waits for background work with Thread.Sleep(3000), shares a static list and DateTime.Now between tests, and asserts on exact log message text through a mocked ILogger. What is wrong, in order of severity, and how would you rewrite it?

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.

Senior CodeReview Advanced code-review fakelogger faketimeprovider flaky-tests mocking testing

🎯 Key points

  • Rank by severity: tests that can't fail (async void tests the runner can't await, swallowed exceptions) first
  • Shared static state makes results depend on order and parallelism (flaky, wrong data)
  • Thread.Sleep is both slow and flaky; await a signal (TaskCompletionSource, Channel) or poll with a timeout
  • DateTime.Now in code and tests: inject TimeProvider, work in UTC, test boundaries with FakeTimeProvider
  • Mocking DbContext skips LINQ translation, change tracking and constraints; mocking every collaborator tests the mocks, not the behaviour
  • Assert on structured log state with FakeLogger (Microsoft.Extensions.Diagnostics.Testing), not message text; check logs end to end only when they are a requirement
  • Close the review with blocking vs suggested comments, xUnit analysers, banned-API rules and a checklist

⏱ 30-second answer

Ranked by severity:

  1. Tests that can't fail: an async void test and a try/catch that swallows the assertion exception give false greens.
  2. Shared static list: results depend on order and parallelism, so tests are flaky and can assert on another test's data.
  3. Thread.Sleep(3000): slow (3 s each) and still flaky on a busy CI agent. Await a completion signal instead.
  4. DateTime.Now: time-dependent logic is untestable at boundaries. Inject TimeProvider and use FakeTimeProvider.
  5. Mocking everything, including DbContext: tests check call sequences, not behaviour, and break on every refactor.
  6. Exact log-text assertions: brittle. Use 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 a try/catch (Exception) that also catches the assertion exception. Both report green regardless. Next is the shared static List<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.Now in the code under test means the 'orders older than 24 hours expire' rule is only tested by whatever time CI happens to run; inject TimeProvider and use FakeTimeProvider.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 DbContext and 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 mocked ILogger breaks when someone edits wording; FakeLogger from Microsoft.Extensions.Diagnostics.Testing lets 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."


Code under review

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
    }
}

Findings, by severity

# 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

The rewrite

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.

How I'd close the review

  • Blocking: items 1, 2, 5, 8; the suite must be able to fail and must be deterministic.
  • Requested: TimeProvider injection, removing DbContext mocks.
  • Suggested: FakeLogger, and a LoggerMessage source-generated event id per log.
  • Guard rails: keep the xUnit analysers on with warnings as errors (they flag 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.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can review tests critically, prioritise by real impact and knows modern .NET tools for deterministic tests.

Green flags

  • Spots the false-green issues (async void, swallowed exceptions) and ranks them first
  • Explains why static state and sleeps cause flakiness under parallel runs
  • Uses TimeProvider/FakeTimeProvider and FakeLogger
  • Proposes analysers and a checklist, not just a one-off fix

Red flags

  • Ranks Thread.Sleep or log text as the worst issue and misses the false greens
  • Suggests longer sleeps or retries to fix flakiness
  • Thinks mocking DbContext is fine

📚 Learn in depth

1. Why async void tests can't fail properly

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.

2. Static state and parallelism

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.

3. Replacing sleeps with signals

Background work should expose a way to observe completion:

  • A TaskCompletionSource set when a batch finishes.
  • A Channel<T> the test reads from.
  • IHostedService.StopAsync that waits for in-flight work.
  • As a last resort, poll a condition every 50 ms with an overall timeout.

The test then takes as long as the work does (milliseconds) and fails clearly on timeout.

4. TimeProvider

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.

5. FakeLogger

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.

6. What to mock

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.

Try it yourself

  1. Write an async void test that fails after await Task.Delay(10) and see what the runner reports; then enable the xUnit analysers.
  2. Make two test classes add to a static list in parallel and run them 20 times with a loop; count failures.
  3. Replace a Thread.Sleep with a TaskCompletionSource signal and compare run times.
  4. Use FakeTimeProvider.Advance to test a 24-hour expiry at 23:59:59 and 24:00:00.
  5. Switch a Mock<ILogger> assertion to FakeLogger and assert on StructuredState.

💻 Code

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");
    }
}

⚠ Common mistakes

  • Mistake: Writing 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.
  • Mistake: Wrapping assertions in 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.
  • Mistake: Using 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.
  • Mistake: Static mutable fields in test classes. Why it is wrong: State leaks across tests and parallel classes. Instead: Instance fields (new per test in xUnit) or fixtures with explicit reset.
  • Mistake: Reading 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.
  • Mistake: Mocking 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.
  • Mistake: Verifying exact log message text via 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.
  • Mistake: Verifying every collaborator call. Why it is wrong: Tests encode implementation steps and fail on safe refactors. Instead: Assert observable outcomes; verify only boundary commands.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions TimeProvider or FakeTimeProvider. Why: Checks deeper knowledge of testing time-dependent code.
    How to answer

    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.

  2. When: Candidate mentions flakiness from sleeps or shared state. Why: Checks a systematic approach to flaky tests at team level.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Nightly order-processing suite: 11 minutes, fails one night in five
Situation
An order-processing worker service on [Azure Container Apps] with a [180-test] suite run nightly and before each [fortnightly] release. The release gate required a green run.
Signals
CI history showed [~20%] of nightly runs failing, almost always passing on re-run; the suite took [11 minutes]; developers had added try/catch blocks to 'stabilise' tests; failures clustered around [midnight UTC].
Investigation
Pulled the CI test reports for [30] runs and grouped failures by test. Read the failing tests: Thread.Sleep waits, a static List<Order>, DateTime.Now in the expiry logic and tests, async void tests. Ran the suite 50 times locally with parallelism on and reproduced the failures; the midnight cluster matched the 24-hour expiry crossing a date boundary.
Resolution
Immediately removed the swallowing try/catch blocks and fixed the async void tests, accepting that real failures would show. Then injected TimeProvider into the processor, exposed a batch-completion Task, replaced the static list with per-test fakes and Testcontainers for the EF repository, and moved log assertions to FakeLogger.
Prevention
xUnit analysers as errors, BannedApiAnalyzers for Thread.Sleep and DateTime.Now, a flaky-test dashboard from CI retries, and a test-review checklist in the PR template.

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.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me