skip to content

In xUnit.net, how do you assert that code throws, and how do Assert.Throws, Assert.ThrowsAny and Assert.ThrowsAsync differ?

level: juniorimportance: should knowfreq 60%

answer

  1. no attribute: assert on one statement
  2. Throws<T> accepts the exact type only
  3. ThrowsAny<T> also accepts derived types
  4. ThrowsAsync<T> returns Task<T>, await it
  5. Throws<T>(paramName, action) checks ParamName

basics

~10 s

Wrap the call in a lambda: Assert.Throws<T> passes only for exactly T, Assert.ThrowsAny<T> also accepts derived exceptions, and Assert.ThrowsAsync<T> handles Task-returning code and must be awaited. Each returns the caught exception for further asserts.

solid answer

~40 s

xUnit.net has no `[ExpectedException]`-style attribute; you assert on the exact statement that should throw: `var ex = Assert.Throws<ArgumentOutOfRangeException>(() => calculator.Calculate(-1m));`. `Throws<T>` is strict: it fails when the code throws a subclass of `T`, so `Throws<ArgumentException>` fails against an `ArgumentOutOfRangeException`, while `ThrowsAny<T>` accepts `T` or anything derived. For async code write `await Assert.ThrowsAsync<T>(() => filing.FileAsync(2024, 30_000m))` (or `ThrowsAnyAsync<T>`). Passing a Task-returning lambda to `Throws<T>` does not compile, because that overload is marked obsolete as an error that tells you to use `ThrowsAsync`. Every variant returns the caught exception, so you can assert on its message, and `Assert.Throws<T>("income", () => ...)` also checks `ParamName` for `ArgumentException` types. `Record.Exception` and `Record.ExceptionAsync` capture an exception without asserting.

code

csharp · 20 lines
csharp
public class TaxGuardTests
{
    private readonly TaxCalculator _calculator = new(TaxBrackets.Default2026);

    [Fact]
    public void Negative_income_is_rejected() =>
        Assert.Throws<ArgumentOutOfRangeException>(
            "income", () => _calculator.Calculate(-1m));

    [Fact]
    public async Task Filing_for_a_closed_year_fails()
    {
        var filing = new TaxFilingService(new FakeYearCalendar(closedYears: [2024]));

        var ex = await Assert.ThrowsAsync<InvalidOperationException>(
            () => filing.FileAsync(year: 2024, income: 30_000m));

        Assert.Contains("2024", ex.Message);
    }
}

go deeper

for a junior

Recall that xUnit.net asserts exceptions with Assert.Throws<T> around a lambda, and that it returns the exception.

for a middle

Explain exact versus derived matching with ThrowsAny, the paramName overload, and why async code needs an awaited ThrowsAsync.

for a senior

Catch the silent-pass bug of an unawaited ThrowsAsync in review, and avoid exception tests that blur setup failures with the behaviour under test.

for a principal

Set a team convention: exact types for public contracts, ThrowsAny only where any subtype is acceptable, and analyzers or reviews that flag unawaited assertions.

## Asserting on a statement, not on a method Some test frameworks let you put an attribute on a test to say it should end with an exception. xUnit.net offers no such attribute. That is deliberate: an attribute passes if **any** line of the test throws the expected type, including a line in the arrange step that was never meant to fail. xUnit.net instead asks you to wrap the exact call in a delegate and hand it to an assertion, which runs the delegate, catches what it throws and checks it. ```csharp var ex = Assert.Throws<ArgumentOutOfRangeException>(() => _calculator.Calculate(-1m)); ``` If the delegate throws nothing, or throws a different type, the assertion fails and says what actually happened. ## The four families | Assertion | Accepts | Delegate | Returns | |---|---|---|---| | `Assert.Throws<T>` | exactly `T` | `Action` or `Func<object?>` | `T` | | `Assert.ThrowsAny<T>` | `T` or any subclass | `Action` or `Func<object?>` | `T` | | `Assert.ThrowsAsync<T>` | exactly `T` | `Func<Task>` | `Task<T>` | | `Assert.ThrowsAnyAsync<T>` | `T` or any subclass | `Func<Task>` | `Task<T>` | Non-generic overloads such as `Assert.Throws(typeof(T), ...)` exist for when the type is only known at run time; they return `Exception`. The exact-type rule matters more often than people expect. `ArgumentOutOfRangeException` and `ArgumentNullException` both derive from `ArgumentException`, so `Assert.Throws<ArgumentException>` **fails** when the calculator throws either of them. Use the precise type when you care which one is thrown, and `ThrowsAny<ArgumentException>` when any argument problem is acceptable. ## Inspecting the exception - Every variant **returns the exception**, so further asserts can check its details, for example `Assert.Contains("2024", ex.Message)`. - For the `ArgumentException` family, `Assert.Throws<T>("income", () => ...)` also verifies `ParamName`, failing if the exception names a different parameter. - Overloads with an `inspector` function (`Func<T, string?>`) let you validate the exception inline: return `null` when it is acceptable or a message explaining why not. ## The async traps Async code is where exception tests most often go wrong: 1. **Forgetting `await`.** `Assert.ThrowsAsync<T>` returns a `Task<T>` that holds the verdict. If the test discards it, the test method finishes without observing the result and is reported as passed, whether or not anything was thrown. Make the test `async Task` and await the assertion. 2. **Using the synchronous assertion.** `Assert.Throws<T>(() => filing.FileAsync(...))` binds to an overload taking `Func<Task>` that is marked `[Obsolete(..., true)]`, so the build fails with "You must call Assert.ThrowsAsync<T> (and await the result) when testing async code." That is a feature: a synchronous check would only see the returned task, not the exception inside it. 3. **Blocking instead of awaiting.** Calling `.Result` or `.Wait()` inside the delegate wraps the failure in `AggregateException`, so an exact-type assertion against the inner type fails. ## What to assert, and what to leave alone A good exception test pins the parts of the failure that are a contract and nothing else: - **The type** is almost always a contract, because callers catch by type. - **`ParamName`** is a contract for argument guards; the `paramName` overload makes it a one-liner. - **The full message text** usually is not. Asserting an exact sentence breaks when wording or localisation changes; check that it mentions the key value, as `Assert.Contains("2024", ex.Message)` does, or skip it. - **Side effects** matter too: after the throw, assert that nothing was persisted or published, otherwise a method that throws halfway through can leave half-written state that the type check never sees. ## Capturing without asserting `Record.Exception(() => ...)` and `await Record.ExceptionAsync(() => ...)` run the code and return the exception, or `null` if nothing was thrown, without judging it. They suit tests that keep the act and assert steps visibly separate, and tests that must prove nothing was thrown, via `Assert.Null(ex)`. ## In the tax-bracket suite Two error paths are typical: a guard clause that rejects negative income with `ArgumentOutOfRangeException` naming the `income` parameter, and an async filing service that refuses a closed tax year with `InvalidOperationException`. The first uses the `paramName` overload of `Throws<T>`; the second awaits `ThrowsAsync<T>` and then checks the message names the year. Both assert on one statement, so an unexpected failure while building the calculator or the service is reported as an error in setup rather than mistaken for the expected exception.

  • Why can a test that calls Assert.ThrowsAsync without await pass when nothing is thrown?
    `ThrowsAsync` returns a `Task<T>`, and the assertion's verdict lives inside that task. If the test discards it, the test method returns without observing the outcome, so the runner records a pass. Declare the test `async Task` and `await` the call so a missing or wrong exception fails the test.
  • When would you use Record.Exception instead of Assert.Throws?
    `Record.Exception(() => ...)` and `Record.ExceptionAsync` run the code and return the exception or `null` without asserting. That keeps acting and asserting in separate statements and lets you prove that nothing was thrown with `Assert.Null(ex)`. `Assert.Throws` is shorter when a type check on one call is all you need.

  • Mark the test with [ExpectedException(typeof(ArgumentException))] to expect an exception in xUnit.net.
  • Assert.Throws<ArgumentException> also passes when ArgumentOutOfRangeException is thrown.
  • Assert.Throws<T> works fine with Task-returning lambdas; ThrowsAsync is only a convenience.
  • Assert.ThrowsAsync can be called without await because it checks synchronously.
  • Assert.ThrowsAny<T> is simply an alias for Assert.Throws<T>.