skip to content

In NUnit 5, how do Assert.Multiple and Assert.EnterMultipleScope collect failures, and what traps appear when exceptions or async code run inside them?

level: seniorimportance: should knowfreq 32%

answer

  1. failures recorded, not thrown
  2. MultipleAssertException at the end
  3. a using block around the scope
  4. Assert.Throws may return null inside
  5. MultipleAsync for awaited assertions

basics

~20 s

Inside Assert.Multiple or a using (Assert.EnterMultipleScope()) block, a failed NUnit assertion is recorded instead of thrown; all failures are reported together when the outermost scope ends. Unexpected exceptions still end the block, and Assert.Throws may return null.

solid answer

~40 s

Normally a failing `Assert.That` throws and the test stops at the first failure. In a multiple-assert scope NUnit **records** each failure and keeps going; when the outermost scope is disposed it throws `MultipleAssertException` and the result lists every failure. `Assert.Multiple(() => ...)` and `await Assert.MultipleAsync(async () => ...)` wrap the same mechanism as `using (Assert.EnterMultipleScope()) { ... }`. Traps: an **unexpected exception** (a `NullReferenceException` from a dependent line) still escapes and ends the block; `Assert.Throws<T>` and `Assert.Fail` do not throw inside a scope, so `Assert.Throws` can return `null` and the next line dereferencing it crashes; the synchronous `Assert.Multiple(Func<Task>)` blocks on async code; and a scope that is never disposed makes the test an error, "Test completed with 1 active assertion scope(s)".

code

csharp · 15 lines
csharp
[Test]
public void Negative_weight_is_rejected()
{
    ArgumentOutOfRangeException? ex;

    using (Assert.EnterMultipleScope())
    {
        ex = Assert.Throws<ArgumentOutOfRangeException>(
            () => _calculator.Calculate(-1m, Zone.Europe, express: false));
        // Inside the scope a missing exception is recorded, and ex is null
    }

    // Dereference only after the scope; a recorded failure has ended the test by now
    Assert.That(ex!.ParamName, Is.EqualTo("weightKg"));
}

go deeper

for a junior

Recall that Assert.Multiple reports every failed assertion in a block instead of stopping at the first one.

for a middle

Explain the three scope forms, nesting, and that MultipleAssertException is thrown when the outermost scope is disposed.

for a senior

Show the traps from real suites: dependent assertions, a null from Assert.Throws, blocked async lambdas and an undisposed scope, and how to structure guards around the scope.

for a principal

Set the team's convention on when a scope helps diagnosis and when it hides that several behaviours were packed into one test.

## The problem it solves By default an NUnit assertion that fails **throws** an `AssertionException`, so the test stops at the first failure. For a shipping quote with a base charge, a weight charge, an express surcharge and a total, that means four test runs to discover four wrong numbers. A **multiple-assert scope** reports them all in one run. ## Three ways to open a scope | Form | Use | |---|---| | `using (Assert.EnterMultipleScope()) { ... }` | plain block, works with `await` inside an async test | | `Assert.Multiple(() => { ... })` | lambda form for synchronous assertions | | `await Assert.MultipleAsync(async () => { ... })` | lambda form for asynchronous assertions | `Assert.Multiple` and `Assert.MultipleAsync` are thin wrappers: each opens `Assert.EnterMultipleScope()` in a `using` and runs the delegate inside it. ## What happens inside the scope 1. Each failing assertion is **recorded** in the test result, with its message and stack trace, and execution continues with the next line. 2. Scopes **nest**; only the **outermost** scope reports. 3. When the outermost scope is disposed and failures were recorded, NUnit throws **`MultipleAssertException`**, which ends the test and lists every recorded failure. 4. If another exception is already propagating out of the block, NUnit does not throw `MultipleAssertException` on top of it, so the original exception is not lost. `Assert.Fail()` follows the same rule: inside a scope it records a failure and returns instead of throwing. ## The traps - **Unexpected exceptions are not collected.** Only assertion failures are recorded. A `NullReferenceException`, a `KeyNotFoundException` or an exception from the code under test escapes the block immediately and the remaining assertions never run. - **Dependent assertions.** `Assert.That(quote, Is.Not.Null)` inside the scope does not stop the next line, `quote.Total`, from throwing. Put **guard assertions before** the scope, and keep only independent checks inside it. - **`Assert.Throws` can return `null`.** Outside a scope it throws when no exception occurs; inside a scope it records the failure and returns `null`. A following `ex.ParamName` then crashes with a `NullReferenceException`. Check the exception outside the scope, or guard the dereference. - **Async lambdas.** The overload `Assert.Multiple(Func<Task>)` exists but runs the async delegate synchronously, blocking the test thread until it completes. In an `async Task` test, use `await Assert.MultipleAsync(...)` or a `using` block with `await` inside. - **A scope that is never disposed.** Calling `Assert.EnterMultipleScope()` without `using` leaves the scope open; NUnit then reports the test as an **error**: "Test completed with 1 active assertion scope(s)." - **Debugging.** Because failures do not throw, a debugger does not break at the failing line by default; the runner setting `ThrowOnEachFailureUnderDebugger` makes NUnit throw and catch at each failure when a debugger is attached. ## A good shape ```csharp [Test] public async Task Europe_express_quote_breakdown() { var quote = await _service.QuoteAsync(2m, Zone.Europe, express: true); Assert.That(quote, Is.Not.Null); // guard outside the scope using (Assert.EnterMultipleScope()) { Assert.That(quote.Base, Is.EqualTo(9.00m)); Assert.That(quote.WeightCharge, Is.EqualTo(2.40m)); Assert.That(quote.ExpressSurcharge, Is.EqualTo(5.00m)); Assert.That(quote.Total, Is.EqualTo(16.40m)); } } ``` The guard stops the test cleanly if there is no quote; the four independent checks are all reported in one run. ## Helpers and nesting - **Assertion helpers** called inside a scope record their failures too, because the scope is tracked on the test's execution context, not on the calling method. A helper such as `AssertQuoteLine(line, 2.40m)` can therefore be reused inside or outside a scope. - **Nested scopes** are allowed. A helper that opens its own scope while the caller already has one does not report early; only the outermost scope throws at the end. - **Warnings** issued with `Assert.Warn` are recorded the same way and do not fail the test; they only appear beside the failures in the result. ## When not to use it - When later checks are **meaningless after an early failure**: if the quote's currency is wrong, comparing amounts adds noise. - As a way to cram unrelated behaviours into one test; a scope reports several facts about **one** result, not several tests.

  • What exception ends an NUnit test when assertions inside a multiple scope have failed?
    `MultipleAssertException`, thrown when the outermost scope is disposed and at least one failure was recorded. Its result lists every recorded failure. NUnit skips throwing it if another exception is already leaving the block, so that exception is not masked.
  • Which form should an async NUnit test use for multiple assertions?
    Either `await Assert.MultipleAsync(async () => ...)` or a `using (Assert.EnterMultipleScope())` block with `await` statements inside. The synchronous `Assert.Multiple(Func<Task>)` overload also accepts an async lambda, but it blocks the test thread until the delegate completes.
  • Why does an NUnit test report 'Test completed with 1 active assertion scope(s)'?
    `Assert.EnterMultipleScope()` was called without disposing the returned object, usually because the `using` was forgotten. NUnit detects the open scope when the test method ends and reports the test as an error. Wrap the call in `using`.

A vehicle inspector with a checklist writes down every defect and hands over the full list at the end instead of stopping at the first worn tyre; but if the engine catches fire mid-inspection, the inspection simply ends. Assertion failures are the noted defects; an unexpected exception is the fire.

  • Assert.Multiple also catches NullReferenceException and reports it with the rest
  • Inside a multiple scope Assert.Throws still throws when nothing is thrown
  • Assert.EnterMultipleScope works without a using block
  • Assert.Fail inside Assert.Multiple stops the block immediately
  • Each failing assertion in the scope throws its own AssertionException
  • A null check inside the scope protects the lines after it