Lesson 15 of 93 · 5 min read · Updated
Testing Exceptions in xUnit: Throws, ThrowsAny and Awaiting ThrowsAsync
On this page
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
- .NET 11 SDK
- 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
Three things happen in Assert.Throws<T>:
- It runs the lambda. The code under test must be inside the lambda, so xUnit can catch what it throws.
- It fails if nothing is thrown, or if the exception type is not exactly
T. A subclass ofTalso fails. - 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
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
M02.XUnitBasics.Tests/ExceptionAssertionTests.cs
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
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
Assert.Throws<T>requires the exact type.Assert.ThrowsAny<T>acceptsTand its subtypes.- Both return the caught exception. Assert on stable details such as
ParamName, and on message text only when callers see it. - For async code, use
ThrowsAsyncorThrowsAnyAsyncand alwaysawaitthem. Withoutawait, the test passes no matter what. - Test methods that await must return
Task, neverasync void. - To test "does not throw", call the method and assert on its result.