Lesson 15 of 93 · 5 min read · Updated

Testing Exceptions in xUnit: Throws, ThrowsAny and Awaiting ThrowsAsync

Error paths are part of a method's contract, and they deserve tests as much as the happy path. xUnit has four assertions for exceptions: Assert.Throws, Assert.ThrowsAny and their asynchronous versions ThrowsAsync and ThrowsAnyAsync. This lesson shows when to use each one, how to check the exception's details without making the test brittle, and the one mistake that makes an async exception test pass when it should fail.

Technical Requirements

  1. .NET 11 SDK
  2. xunit 2.9.3 (with xunit.runner.visualstudio and Microsoft.NET.Test.Sdk)

Throws: Exact Exception Type

Product.Reserve throws InvalidOperationException when you ask for more items than are in stock, and ArgumentOutOfRangeException when the quantity is zero or negative (see the Product class in the Arrange-Act-Assert lesson).

M02.XUnitBasics.Tests/ExceptionAssertionTests.cs

[Fact]
public void Reserve_WithMoreThanStock_ThrowsInvalidOperation()
{
var product = new Product("KLAVYE-01", "Mekanik Klavye", 750m, stock: 2);

var exception = Assert.Throws<InvalidOperationException>(() => product.Reserve(5));

// Only check the message text if it is shown to the user or caller.
// Otherwise the test breaks for no reason when the message changes.
Assert.Contains("Yetersiz stok", exception.Message);
}

Three things happen in Assert.Throws<T>:

  1. It runs the lambda. The code under test must be inside the lambda, so xUnit can catch what it throws.
  2. It fails if nothing is thrown, or if the exception type is not exactly T. A subclass of T also fails.
  3. It returns the caught exception, typed as T, so you can inspect it.

Wrapping the call in a lambda is the key difference from a plain try/catch in the test. A hand-written try/catch needs an extra Assert.Fail for the "nothing was thrown" case, and people forget it. Assert.Throws handles both cases in one line.

When to Check the Message

The returned exception lets you check details. Be selective. The message text ("insufficient stock" here) is checked with Contains, not Equal, and only because the message is shown to the caller. If a message is only for developers, asserting on it couples the test to wording. Fixing a typo then breaks a test, which teaches the team to ignore failing tests.

Prefer stable, structured details where they exist. For argument exceptions, ParamName is part of the contract. The range and type lesson used Assert.Equal("channel", exception.ParamName) for exactly that reason. For custom exceptions, assert on properties such as an error code rather than on the text.

ThrowsAny: Accept a Type Hierarchy

M02.XUnitBasics.Tests/ExceptionAssertionTests.cs

[Fact]
public void Reserve_WithZeroQuantity_ThrowsArgumentOutOfRange()
{
var product = new Product("KLAVYE-01", "Mekanik Klavye", 750m, stock: 2);

// ArgumentOutOfRangeException derives from ArgumentException.
// With ThrowsAny we can accept the hierarchy.
Assert.ThrowsAny<ArgumentException>(() => product.Reserve(0));
}

Reserve(0) throws ArgumentOutOfRangeException. Assert.Throws<ArgumentException> would fail, because the type is not an exact match. Assert.ThrowsAny<ArgumentException> accepts ArgumentException and every type derived from it.

Which one should you pick? Use Throws when the exact type is part of the contract and callers catch that type. Use ThrowsAny when the contract is "some argument error" and you do not want the test to break if the code switches to a more specific subtype. Note that the test name still documents the expected exception precisely, even though the assertion accepts a family of types.

Asynchronous Code: ThrowsAsync and the Missing await

The async examples use a fake remote client that can be told to fail:

M02.XUnitBasics/RemoteCatalogClient.cs

public sealed class RemoteCatalogClient(bool isAvailable)
{
public async Task<Product> LoadAsync(string sku, CancellationToken cancellationToken = default)
{
// A minimal async boundary that stands in for real I/O.
await Task.Yield();
cancellationToken.ThrowIfCancellationRequested();

if (!isAvailable)
{
throw new HttpRequestException("Katalog servisine ulaşılamıyor.");
}

return new Product(sku, "Uzak Ürün", 199.90m, 10);
}
}

M02.XUnitBasics.Tests/ExceptionAssertionTests.cs

[Fact]
public async Task LoadAsync_WhenServiceIsDown_ThrowsHttpRequestException()
{
var client = new RemoteCatalogClient(isAvailable: false);

// WARNING: the await is required!
await Assert.ThrowsAsync<HttpRequestException>(() => client.LoadAsync("MOUSE-01"));
}

[Fact]
public async Task LoadAsync_WhenCancelled_ThrowsOperationCanceled()
{
var client = new RemoteCatalogClient(isAvailable: true);
using var cts = new CancellationTokenSource();
await cts.CancelAsync();

await Assert.ThrowsAnyAsync<OperationCanceledException>(
() => client.LoadAsync("MOUSE-01", cts.Token));
}

An async method does not throw when you call it. It returns a Task, and the exception is stored in that task. Assert.ThrowsAsync takes a lambda that returns the task, awaits it and checks what comes out. That is why the test method is async Task and why the assertion itself must be awaited.

This is the most dangerous pitfall in the lesson. If you write Assert.ThrowsAsync<HttpRequestException>(...) without await, the assertion returns an unobserved task and the test method finishes immediately. The test passes whether the code throws or not. The xUnit analyzers warn about this, so do not suppress that warning. Also avoid async void test methods: always return Task, so the runner can await the test and see its failures reliably.

The cancellation test uses ThrowsAnyAsync on purpose. Cancellation can surface as OperationCanceledException or as its subclass TaskCanceledException, depending on where in the call chain the token is observed. The contract is "the operation was cancelled", so the test accepts the whole family.

The Happy Path Needs No Special Assertion

M02.XUnitBasics.Tests/ExceptionAssertionTests.cs

[Fact]
public async Task LoadAsync_WhenServiceIsUp_DoesNotThrow()
{
var client = new RemoteCatalogClient(isAvailable: true);

var product = await client.LoadAsync("MOUSE-01");

Assert.Equal("MOUSE-01", product.Sku);
}

xUnit has no Assert.DoesNotThrow, and you do not need one. Any unhandled exception fails the test anyway. Call the method normally and assert on its result. That checks more than "it did not throw".

Summary

  1. Assert.Throws<T> requires the exact type. Assert.ThrowsAny<T> accepts T and its subtypes.
  2. Both return the caught exception. Assert on stable details such as ParamName, and on message text only when callers see it.
  3. For async code, use ThrowsAsync or ThrowsAnyAsync and always await them. Without await, the test passes no matter what.
  4. Test methods that await must return Task, never async void.
  5. To test "does not throw", call the method and assert on its result.