skip to content

In MSTest 4, in what order do the assembly, class and test lifecycle hooks run, and what signatures must they have?

level: middleimportance: should knowfreq 55%

answer

  1. assembly, then class, then each test
  2. public static with one TestContext
  3. constructor before TestInitialize
  4. ClassCleanup when the class finishes
  5. InheritanceBehavior.BeforeEachDerivedClass

basics

~20 s

[AssemblyInitialize] runs once, [ClassInitialize] once per class, then for each test: constructor, [TestInitialize], the test, [TestCleanup], Dispose; [ClassCleanup] and [AssemblyCleanup] close out. Assembly and class hooks are public static, and both initializers take one TestContext.

solid answer

~40 s

MSTest 4 runs hooks from the widest scope inward. `[AssemblyInitialize]` runs once before any test; `[ClassInitialize]` runs once before a class's first test. Then, for every test — and every data row — MSTest creates a new instance (constructor), runs `[TestInitialize]` (base class first), the test, `[TestCleanup]` (derived class first), then `DisposeAsync`/`Dispose`. `[ClassCleanup]` runs when that class's tests are done and `[AssemblyCleanup]` at the very end. Assembly and class hooks must be `public static`, return `void`, `Task` or `ValueTask`, and the two initializers take exactly one `TestContext`; the cleanups take none or one. Test-level hooks are public instance methods with no parameters. If the constructor throws, cleanup and dispose are skipped; if `[TestInitialize]` throws, they still run. Since v4 `[ClassCleanup]` always runs at the end of its class.

code

csharp · 23 lines
csharp
[TestClass]
public sealed class BreachedPasswordTests
{
    private static HashSet<string> s_breached = null!;
    private PasswordStrengthChecker _checker = null!;

    [ClassInitialize]
    public static async Task LoadListAsync(TestContext context)
    {
        string[] lines = await File.ReadAllLinesAsync("breached-top-1000.txt", context.CancellationToken);
        s_breached = new HashSet<string>(lines, StringComparer.Ordinal);
    }

    [TestInitialize]
    public void CreateChecker() => _checker = new PasswordStrengthChecker(s_breached);

    [TestMethod]
    public void Evaluate_BreachedPassword_IsWeak()
        => Assert.AreEqual(PasswordStrength.Weak, _checker.Evaluate("letmein"));

    [ClassCleanup]
    public static void ReleaseList() => s_breached.Clear();
}

go deeper

for a junior

Recall the nesting: assembly hooks once, class hooks once per class, TestInitialize and TestCleanup around every test, with a new class instance each time.

for a middle

Explain the signatures (public static plus TestContext for the initializers), why shared state must be static, and what runs when a constructor or TestInitialize throws.

for a senior

Use the scopes deliberately: expensive fixtures at class or assembly level, fallible setup in TestInitialize, and the v4 ClassCleanup timing when upgrading suites that relied on end-of-assembly cleanup.

for a principal

Judge shared fixtures against isolation: class-wide state speeds suites up but couples tests, so define which resources may be shared and how a failing fixture is surfaced to the team.

## Four scopes, widest first MSTest groups setup and teardown into scopes and runs them from the outside in. Each hook is an ordinary method marked with an attribute from `Microsoft.VisualStudio.TestTools.UnitTesting`. | Scope | Setup | Teardown | Runs | |---|---|---|---| | Assembly | `[AssemblyInitialize]` | `[AssemblyCleanup]` | once per test assembly | | Class | `[ClassInitialize]` | `[ClassCleanup]` | once per test class | | Every test, assembly-wide | `[GlobalTestInitialize]` | `[GlobalTestCleanup]` | around every test (MSTest 3.10+) | | Test | constructor, `[TestInitialize]` | `[TestCleanup]`, `Dispose` | once per test and per data row | ## The full order for one class For a class of password-strength tests whose `[ClassInitialize]` loads a breached-password list: 1. `[AssemblyInitialize]` — once, before any test in the assembly. 2. `[ClassInitialize]` — once, before the class's first test. 3. For **each** test method, and for **each** data row of a parameterised one: 1. a new instance is created with the constructor; 2. the `TestContext` property is set, if the class declares one; 3. any `[GlobalTestInitialize]` methods run; 4. `[TestInitialize]` runs, base class before derived class; 5. the test method runs; 6. `[TestCleanup]` runs, derived class before base class; 7. any `[GlobalTestCleanup]` methods run; 8. `DisposeAsync` and then `Dispose` run, if implemented. 4. `[ClassCleanup]` — once the class's tests are finished. 5. `[AssemblyCleanup]` — once, after every test in the assembly. Because every test gets a **new instance**, instance fields cannot carry state from one test to the next. State shared across a class lives in **static** fields that `[ClassInitialize]` fills. ## Signatures MSTest accepts - **Assembly and class hooks** are `public static`, return `void`, `Task` or `ValueTask`, and live in a `[TestClass]`. - `[AssemblyInitialize]` and `[ClassInitialize]` take **exactly one** `TestContext` parameter. - `[AssemblyCleanup]` and `[ClassCleanup]` take **no parameters or one** `TestContext`. - There is one of each assembly hook per assembly and one of each class hook per class. - **Test-level hooks** (`[TestInitialize]`, `[TestCleanup]`) are public **instance** methods with no parameters, returning `void`, `Task` or `ValueTask`. A wrong signature is reported twice: analyzers MSTEST0008 to MSTEST0013 flag it at build time, and at run time the adapter fails the affected tests with a message such as "Method … has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext." ## When a hook throws - **`[AssemblyInitialize]` throws** — MSTest reports "Assembly Initialization method … threw exception … Aborting test execution." and no test in that assembly passes. - **`[ClassInitialize]` throws** — the tests of that class fail with the initialization error; other classes are unaffected. - **The constructor throws** — no instance exists, so `[TestCleanup]` and `Dispose` do **not** run. - **`[TestInitialize]` throws** — the test fails, but `[TestCleanup]` and `Dispose` **still** run. That asymmetry is the main argument for doing fallible or async setup in `[TestInitialize]` and keeping constructors to simple `readonly` field assignments. ## Choosing the scope for a resource Put each piece of setup at the widest scope that is still safe to share: - **Assembly** — something every class needs and that is expensive to start, such as a test host or a database created once; release it in `[AssemblyCleanup]`. - **Class** — read-only data a group of tests shares, such as the breached-password list above; keep it in a static field and never mutate it from a test. - **Test** — anything a test changes: the checker under test, a policy object, a temp file. A fresh copy per test is what keeps a failure in one test from leaking into the next. Two habits avoid most surprises. Declare async hooks as `async Task`, never `async void`, so MSTest can await them and see their exceptions. And prefer the constructor for simple `readonly` fields while keeping anything async or fallible in `[TestInitialize]`, which also accepts `[Timeout]`. ## Inheritance and the v4 change `[ClassInitialize]` and `[ClassCleanup]` accept an `InheritanceBehavior`. With the default, `None`, a base class's hook runs only for the base class itself; with `InheritanceBehavior.BeforeEachDerivedClass`, a base `[ClassInitialize]` runs before the tests of each derived class. In MSTest 3 a `[ClassCleanup]` ran, by default, at the **end of the assembly**, and `ClassCleanupBehavior.EndOfClass` was needed to get the intuitive timing. MSTest 4 removed the `ClassCleanupBehavior` enum: class cleanup now always runs when its class finishes, and logic that must wait for the whole run belongs in `[AssemblyCleanup]`.

  • Can a base class's [ClassInitialize] run for each derived MSTest test class?
    Yes, with `[ClassInitialize(InheritanceBehavior.BeforeEachDerivedClass)]` on the base method. The default, `InheritanceBehavior.None`, runs it only for the declaring class. `[ClassCleanup]` accepts the same argument, so shared base-class fixtures can set up and tear down around every derived class.
  • Why does reading TestContext.TestName inside [ClassInitialize] throw in MSTest 4?
    The `TestContext` passed to class and assembly initializers describes no single test, and MSTest 4 throws `InvalidOperationException` instead of returning an empty value when a test-only property such as `TestName` is read there. `FullyQualifiedTestClassName` likewise throws in `[AssemblyInitialize]`. Analyzer MSTEST0048 warns about such reads at build time.

A conference: the venue is opened and closed once (assembly hooks), each room is set up before its first session and cleared after its last (class hooks), and every talk gets a fresh microphone check and reset (test hooks). A speaker who never arrives (a failing constructor) leaves nothing on stage to reset.

  • [ClassInitialize] can be an instance method because MSTest creates the class first.
  • In MSTest 4 [ClassCleanup] waits for the end of the assembly by default.
  • [TestInitialize] runs once per class, shared by all of its tests.
  • If the constructor throws, [TestCleanup] still runs to tidy up.
  • [AssemblyCleanup] must declare a TestContext parameter to be valid.
  • Instance fields keep their values from one test method to the next.

Assumes MSTest 4.4.1: v4 removed ClassCleanupBehavior, so [ClassCleanup] always runs at the end of its class instead of the old end-of-assembly default.