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.
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.
"The first rule is that the test itself is async all the way:
public async Taskandawaitthe call. If you block with.Resultyou get anAggregateExceptioninstead 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 anasync voidtest 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
BackgroundServicereading from aChannel, I give it a fake sender whose method completes aTaskCompletionSourceor writes to a channel; the test writes a message, awaits the fake's signal, then callsStopAsync. 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 assertThrowsAnyAsync<OperationCanceledException>, because the framework often throws the derivedTaskCanceledException.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: aCancellationTokenSourcelinked toTestContext.Current.CancellationTokenwithCancelAfter(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."
| 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 |
| 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) |
| 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 |
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.
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 wrongThrowsAnyAsync<OperationCanceledException> and checks the tokenRed flags
Thread.Sleep or Task.Delay to wait for background workasync void test methodsxUnit, 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:
await is captured in the task and reported with its real type and stack.async void method returns nothing to await, so the runner sees success the moment the first await yields..Result) wrap the exception in AggregateException and tie up a thread.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.
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.
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.
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.
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.
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.
.Result on a method that throws InvalidOperationException after an await; observe the AggregateException; switch to await.async void helper that throws and see the test pass (or the host crash); enable the xUnit analysers and read the warning.ConfirmationWorker below and write the "survives a failure" test before adding the try/catch; watch it fail.catch (Exception) (no filter) and write a test proving StopAsync now waits for the guard timeout.SemaphoreSlim gate for a worker using Parallel.ForEachAsync with MaxDegreeOfParallelism = 4.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!);
}
}
.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.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.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.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.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.catch (Exception ex) when (ex is not OperationCanceledException) and a test for prompt stop.CancelAfter guard to TestContext.Current.CancellationToken (xUnit v3) or use a plain CancelAfter source in other frameworks; use --blame-hang-timeout as a backstop.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.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.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.
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.
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.
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.
Last updated 23 Nov 2026.