Lesson 26 of 93 · 5 min read · Updated
Async Tests in xUnit: Awaiting Results, Exceptions and Cancellation Correctly
On this page
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
- .NET 11 SDK
- xunit 2.9.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
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
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
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:
ThrowsAnyAsyncinstead ofThrowsAsync.ThrowsAsync<T>requires the exact typeT. Cancellation can surface asOperationCanceledExceptionor its subclassTaskCanceledException, depending on where it happens.ThrowsAnyAsync<OperationCanceledException>accepts both, so the test checks the behavior, "the operation was cancelled", and not an implementation detail.- The
awaitin front of the assertion.Assert.ThrowsAnyAsyncreturns aTask. 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
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
- Async tests must return
Taskandawaitthe code under test, so xUnit observes results and exceptions. - Avoid
async voidin test code, and never call an async method without awaiting it. - Use
await Assert.ThrowsAsyncorawait Assert.ThrowsAnyAsync; a missingawaitmakes the assertion a no-op. - Prefer
ThrowsAnyAsync<OperationCanceledException>for cancellation, since the concrete exception type can vary. - Wait for observable conditions with a bounded timeout instead of fixed
Task.Delaycalls.