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

📚 Interview question

How do you write reliable tests for asynchronous .NET code? Explain awaiting correctly instead of blocking, testing cancellation and timeouts, testing a Channel-based BackgroundService, and the xUnit features and analysers that help.

Testing async .NET code: async test methods, avoiding .Result and async void, asserting cancellation with ThrowsAnyAsync, timeouts with TestContext.Current.CancellationToken, and testing Channel-driven BackgroundService workers deterministically.

Mid-Level Coding Intermediate async-await background-services cancellation channels testing xunit

🎯 Key points

  • Test methods return Task and await; never .Result, .Wait() or GetAwaiter().GetResult() (xUnit1031 analyser); exceptions then surface with their real type
  • async void methods can't be awaited; exceptions escape the test and crash or pass silently
  • TaskCanceledException derives from OperationCanceledException: ThrowsAnyAsync<OperationCanceledException> accepts both, ThrowsAsync needs the exact type; check ex.CancellationToken to prove which token cancelled
  • Guard timeout on every await: a CancellationTokenSource with CancelAfter, linked to TestContext.Current.CancellationToken in xUnit v3 (in NUnit/MSTest or xUnit v2, a plain CancelAfter source)
  • Synchronise on observable effects (TaskCompletionSource with RunContinuationsAsynchronously, Channel) not fixed Task.Delay waits
  • Test a BackgroundService through StartAsync / StopAsync; assert it survives a failing item and stops on cancellation
  • Gated fakes (SemaphoreSlim) hold calls in flight to test cancellation and concurrency limits deterministically

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"The first rule is that the test itself is async all the way: public async Task and await the call. If you block with .Result you get an AggregateException instead of the real one, and under a synchronisation context you can deadlock. xUnit ships analysers for this, xUnit1031 flags blocking task operations in tests. And never write an async void test or helper: nobody can await it, so an exception either crashes the test host or the test passes before the work even runs.

Then I think about what 'done' means for the code under test. If it returns a task, I just await it. If it is fire-and-forget or a background worker, I need an observable effect. For a BackgroundService reading from a Channel, I give it a fake sender whose method completes a TaskCompletionSource or writes to a channel; the test writes a message, awaits the fake's signal, then calls StopAsync. I test three behaviours: it processes a message, it survives an item that throws, and it stops promptly when cancelled, including cancelling an in-flight call. For cancellation I use a gated fake that waits on the token, cancel, and assert ThrowsAnyAsync<OperationCanceledException>, because the framework often throws the derived TaskCanceledException.

The mistake I see is await Task.Delay(500) and then asserting. It is slow and it still fails on a busy agent. I always have a real-time guard instead: a CancellationTokenSource linked to TestContext.Current.CancellationToken with CancelAfter(5 seconds), passed to the waits. If the code is correct, the test takes milliseconds; if it is broken, it fails fast with a clear timeout. Await the effect, never the clock."


Blocking versus awaiting in tests

Pattern What happens Verdict
await sut.DoAsync() Real exception, no deadlock Use
sut.DoAsync().Result AggregateException; deadlock risk under a sync context Avoid (xUnit1031)
async void Test() Not awaitable; exceptions escape Never
await Task.Delay(500); Assert... Slow, still racy Replace with a signal
Assert.ThrowsAsync<T> Exact type only For precise types
Assert.ThrowsAnyAsync<OperationCanceledException> Includes TaskCanceledException For cancellation

Signals to await

Tool Good for
TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously) One event, e.g. "the email was sent"
Channel<T> A sequence of events to read in order
SemaphoreSlim gate in a fake Holding a call in flight to test cancellation or concurrency limits
FakeTimeProvider Delays and timers (see the time-testing question)

What to test on a background worker

Behaviour How
Processes an item Write to the channel, await the fake's signal
Survives a failing item Fake throws for item 1; assert item 2 still processed
Stops on shutdown StopAsync; assert ExecuteTask completes within the guard
Cancels in-flight work Gated fake waits on the token; StopAsync; assert it observed cancellation

Production example

An order-confirmation worker swallowed OperationCanceledException along with everything else, so on every deployment App Service waited the full 30-second shutdown timeout and then killed the process mid-send, producing [n] duplicate emails per release. A test that held a send in flight with a gated fake and asserted StopAsync finished within 2 seconds failed immediately; adding when (ex is not OperationCanceledException) to the catch fixed it and shutdown dropped to under 1 second.

🔍 What the interviewer is checking

Checks whether the candidate writes async tests that are correct (no blocking, no async void), deterministic (signals not sleeps) and able to verify cancellation and background behaviour.

Green flags

  • async Task tests, names xUnit1031 or explains why blocking is wrong
  • Uses ThrowsAnyAsync<OperationCanceledException> and checks the token
  • Synchronises on TaskCompletionSource or Channel; guard timeouts linked to the test token
  • Tests that a worker survives a failing item and stops promptly

Red flags

  • Thread.Sleep or Task.Delay to wait for background work
  • async void test methods
  • Never tests cancellation, or swallows it in production code

📚 Learn in depth

1. What an async test really is

xUnit, NUnit and MSTest all recognise test methods returning Task (and ValueTask in xUnit v3). The runner awaits the returned task; the test passes if it completes successfully and fails if it faults. That gives three consequences:

  • An exception thrown after an await is captured in the task and reported with its real type and stack.
  • An async void method returns nothing to await, so the runner sees success the moment the first await yields.
  • Blocking calls (.Result) wrap the exception in AggregateException and tie up a thread.

2. Deadlocks and synchronisation contexts

Classic deadlock:

Test thread (has SynchronizationContext)
   calls DoAsync().Result  ---- blocks waiting --------+
                                                        |
DoAsync awaits I/O, wants to resume on the context ----+  (context is blocked)

ASP.NET Core has no SynchronizationContext, and xUnit v2/v3 installs a context only to limit parallelism, but WPF/WinForms code under test and some test frameworks do. Awaiting avoids the whole class of problem.

3. How cancellation surfaces

Cancellation in .NET is cooperative: code checks token.ThrowIfCancellationRequested() or passes the token to an API that does. Most BCL APIs throw TaskCanceledException (a subclass of OperationCanceledException); Channel reads and SemaphoreSlim.WaitAsync throw OperationCanceledException. Asserting the base type with ThrowsAnyAsync makes tests robust to which API cancelled. Also assert the token: ex.CancellationToken == expectedToken proves it was your cancellation, not an unrelated timeout.

4. The BackgroundService lifecycle

host.StartAsync
   -> BackgroundService.StartAsync
        -> ExecuteTask = ExecuteAsync(stoppingToken)   (runs until first real await, then returns)
host.StopAsync
   -> BackgroundService.StopAsync
        -> cancels stoppingToken
        -> awaits ExecuteTask or the StopAsync token, whichever first

In .NET 10 ExecuteAsync is started on the thread pool (Task.Run) so a synchronous prefix no longer blocks start-up; in earlier versions a long synchronous section before the first await blocked StartAsync. You can test the class directly: construct it, call StartAsync(ct), interact, call StopAsync(ct), then inspect ExecuteTask.

The default HostOptions.BackgroundServiceExceptionBehavior is StopHost, so an unhandled exception in ExecuteAsync stops the whole app. That makes "survives a failing item" a critical test.

5. TaskCompletionSource options

new TaskCompletionSource() by default runs awaiting continuations synchronously inside SetResult. If the code under test completes it while holding a lock, the test's continuation runs inside that lock. Use TaskCreationOptions.RunContinuationsAsynchronously for signals in fakes.

6. Test-level timeouts

xUnit v3 exposes TestContext.Current.CancellationToken, cancelled when the run is aborted or a [Fact(Timeout = ...)] elapses. Linking your own CancelAfter to it gives a per-await guard. The dotnet test --blame-hang-timeout 5m option is the last line of defence: it captures a dump of a hung test host so you can see which test was stuck.

7. Parallel and concurrency tests

To test that a worker processes at most N items at once, give the fake a gate (SemaphoreSlim(0)) and a counter incremented with Interlocked. Write N+1 items, await until N calls are inside the fake, assert the counter equals N, release the gate. No sleeps, no timing assumptions.

Try it yourself

  1. Write a test that calls .Result on a method that throws InvalidOperationException after an await; observe the AggregateException; switch to await.
  2. Write an async void helper that throws and see the test pass (or the host crash); enable the xUnit analysers and read the warning.
  3. Build the ConfirmationWorker below and write the "survives a failure" test before adding the try/catch; watch it fail.
  4. Change the catch to catch (Exception) (no filter) and write a test proving StopAsync now waits for the guard timeout.
  5. Write a concurrency-limit test with a SemaphoreSlim gate for a worker using Parallel.ForEachAsync with MaxDegreeOfParallelism = 4.

💻 Code

A Channel-fed BackgroundService and xUnit v3 tests for processing, failure isolation and cancellation, with no sleeps.

// Orders/ConfirmationWorker.cs
using System.Threading.Channels;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Orders;

public sealed record OrderPlaced(Guid OrderId);

public interface IEmailSender
{
    Task SendConfirmationAsync(Guid orderId, CancellationToken ct);
}

public sealed class OrderQueue
{
    private readonly Channel<OrderPlaced> _channel = Channel.CreateBounded<OrderPlaced>(100);
    public ValueTask EnqueueAsync(OrderPlaced message, CancellationToken ct) => _channel.Writer.WriteAsync(message, ct);
    public IAsyncEnumerable<OrderPlaced> ReadAllAsync(CancellationToken ct) => _channel.Reader.ReadAllAsync(ct);
}

public sealed class ConfirmationWorker(OrderQueue queue, IEmailSender sender, ILogger<ConfirmationWorker> logger)
    : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var message in queue.ReadAllAsync(stoppingToken))
        {
            try
            {
                await sender.SendConfirmationAsync(message.OrderId, stoppingToken);
            }
            // Let cancellation propagate so shutdown is quick; isolate everything else.
            catch (Exception ex) when (ex is not OperationCanceledException)
            {
                logger.LogError(ex, "Confirmation for order {OrderId} failed", message.OrderId);
            }
        }
    }
}
// Orders.Tests/ConfirmationWorkerTests.cs
using System.Threading.Channels;
using Microsoft.Extensions.Logging.Abstractions;
using Orders;
using Xunit;

namespace Orders.Tests;

public sealed class ConfirmationWorkerTests
{
    private sealed class FakeSender : IEmailSender
    {
        private readonly Channel<Guid> _sent = Channel.CreateUnbounded<Guid>();
        public Func<Guid, CancellationToken, Task> Behaviour { get; set; } = (_, _) => Task.CompletedTask;

        public async Task SendConfirmationAsync(Guid orderId, CancellationToken ct)
        {
            await Behaviour(orderId, ct);
            _sent.Writer.TryWrite(orderId);
        }

        public ValueTask<Guid> NextSentAsync(CancellationToken ct) => _sent.Reader.ReadAsync(ct);
    }

    private static CancellationTokenSource Guard()
    {
        var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
        cts.CancelAfter(TimeSpan.FromSeconds(5));
        return cts;
    }

    [Fact]
    public async Task FailingOrder_DoesNotStopLaterOrders()
    {
        using var guard = Guard();
        var queue = new OrderQueue();
        var bad = Guid.NewGuid();
        var good = Guid.NewGuid();
        var sender = new FakeSender
        {
            Behaviour = (id, _) => id == bad ? throw new InvalidOperationException("SMTP down") : Task.CompletedTask
        };
        var worker = new ConfirmationWorker(queue, sender, NullLogger<ConfirmationWorker>.Instance);

        await worker.StartAsync(guard.Token);
        await queue.EnqueueAsync(new OrderPlaced(bad), guard.Token);
        await queue.EnqueueAsync(new OrderPlaced(good), guard.Token);

        Assert.Equal(good, await sender.NextSentAsync(guard.Token)); // awaited, not slept
        await worker.StopAsync(guard.Token);
    }

    [Fact]
    public async Task StopAsync_CancelsInFlightSend()
    {
        using var guard = Guard();
        var queue = new OrderQueue();
        var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var sender = new FakeSender
        {
            // Hold the call in flight until the worker's token is cancelled.
            Behaviour = async (_, ct) => { started.SetResult(); await Task.Delay(Timeout.Infinite, ct); }
        };
        var worker = new ConfirmationWorker(queue, sender, NullLogger<ConfirmationWorker>.Instance);

        await worker.StartAsync(guard.Token);
        await queue.EnqueueAsync(new OrderPlaced(Guid.NewGuid()), guard.Token);
        await started.Task.WaitAsync(guard.Token);

        await worker.StopAsync(guard.Token);

        Assert.NotNull(worker.ExecuteTask);
        await Assert.ThrowsAnyAsync<OperationCanceledException>(() => worker.ExecuteTask!);
    }
}

⚠ Common mistakes

  • Mistake: Blocking with .Result, .Wait() or GetAwaiter().GetResult() in a test. Why it is wrong: exceptions arrive wrapped, threads are blocked and deadlocks are possible. Instead: make the test async Task and await; turn on xUnit1031.
  • Mistake: Writing async void tests or helpers. Why it is wrong: the runner can't await them, so failures are lost or crash the host. Instead: return Task.
  • Mistake: await Task.Delay(500) as the way to wait for background work before asserting. Why it is wrong: it guesses how long the work takes, so it is slow on fast machines and flaky on loaded CI agents. Instead: await a TaskCompletionSource or channel signal from a fake. A real delay is fine only where the delay itself is the behaviour (for example a fake dependency that must be slow to trigger a timeout), and even then prefer FakeTimeProvider.
  • Mistake: Asserting ThrowsAsync<OperationCanceledException> when the API throws TaskCanceledException. Why it is wrong: ThrowsAsync checks the exact type, so the test fails for the wrong reason. Instead: ThrowsAnyAsync<OperationCanceledException>, and check ex.CancellationToken when it matters whether your token or a timeout cancelled.
  • Mistake: Accepting any cancellation as success. Why it is wrong: a timeout inside HttpClient also throws TaskCanceledException, so the test can pass while the code never honoured your token. Instead: assert the exception's token equals the one you cancelled.
  • Mistake: A catch-all in a worker loop that also swallows cancellation. Why it is wrong: shutdown waits for the host timeout and kills work mid-flight. Instead: catch (Exception ex) when (ex is not OperationCanceledException) and a test for prompt stop.
  • Mistake: No timeout on awaits in tests. Why it is wrong: a bug hangs the CI job until it is killed with no useful output. Instead: link a CancelAfter guard to TestContext.Current.CancellationToken (xUnit v3) or use a plain CancelAfter source in other frameworks; use --blame-hang-timeout as a backstop.
  • Mistake: TaskCompletionSource without RunContinuationsAsynchronously in fakes. Why it is wrong: the test's continuation runs inline inside the code under test, sometimes under its locks. Instead: pass the option.
  • Mistake: Testing a BackgroundService only through the full host with real delays. Why it is wrong: slow and hard to control. Instead: call StartAsync/StopAsync directly with fakes; keep one host-level smoke test.

🏛 Senior insight: trade-offs

Async tests fail in two directions: they hang, or they pass without testing anything. Seniors design against both. Against hangs: every await in a test has a guard timeout, and --blame-hang-timeout is on in CI so a stuck host produces a dump. Against false passes: no async void, no fire-and-forget in tests, and assertions on an awaited effect, not on state read after an arbitrary delay.

The design point is that testability of async code is mostly decided in production code. A worker that exposes its dependencies, accepts a CancellationToken everywhere and doesn't swallow cancellation is easy to test; one that creates its own HttpClient and loops on Task.Delay(1000) is not. I push those changes in code review rather than writing heroic tests.

Technique When it fits Cost When not to
Await the returned task Code returns Task None Fire-and-forget code
Fake that signals (TCS / Channel) Background workers, events A small fake class Code with a return value you can await
Gated fake (SemaphoreSlim) Cancellation, concurrency limits, ordering More plumbing Simple sequential code
Full host with WebApplicationFactory Wiring and DI smoke test Slower Behaviour details

I measure it by flake rate and duration: async worker tests should take milliseconds each and show zero retries over hundreds of runs.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions combining the test token with a timeout Why: Checks they understand linked cancellation token sources and their disposal.
    How to answer

    CancellationTokenSource.CreateLinkedTokenSource(a, b, ...) creates a new source that is cancelled when any of the given tokens is cancelled, and can also be cancelled itself (for example with CancelAfter). It is how you combine "the caller cancelled" with "my own timeout" or "the host is shutting down". You must dispose the linked source, because it registers callbacks on the parent tokens; forgetting to do that on long-lived tokens leaks memory. To report the right error, check which source fired: if the caller's token is cancelled, rethrow cancellation; if only your timeout fired, throw a TimeoutException.

  2. When: Candidate mentions concurrency or Parallel.ForEachAsync Why: Checks they can test concurrency limits deterministically with gates instead of timing.
    How to answer

    Make the limit observable instead of timing it. In an xUnit test, give the worker a fake handler with a SemaphoreSlim(0) gate: every call increments an Interlocked in-flight counter (recording the maximum), signals "entered" through a channel, then awaits the gate. Because the gate starts at zero, calls that enter stay in flight, so the worker's own limit is the only thing deciding how many get in. Enqueue five messages, await four "entered" signals (with a guard timeout), assert in-flight is 4 and that no fifth signal arrives, then Release(5) and assert all five complete and the recorded maximum never exceeded 4. Finish by stopping the worker with its cancellation token and awaiting it, so no calls or threads outlive the test.

🛠 Real-world problems: how you handle them

Every deploy waited 30 seconds and duplicated confirmation emails
Situation
An [order-processing] ASP.NET Core service on Azure App Service ran a `BackgroundService` that sent order confirmations from an in-process `Channel`. The team released [several times a day].
Signals
Deployment logs showed the old instance taking the full 30-second shutdown timeout every release; customers reported duplicate confirmation emails after deploys; Application Insights showed `Confirmation for order ... failed` errors with `TaskCanceledException` at each shutdown.
Investigation
I read the worker and found `catch (Exception ex)` around the send, which swallowed the `OperationCanceledException` raised by the stopping token, so the loop kept going until the host gave up. I wrote a test with a gated fake that held a send in flight, called `StopAsync` and asserted `ExecuteTask` completed within 2 seconds: it timed out, reproducing the bug in milliseconds.
Resolution
Immediate: none needed beyond the fix, which shipped the same day. Fix: changed the catch to `when (ex is not OperationCanceledException)`, passed the stopping token to the email client, and made sends idempotent by order id so a killed send retried after restart didn't duplicate. The stop test then passed and shutdown took under 1 second.
Prevention
Kept the stop and failure-isolation tests as a template for every new worker; enabled the xUnit analysers and `--blame-hang-timeout` in CI; added a code-review checklist item for catch-all blocks in loops that receive a cancellation token.

How to tell it (STAR)

**S:** At [company], every deployment of our [order-processing] service hung for 30 seconds on shutdown and some customers got duplicate confirmation emails. **T:** I picked it up because it was costing us [support tickets] each release. **A:** I suspected the worker's catch-all block was eating cancellation. I proved it with a test that held a send in flight with a gated fake, called `StopAsync`, and expected completion within 2 seconds; it timed out. I filtered `OperationCanceledException` out of the catch, passed the token through, and made sends idempotent by order id. **R:** Shutdown dropped from 30 seconds to under 1, duplicate emails stopped, and the stop test became the template for our [n] other workers.

↩ Usually asked after

More in Senior Testing Topics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me