skip to content

Upgrading a test project from MSTest 3 to MSTest 4, which attribute, Assert and TestContext changes break the build or quietly change behaviour?

level: seniorimportance: should knowfreq 32%

answer

  1. not binary compatible: recompile everything
  2. a positional TestMethod string
  3. ClassCleanupBehavior and TestTimeout gone
  4. ExpectedException and ThrowsException gone
  5. TestContext throws in fixtures

basics

~10 s

MSTest 4 removes [ExpectedException], Assert.ThrowsException, ClassCleanupBehavior and TestTimeout, retypes TestContext.Properties, and silently changes [TestMethod("name")], class-cleanup timing and TestContext reads in initializers. It is not binary compatible, so everything built on 3 is recompiled.

solid answer

~40 s

Start by recompiling every library built against MSTest 3 — v4 is not binary compatible. The build then breaks where APIs were removed: `[ExpectedException]` and `Assert.ThrowsException` (use `Assert.ThrowsExactly`/`Throws`), `ClassCleanupBehavior` (plain `[ClassCleanup]`), the `TestTimeout` enum (`int.MaxValue`), `TestContext.ManagedType` (`FullyQualifiedTestClassName`), `Properties.Contains` (now `IDictionary<string, object>`, so `ContainsKey`), and Assert overloads taking format arguments (use interpolation). Custom `TestMethodAttribute`s move from `Execute` to `ExecuteAsync`. The quiet changes hurt more: `[TestMethod("name")]` still compiles but binds the string to a caller-file-path parameter (MSTEST0056 warns), `[ClassCleanup]` now runs at the end of its class instead of the assembly, and reading `TestContext.TestName` in a class or assembly initializer now throws. Fix the removals on the last 3.x first, where analyzers offer code fixes.

code

csharp · 18 lines
csharp
[TestClass]
public sealed class PasswordStrengthCheckerTests
{
    // MSTest 3: [TestMethod("Null password is rejected")]
    // In v4 that string would bind to callerFilePath (MSTEST0056).
    [TestMethod(DisplayName = "Null password is rejected")]
    public void Evaluate_Null_Throws()
    {
        var checker = new PasswordStrengthChecker();

        // MSTest 3 used [ExpectedException(typeof(ArgumentNullException))].
        Assert.ThrowsExactly<ArgumentNullException>(() => checker.Evaluate(null!));
    }

    // MSTest 3: [ClassCleanup(ClassCleanupBehavior.EndOfClass)]
    [ClassCleanup]
    public static void DeleteFixtureFiles() => File.Delete("policy-fixture.json");
}

go deeper

for a junior

Recall the headline removals: no [ExpectedException] and no Assert.ThrowsException in MSTest 4, replaced by Assert.ThrowsExactly around the throwing call.

for a middle

List the compile-time breaks and their replacements, including ClassCleanupBehavior, the TestTimeout enum, TestContext.ManagedType and the retyped TestContext.Properties dictionary.

for a senior

Lead with the silent changes — the positional TestMethod string, class-cleanup timing, TestContext throwing in initializers — and sequence the upgrade so the 3.x code fixes run first.

for a principal

Plan the upgrade across many test projects: shared libraries recompiled in lockstep, a warnings budget for the raised analyzers, and one owner for the cleanup-timing audit.

## Why the upgrade is not a version bump MSTest 4 is **not binary compatible** with MSTest 3. Any assembly compiled against v3 — a shared test-helpers library, a custom attribute package — must be recompiled against v4. Beyond that the changes fall into two groups: **source breaks**, which the compiler finds for you, and **behaviour changes**, which it does not. This answer covers the test-authoring surface: attributes, `Assert` and `TestContext`. Package, SDK and runner changes are a separate checklist. ## Source breaks the compiler reports | MSTest 3 | MSTest 4 replacement | |---|---| | `[ExpectedException(typeof(T))]` | `Assert.ThrowsExactly<T>(() => ...)` around the throwing call | | `Assert.ThrowsException<T>` / `ThrowsExceptionAsync<T>` | `Assert.ThrowsExactly<T>` / `ThrowsExactlyAsync<T>` (or `Throws`) | | `[ClassCleanup(ClassCleanupBehavior.EndOfClass)]` | `[ClassCleanup]` | | `[Timeout(TestTimeout.Infinite)]` | `[Timeout(int.MaxValue)]` | | `TestContext.ManagedType` | `TestContext.FullyQualifiedTestClassName` | | `TestContext.Properties.Contains(key)` | `ContainsKey(key)` — `Properties` is now `IDictionary<string, object>` | | `Assert.AreEqual(a, b, "{0} failed", name)` | `Assert.AreEqual(a, b, $"{name} failed")` | | `Assert.IsInstanceOfType<T>(x, out var t)` | `var t = Assert.IsInstanceOfType<T>(x)` | | `ConditionBaseAttribute.ShouldRun` | `IsConditionMet` | Two more affect teams with their own extensions: - a custom **`TestMethodAttribute`** overrides `ExecuteAsync` instead of `Execute` (the change fixes deadlocks from synchronous blocking), and its constructor should pass the caller-info parameters through to the base; - the **unfolding strategy** moved from `DataRowAttribute`/`DynamicDataAttribute` to `TestMethodAttribute`. ## Behaviour changes the compiler misses 1. **`[TestMethod("Readable name")]`.** The v4 constructor is `TestMethodAttribute(string callerFilePath = "", int callerLineNumber = -1)`. A positional string still compiles — it becomes the *file path*, and the display name is lost. Analyzer **MSTEST0056** (a warning) flags it; the fix is `[TestMethod(DisplayName = "Readable name")]`. 2. **Class cleanup timing.** MSTest 3 ran `[ClassCleanup]` at the end of the **assembly** by default. MSTest 4 always runs it when the **class** finishes. A cleanup that deleted a database or file another class still used now runs earlier; move such logic to `[AssemblyCleanup]`. 3. **`TestContext` in initializers.** Reading `TestName` in `[ClassInitialize]` or `[AssemblyInitialize]`, or `FullyQualifiedTestClassName` in `[AssemblyInitialize]`, now throws `InvalidOperationException` instead of yielding nothing useful. MSTEST0048 warns about such reads. 4. **Analyzer severities.** MSTest 4.0 raised twelve analyzers from Info to Warning (MSTest 4.1 lowered four back), so a build with `TreatWarningsAsErrors` can fail on rules that were silent before. ## What does not change It helps to know what to leave alone, so the review stays focused: - `[TestClass]`, `[TestMethod]` without a positional argument, `[DataRow]` and `[DynamicData]` keep their meaning; - the lifecycle attributes keep their signatures — `public static` with one `TestContext` for the assembly and class initializers; - `Assert.AreEqual`, `Assert.IsTrue` and the other everyday assertions keep their names; only the format-argument overloads went away; - `Assert.Throws` and `Assert.ThrowsExactly`, added in MSTest 3.8, are unchanged — a suite already using them has nothing to rewrite there. A suite written in the MSTest 3.8+ style therefore needs little beyond a recompile and the silent-change review. The packages, the project SDK and the choice of runner change in the same upgrade, but they are reviewed on their own. ## A migration order that works 1. **Stay on the last 3.x release first.** Its analyzers carry code fixes: MSTEST0006 rewrites `[ExpectedException]`, MSTEST0039 rewrites `Assert.ThrowsException`, MSTEST0053 removes format arguments. MSTest 4.0 **removed** those analyzers along with the APIs, so after the bump there is nothing left to auto-fix. 2. **Bump the packages**, recompile shared libraries and fix the remaining compile errors from the table. 3. **Grep for `[TestMethod("`** and for `[ClassCleanup]` methods that assumed end-of-assembly timing. 4. **Run the suite** and read the new warnings before deciding which to silence. For the reserved password-strength suite this is typically small: a few `ExpectedException` tests on `Evaluate(null)` become `Assert.ThrowsExactly<ArgumentNullException>`, and a class cleanup that deleted a shared breached-password file moves to `[AssemblyCleanup]`.

  • Why migrate ExpectedException tests before bumping to MSTest 4 rather than after?
    The code fixes live in analyzers that MSTest 4.0 removed: MSTEST0006 for `[ExpectedException]` and MSTEST0039 for `Assert.ThrowsException`. On the last 3.x release they flag every use and rewrite it in one pass; after the bump the APIs simply fail to compile and each test has to be fixed by hand.
  • A v4 cleanup now deletes a file another test class still needs; what changed and where does the code go?
    In MSTest 3, `[ClassCleanup]` defaulted to running at the end of the assembly, so the file survived until every class finished. MSTest 4 removed `ClassCleanupBehavior` and runs class cleanup when its class completes. Cleanup that must wait for the whole run belongs in `[AssemblyCleanup]`.

  • MSTest 4 is binary compatible, so v3-built helper libraries keep working.
  • [TestMethod("name")] still sets the display name after the upgrade.
  • ClassCleanupBehavior.EndOfAssembly is still the way to defer class cleanup.
  • The MSTEST0006 code fix can be run after upgrading to MSTest 4.
  • Reading TestContext.TestName in [ClassInitialize] returns null in MSTest 4.
  • If the upgraded project compiles, no test behaviour has changed.

Assumes MSTest 4.4.1 upgraded from 3.x; MSTest 4 is not binary compatible with 3, and the 3.x migration analyzers MSTEST0006, MSTEST0039 and MSTEST0053 were removed in 4.0.