Lesson 26 of 93 · 5 min read · Updated

Async Tests in xUnit: Awaiting Results, Exceptions and Cancellation Correctly

Most modern .NET code is asynchronous, so most tests have to deal with Task. An async test that is written slightly wrong can pass while the code under test is broken, because the assertion never runs or its failure is never observed. This lesson shows how to write async tests that xUnit actually waits for, how to assert on exceptions and cancellation, and how to wait for parallel work without guessing with fixed delays.

Technical Requirements

  1. .NET 11 SDK
  2. xunit 2.9.3
  3. xunit.runner.visualstudio 4.0.1 and Microsoft.NET.Test.Sdk 18.12.0

The Method Under Test

The test class contains a small async helper that stands in for real I/O, such as a database query or an HTTP call. It yields once, so it really completes asynchronously, then honors a cancellation token and returns a value.

M03.DataDriven.Tests/AsyncTestTests.cs

private static async Task<int> LoadCountAsync(CancellationToken cancellationToken = default)
{
await Task.Yield();
cancellationToken.ThrowIfCancellationRequested();
return 42;
}

Task.Yield() forces the rest of the method to run as a continuation. Without it, the method could complete synchronously, and the tests would not prove much about async behavior.

Return Task, Not void

An async test method must return Task. xUnit sees the returned task, waits for it to complete, and reports any exception stored in it as a test failure.

M03.DataDriven.Tests/AsyncTestTests.cs

[Fact]
public async Task LoadCountAsync_ReturnsValue()
{
// We await the Act step: xUnit sees the result and any exception.
var count = await LoadCountAsync();

Assert.Equal(42, count);
}

The await is what makes this test correct. The assertion runs only after the result is available, and if LoadCountAsync throws, the exception comes out of the await and fails the test.

The common mistake is async void. An async void method returns nothing the caller can wait on, so the caller has no way to know when it finishes or whether it failed. xUnit 2 has special handling that tries to wait for async void test methods, but xUnit v3 no longer supports them, and newer versions of the xUnit analyzers warn about them. The same problem shows up in helper methods and event handlers: any async void call inside a test runs "fire and forget", and an exception it throws later is lost or crashes the process. Use async Task everywhere in test code.

A second version of the same mistake is calling an async method without awaiting it. LoadCountAsync(); on its own line starts the work and moves on. The test finishes before the work does, and it passes no matter what happens.

Asserting Exceptions and Cancellation

To check that an async method throws, use the async assertion and await it.

M03.DataDriven.Tests/AsyncTestTests.cs

[Fact]
public async Task LoadCountAsync_WhenTokenIsCancelled_Throws()
{
using var cts = new CancellationTokenSource();
await cts.CancelAsync();

await Assert.ThrowsAnyAsync<OperationCanceledException>(() => LoadCountAsync(cts.Token));
}

The test cancels the token before calling the method, so the outcome is deterministic. There is no race between the cancel call and the method. CancelAsync is the async version of Cancel. It runs registered callbacks without blocking the calling thread.

Two details matter here:

  1. ThrowsAnyAsync instead of ThrowsAsync. ThrowsAsync<T> requires the exact type T. Cancellation can surface as OperationCanceledException or its subclass TaskCanceledException, depending on where it happens. ThrowsAnyAsync<OperationCanceledException> accepts both, so the test checks the behavior, "the operation was cancelled", and not an implementation detail.
  2. The await in front of the assertion. Assert.ThrowsAnyAsync returns a Task. If you forget to await it, nobody observes its result, and the test passes even when no exception is thrown. The xUnit analyzers flag this, but it is easy to miss in a review.

The assertion takes a Func<Task>, so you pass a lambda, () => LoadCountAsync(cts.Token). The assertion invokes it itself, which lets it catch the exception whether the method throws synchronously or stores the exception in the returned task.

Waiting for Parallel Work with a Bounded Timeout

Tests for concurrent code often wait for something to happen. The fragile way is to sleep for a fixed time, such as await Task.Delay(500), and then check the result. On a fast machine the delay wastes time. On a slow CI agent it is not long enough, and the test fails at random.

The reliable way is to wait for an observable condition, here the completion of the tasks, and to put an upper limit on how long you are willing to wait.

M03.DataDriven.Tests/AsyncTestTests.cs

[Fact]
public async Task ParallelWork_CompletesWithinBoundedTimeout()
{
// Instead of "sleep for a fixed time", wait for an OBSERVABLE condition with a BOUNDED timeout.
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));

var tasks = Enumerable.Range(0, 8).Select(_ => LoadCountAsync(cts.Token));
var results = await Task.WhenAll(tasks);

Assert.All(results, value => Assert.Equal(42, value));
}

Task.WhenAll completes as soon as all eight tasks complete, so a fast run finishes quickly. The CancellationTokenSource created with a five-second timeout is the safety net. If the work hangs, the token is cancelled, the tasks throw, and the test fails with a clear cancellation error instead of hanging the whole test run.

Assert.All checks every result and reports which item failed, which is more useful than checking only the first element.

The same principle applies to time in general. If the code under test depends on the current time or on timers, inject a time source such as TimeProvider and control it from the test, instead of waiting for real time to pass.

Summary

  1. Async tests must return Task and await the code under test, so xUnit observes results and exceptions.
  2. Avoid async void in test code, and never call an async method without awaiting it.
  3. Use await Assert.ThrowsAsync or await Assert.ThrowsAnyAsync; a missing await makes the assertion a no-op.
  4. Prefer ThrowsAnyAsync<OperationCanceledException> for cancellation, since the concrete exception type can vary.
  5. Wait for observable conditions with a bounded timeout instead of fixed Task.Delay calls.