In MSTest 4, why did [ExpectedException] give way to Assert.Throws and Assert.ThrowsExactly, and how do the two differ?
answer
- any line could satisfy the attribute
- removed in MSTest 4
- derived types accepted or rejected
- returns the caught exception
- ThrowsAsync and ThrowsExactlyAsync
basics
~20 s[ExpectedException] passed when any line of the test threw, so it could hide bugs, and MSTest 4 removed it. Assert.Throws<T> wraps only the call under test and accepts T or a subclass; Assert.ThrowsExactly<T> requires exactly T. Both return the exception.
solid answer
~40 s`[ExpectedException(typeof(T))]` sat on the method, so the test passed if **any** statement threw `T` — including the arrange step — and the exception could not be inspected. MSTest 4 removed it, along with `Assert.ThrowsException`. The replacements wrap just the call under test in a lambda. `Assert.Throws<T>` passes when the call throws `T` **or a derived type**; `Assert.ThrowsExactly<T>` passes only for exactly `T`. Both fail with an `AssertFailedException` if nothing is thrown or the type is wrong, and both return the caught exception for further asserts. For a password checker that calls `ArgumentException.ThrowIfNullOrEmpty`, `Evaluate(null)` throws `ArgumentNullException`: `Throws<ArgumentException>` passes, `ThrowsExactly<ArgumentException>` fails. Async code uses `await Assert.ThrowsAsync<T>` or `ThrowsExactlyAsync<T>`.
code
csharp · 19 lines[TestMethod]
public void Evaluate_Null_ThrowsArgumentNullException()
{
var checker = new PasswordStrengthChecker();
ArgumentNullException ex = Assert.ThrowsExactly<ArgumentNullException>(
() => checker.Evaluate(null!));
Assert.AreEqual("password", ex.ParamName);
}
[TestMethod]
public void Evaluate_Empty_ThrowsAnArgumentException()
{
var checker = new PasswordStrengthChecker();
// Passes for ArgumentException or any type derived from it.
Assert.Throws<ArgumentException>(() => checker.Evaluate(""));
}go deeper
Recall that MSTest 4 has no ExpectedException: wrap the throwing call in Assert.ThrowsExactly<T>(() => ...) and use the returned exception if you need its details.
Explain the derived-type rule that separates Throws from ThrowsExactly with a BCL example, the AssertFailedException on mismatch, and the awaited async forms.
Plan the migration: run the 3.x analyzers and code fixes before upgrading, keep exact-type semantics by default, and keep each Throws lambda to the single call under test.
Set a team rule for exception contracts: which types are public API worth pinning with ThrowsExactly, and where a looser Throws check avoids churn when implementations refine exceptions.
## What the attribute got wrong In MSTest 1 to 3 an exception test looked like a normal test with **`[ExpectedException(typeof(ArgumentNullException))]`** on top. The attribute told the framework: if the method ends by throwing that type, count it as a pass. Three problems followed from where the attribute sat: 1. **Scope.** The whole method was covered. If the arrange step — building a `PasswordPolicy`, say — threw the expected type by accident, the test passed without ever reaching the call it was meant to check. 2. **No inspection.** The exception was swallowed by the framework, so a test could not check `ParamName` or the message. 3. **Hidden statements.** Any code after the throwing line was silently skipped, which made such tests hard to read. Analyzer MSTEST0006 (MSTest 3.2) flagged the attribute and offered a code fix, MSTEST0039 (MSTest 3.8) did the same for the old `Assert.ThrowsException` methods, and **MSTest 4 removed both APIs** — together with those two analyzers, since nothing remains to flag. Upgrading a project that still uses them is therefore easiest on the last 3.x release, with its code fixes, before moving to 4. ## The replacements MSTest 4's `Assert` class has four methods, all generic over the expected exception type `TException`: | Method | Accepts derived types | Use for | |---|---|---| | `Assert.Throws<TException>(Action)` | yes | synchronous code | | `Assert.ThrowsExactly<TException>(Action)` | no | synchronous code | | `Assert.ThrowsAsync<TException>(Func<Task>)` | yes | async code, awaited | | `Assert.ThrowsExactlyAsync<TException>(Func<Task>)` | no | async code, awaited | All four: - run only the delegate passed in, so the arrange and assert steps stay outside the check; - fail with **`AssertFailedException`** when nothing is thrown or the thrown type does not match, with the delegate's source text in the message; - **return the caught exception**, typed as `TException`, so the test can assert on its properties. The sync forms also take a `Func<object?>`, so an expression lambda that returns a value works too. ## `Throws` versus `ThrowsExactly` The difference is a single comparison: `Throws` checks `ex is TException`, `ThrowsExactly` checks that the exception's type **equals** `TException`. That matters wherever the BCL throws a subclass. `ArgumentException.ThrowIfNullOrEmpty(password)` throws `ArgumentNullException` for `null` and a plain `ArgumentException` for an empty string: - `Assert.Throws<ArgumentException>(() => checker.Evaluate(null!))` passes, because `ArgumentNullException` derives from `ArgumentException`; - `Assert.ThrowsExactly<ArgumentException>(() => checker.Evaluate(null!))` fails, because the type is not exactly `ArgumentException`; - `Assert.ThrowsExactly<ArgumentNullException>(() => checker.Evaluate(null!))` passes. Use `ThrowsExactly` when the precise type is part of the contract — callers catch `ArgumentNullException` specifically. Use `Throws` when any member of a family is acceptable and you do not want the test to break if the implementation starts throwing a more specific subclass. ## Keeping the lambda honest The point of the lambda is to narrow the check to one call, so keep it to one statement. Analyzer **MSTEST0051** reports a `Throws` lambda containing several statements. For async code, `await` the `Async` variants; a sync assertion that blocks on an async call (`.Result`, `.Wait()`) is what **MSTEST0064** reports. ## Inspecting the returned exception Because the assertion hands back the exception typed as `TException`, the follow-up checks read naturally: - `ParamName` — proves the right argument was rejected, which matters once a method validates several; - `Message` — worth asserting only when the text is part of the contract, such as a validation message shown to users; otherwise it makes tests brittle; - `InnerException` — checks that a wrapper exception preserved its cause. One caution applies inside the experimental `Assert.Scope()` (diagnostic `MSTESTEXP`), which collects several failures before reporting: a failed `Throws` there records the failure and returns `null` instead of throwing, so code that dereferences the result inside the scope hits a `NullReferenceException`. Read the returned exception outside the scope. ## A migration in one line The migration guide's own rewrite is mechanical: delete the attribute and wrap the call that should throw. - Before (MSTest 3): `[ExpectedException(typeof(ArgumentNullException))]` on the method, `checker.Evaluate(null!)` in the body. - After (MSTest 4): `Assert.ThrowsExactly<ArgumentNullException>(() => checker.Evaluate(null!));` in the body. `ThrowsExactly` is the faithful translation, because the attribute did not accept derived types by default either. Switch to `Throws` only where the looser match is what the test really means.
- How do you assert that an async MSTest 4 call throws?Await the async variant: `await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => checker.EvaluateRemoteAsync(pwd));` inside an `async Task` test. It awaits the returned task and checks the exception it faults with. Blocking with `.Result` inside a sync `Throws` is what MSTEST0064 reports, and an un-awaited async assertion checks nothing.
- Why is ThrowsExactly the faithful replacement for [ExpectedException]?The attribute matched the exact type unless its `AllowDerivedTypes` option was set, so a straight swap to `Assert.ThrowsExactly<T>` keeps each test's meaning. Moving to `Assert.Throws<T>` loosens the check to subclasses, which is a deliberate choice to make per test, not a default.
- What does a failing Assert.ThrowsExactly report when the wrong exception is thrown?It throws `AssertFailedException`, failing the test with a message that names the expected type, the actual exception and the delegate's source text captured through caller-argument expression. Since MSTest 4.3 the message also carries the thrown exception's stack trace and inner exceptions.
- [ExpectedException] is still the idiomatic way to test exceptions in MSTest 4.
- Assert.ThrowsExactly<ArgumentException> passes when ArgumentNullException is thrown.
- Assert.Throws<T> fails when the code throws a subclass of T.
- Assert.ThrowsException is the MSTest 4 name for checking a thrown exception.
- A Throws lambda should wrap the whole arrange-and-act block to be safe.
- Assert.Throws returns void, so the exception cannot be inspected.
Assumes MSTest 4.4.1: v4 removed ExpectedExceptionAttribute and Assert.ThrowsException; Assert.Throws, ThrowsExactly and their async forms exist since MSTest 3.8.