Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install migrate-mstest-v3-to-v4@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin migrate-mstest-v3-to-v4 v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install migrate-mstest-v3-to-v4

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/migrate-mstest-v3-to-v4/

Extract the ZIP to .github/skills/ in your repo. The folder name must match migrate-mstest-v3-to-v4 for Copilot to auto-discover it.

Skill Files (2)

SKILL.md 20.9 KB
---
name: migrate-mstest-v3-to-v4
description: >
  Use this skill before answering, planning, or editing any MSTest 3.x-to-4.x
  upgrade or post-upgrade failure. Triggers include "MSTest v4 breaking
  changes"; CS0507/CS0103/CS1061/CS1615; ExecuteAsync, CallerInfo, DisplayName,
  or custom TestMethodAttribute; ClassCleanupBehavior; ContainsKey;
  ThrowsExactly or ExpectedException; IsInstanceOfType out parameters;
  TestTimeout.Infinite; removed TestContext properties; ITestMethod changes;
  StringAssert overloads; MSTEST0056/MSTEST0057; renamed assemblies or
  executor URI; net6/net7 compatibility; TestCase.Id history; TestName in
  ClassInitialize; TreatDiscoveryWarningsAsErrors; ReflectionTypeLoadException
  during discovery; inherited test attributes; custom data-source display names;
  and MSTest.Sdk/MTP or vstest.console discovery changes. Do not use for
  v1/v2-to-v3 leftovers, framework conversion, runner-only migration, or a
  general .NET upgrade.
license: MIT
---

# MSTest v3 -> v4 Migration

Migrate a test project from MSTest v3 to MSTest v4. The outcome is a project using MSTest v4 that builds cleanly, passes tests, and accounts for every source-incompatible and behavioral change. MSTest v4 is **not binary compatible** with MSTest v3 -- any library compiled against v3 must be recompiled against v4.

## First Action

Inspect the supplied project and source before searching the web or answering
from memory. Classify the request as a focused source fix, runtime behavior
change, CI discovery issue, compatibility question, or full migration, then
follow the matching row below. A clean compile does not exclude this skill:
discovery failures, `TestContext` lifecycle exceptions, and test-history
changes are runtime migration failures.

## When to Use

- Upgrading `MSTest.TestFramework`, `MSTest.TestAdapter`, or `MSTest` metapackage from 3.x to 4.x
- Upgrading `MSTest.Sdk` from 3.x to 4.x
- Fixing build errors after updating to MSTest v4 packages
- Resolving behavioral changes in test execution after upgrading to MSTest v4
- Updating custom `TestMethodAttribute` or `ConditionBaseAttribute` implementations for v4

## When Not to Use

- The project already uses MSTest v4 with verified discovery and test execution, and has no remaining migration-related issues
- Upgrading from MSTest v1 or v2 -- use `migrate-mstest-v1v2-to-v3` first, then return here
- The project does not use MSTest
- Migrating between test frameworks (e.g., MSTest to xUnit or NUnit)

## Inputs

| Input | Required | Description |
|-------|----------|-------------|
| Project or solution path | No | The `.csproj`, `.sln`, or `.slnx` entry point containing MSTest test projects. **Discover it yourself** by globbing the working directory; ask only when nothing is found or the choice is genuinely ambiguous |
| Build command | No | How to build (e.g., `dotnet build`, a repo build script). Auto-detect if not provided |
| Test command | No | How to run tests (e.g., `dotnet test`). Auto-detect if not provided |

## Decisions That Change the Result

| Detected request or state | Required action |
|---|---|
| Files are supplied in the current workspace | Search there and open the literal returned paths. The skill directory is not the project directory. If one tool rejects a valid path, retry with another available reader/editor; do not ask the user for a path you can discover. |
| User asks to apply changes to supplied files: "fix my project/files", "please update this source", "make the changes", or "then build and run" | Edit every affected occurrence. Run the narrowest meaningful build/test command against the actual package version; skill activation is not a reason to stop at advice. |
| User asks "what should I expect?", "how do I fix these changes?", for compatibility advice, or for a plan | Answer directly from the actual project state even when source is visible. Keep a single-symptom answer focused; include only adjacent risks that change the decision. |
| Unsupported TFM in a full migration | Update the TFM first, then update MSTest packages, then fix source breaks. Do not bury this order in a release-note inventory. |
| Custom `TestMethodAttribute` subclass | Treat `ExecuteAsync`, CallerInfo propagation, display-name handling, and the subclass's retry/result semantics as one coupled migration. Fix the actual class, not a placeholder example. |
| `MSTest.Sdk` v4 source/API errors (`ManagedType`, `TestTimeout`, `Contains`) | Give the exact source replacements, then add the adjacent runner warning: MTP mode no longer supplies `Microsoft.NET.Test.Sdk`; add it only if VSTest discovery is still required. |
| `MSTest.Sdk` v4 plus `vstest.console` | MTP mode no longer includes `Microsoft.NET.Test.Sdk` in v4. Add it to retain transitional VSTest discovery while keeping MTP, opt into `UseVSTest`, or migrate CI to `dotnet test`. Native MTP requires every project/TFM governed by `global.json` to support it (4.5). |

## Response Guidelines

- **Always identify the current version first**: Before recommending any migration steps, explicitly state the current MSTest version detected in the project (e.g., "Your project uses MSTest v3 (3.8.0)"). This confirms you've read the project files and grounds the migration advice.
- **Resolve, do not assume, the target version**: When the user asks for "latest", query the project's configured package source and select the latest stable MSTest v4 version available at execution time. Never copy the example version from this skill into the result without checking it. Keep all MSTest packages on the same resolved version.
- **Focused fix requests**: Address only matching Step 3 changes with concrete code using the user's types and names. Edit only when a source change is requested; "how do I fix these?" remains an answer request. A green v3 build does not verify v4: update packages when requested or state that limitation. For custom attributes, show the full fixed class with CallerInfo propagation and preserved retry/result semantics. Mention relevant analyzers (e.g., MSTEST0006 for ExpectedException). For `MSTest.Sdk`, explain whether losing the `Microsoft.NET.Test.Sdk` reference affects the visible runner. Skip the full migration workflow.
- **"What to expect" questions** (user asks about breaking changes before upgrading): Present ALL major breaking changes from the Step 3 quick-lookup table -- not just the ones visible in the current code. For each, provide a one-line fix summary. Also mention key behavioral changes from Step 4 (especially TestCase.Id history impact and TreatDiscoveryWarningsAsErrors default). If project code is available, highlight which changes apply directly.
- **Before-upgrade analyzer guidance**: Recommend fixing MSTEST0006, MSTEST0039, and MSTEST0053 warnings while still on v3 because those analyzers are not available in v4. Mention MSTEST0034 when class-cleanup timing is relevant. For `TestMethodAttribute` constructor issues, include MSTEST0056 for display-name arguments and MSTEST0057 for custom attributes that fail to propagate caller info.
- **Full migration requests** (user wants complete migration): Follow the complete workflow below.
- **Behavioral/runtime symptoms**: Match symptoms to Step 4 and give targeted advice, including adjacent behavioral risks. Skip source-breaking changes unless there are also build errors.
- **CI/test-discovery issues**: Match the failure first: resolve loader errors (4.7) rather than suppressing warnings (4.4). For `MSTest.Sdk` v4 plus failing `vstest.console` discovery, explain the missing `Microsoft.NET.Test.Sdk` reference (4.5) and all three paths: add it while preserving MTP, set `UseVSTest`, or switch CI to MTP-native `dotnet test`. Skip the full migration workflow.
- **Explanatory questions** (user asks "is this a known change?", "what else should I watch out for?"): Explain the relevant changes and advise. Mention related changes the user might encounter next. Do not prescribe a full migration procedure.
- **Result proof**: End implementation work with the detected v3 version, resolved v4 version, runner choice, files changed, and actual build/test counts. Never report a build, VSTest compatibility, discovery, or passing tests from inference.

## Workflow

> **Commit strategy:** Do not create commits unless the user asks. Keep package,
> source, and behavioral changes logically separable in the diff, but finish and
> verify the requested migration.

### Step 1: Assess the project

1. Identify the current MSTest version by checking package references for `MSTest`, `MSTest.TestFramework`, `MSTest.TestAdapter`, or `MSTest.Sdk` in `.csproj`, `Directory.Build.props`, or `Directory.Packages.props`.
2. Confirm the starting state: v3 for an upgrade, or v4 for a post-upgrade fix. If already on v4, skip Step 2 unless package changes are needed for the reported issue. If on v1 or v2, use `migrate-mstest-v1v2-to-v3` first.
3. Check target framework(s) -- MSTest v4 drops support for .NET Core 3.1 through .NET 7. Supported target frameworks are: **net8.0**, **net9.0**, **net462** (.NET Framework 4.6.2+), **uap10.0.16299** (UWP), **net9.0-windows10.0.17763.0** (modern UWP), and **net8.0-windows10.0.18362.0** (WinUI).
4. Check for custom `TestMethodAttribute` subclasses and uses of `DataTestMethodAttribute`, `STATestMethodAttribute`, and `UITestMethodAttribute` constructors -- these require changes in v4.
5. Check for usages of `ExpectedExceptionAttribute` -- removed in v4 (deprecated since v3 with analyzer MSTEST0006).
6. Check for usages of `Assert.ThrowsException` (deprecated) -- removed in v4.
7. Search for removed `TestContext` properties, changed `ITestMethod` members, removed cleanup settings, and custom data-source interfaces or overrides listed in Step 3.
8. If code or tools reference MSTest assemblies by name/version or the VSTest executor URI, inventory those references; check whether the test adapter relies on its former `netstandard2.0` asset.
9. Run a clean build to establish a baseline of existing errors/warnings.

### Step 2: Update packages to MSTest v4

First resolve the latest stable v4 version from the configured package source. Pin that exact
version consistently in the metapackage, individual packages, `MSTest.Sdk`, and central package
management.

- For the `MSTest` metapackage, update its `PackageReference` to the resolved exact version.
- For individual packages, update `MSTest.TestFramework` and `MSTest.TestAdapter` to that same version.
- For `MSTest.Sdk`, update the SDK version in the project or `global.json` pin to that same version.

Run `dotnet restore`, then `dotnet build`. Collect all errors for Step 3.

### Step 3: Resolve source breaking changes

Work through compilation errors systematically. Use this quick-lookup table to identify all applicable changes, then apply each fix:

| Error / Pattern in code | Breaking change | Fix |
|---|---|---|
| Custom `TestMethodAttribute` overrides `Execute` | Execute removed | Change to `ExecuteAsync` returning `Task<TestResult[]>` (3.1) |
| `[TestMethod("name")]` or custom attribute constructor | CallerInfo params added | Use `DisplayName = "name"` named param; propagate CallerInfo in subclasses (3.2) |
| `ClassCleanupBehavior.EndOfClass` | Enum removed | Remove argument: just `[ClassCleanup]` (3.3) |
| `TestContext.Properties.Contains("key")` | `Properties` is `IDictionary<string, object>` | Change to `ContainsKey("key")` (3.4) |
| `[Timeout(TestTimeout.Infinite)]` | `TestTimeout` enum removed | Replace with `[Timeout(int.MaxValue)]` (3.5) |
| `TestContext.ManagedType` | Property removed | Use `FullyQualifiedTestClassName` (3.6) |
| `Assert.AreEqual(a, b, "msg {0}", arg)` | Message+params overloads removed | Use string interpolation: `$"msg {arg}"` (3.7) |
| `Assert.ThrowsException<T>(...)` | Renamed | Replace with `Assert.ThrowsExactly<T>(...)` or `Assert.Throws<T>(...)` (3.7) |
| `Assert.IsInstanceOfType<T>(obj, out var t)` | Out parameter removed | Use `var t = Assert.IsInstanceOfType<T>(obj)` (3.7) |
| `[ExpectedException(typeof(T))]` | Attribute removed | Move assertion into test body: `Assert.ThrowsExactly<T>(() => ...)` (3.8) |
| Project targets net5.0, net6.0, or net7.0 | TFM dropped | Change to net8.0 or net9.0 (3.9) |
| `UnfoldingStrategy` on `DataRow` or `DynamicData` | Property moved | Set it on `TestMethodAttribute` instead (3.10) |
| `ConditionBaseAttribute.ShouldRun` | Property renamed | Use `IsConditionMet` (3.11) |
| Public adapter or PlatformServices types | Types internalized or removed | Remove dependencies on those implementation APIs; distinguish the two `ITestMethod` interfaces (3.12) |
| `DataTestMethod`, `STATestMethod`, or `UITestMethod` display-name constructor | `displayName` constructor removed | Set the `DisplayName` property instead (3.13) |
| `ITestMethod.Invoke` or `GetAllAttributes(..., inherit)` | TestFramework interface changed | Use `InvokeAsync`; remove the `inherit` argument because inherited attributes are always included (3.14) |
| Removed `TestContext.TestDir`, `TestDeploymentDir`, `TestLogsDir`, or `ManagedMethod` | Deprecated properties removed | Use the appropriate replacement in 3.15 |
| `ClassCleanupExecutionAttribute`, runsettings `ClassCleanupLifecycle`, or JSON `classCleanupLifecycle` | Assembly attribute and settings removed | Remove the attribute/settings; v4 always uses end-of-class cleanup (3.16) |
| `StringAssert` message and comparison arguments, or renamed named arguments | Assertion signatures changed | Reorder `StringComparison` before `message`; update renamed parameters (3.17) |
| `Assert.ReplaceNullChars`, `ExpectedExceptionBaseAttribute`, `TestIdGenerationStrategy`, CSS attributes, or `InternalTestFailureException` | API/type removed | Remove or replace the usage as described in 3.17 |
| Assembly-name or executor-URI lookup fails | MSTest assemblies and executor URI renamed | Update references to the v4 names and `executor://MSTestAdapter/v4` (3.18) |
| `ITestDataSourceUnfoldingCapability` or custom `IgnoreMessage` override | Interface removed / property no longer virtual | Set `UnfoldingStrategy` on `TestMethodAttribute`; set `IgnoreMessage` without overriding (3.19) |

> **Important**: Scan the entire project for ALL patterns above before starting fixes. Multiple breaking changes often coexist in the same project.

Before applying a matching fix, read the relevant numbered section in the
[breaking-change reference](references/mstest-v3-to-v4-breaking-changes.md).
Resolve this path relative to this `SKILL.md`, not the user's project. If it is
missing, list the known `references` directory at most once and report the
missing guidance rather than silently proceeding with reduced coverage.

For custom test-method attributes, update both `ExecuteAsync` and caller-info
propagation (3.1-3.2), preserving the existing retry and result semantics.
Do not replace a retry implementation with a pass-through call to the base method.

For display names, replace positional strings with the named property:

```csharp
[TestMethod(DisplayName = "custom name")]
```

### Step 4: Address behavioral changes

These changes won't cause build errors but may affect test runtime behavior.

| Symptom | Cause | Fix |
|---|---|---|
| Tests show as new in Azure DevOps / test history lost | `TestCase.Id` generation changed (4.3) | No code fix; history will re-baseline |
| `TestContext.TestName` throws in `[ClassInitialize]` | v4 enforces lifecycle scope (4.2) | Move access to `[TestInitialize]` or test methods |
| Tests not discovered / discovery failures | `TreatDiscoveryWarningsAsErrors` now true (4.4) | Fix warnings, or set to false in .runsettings |
| .NET Framework tests hang under MTP | AppDomain unloading no longer aborts foreground threads by default (4.1) | Stop lingering threads, or enable required isolation with `DisableAppDomain = false` under .runsettings `RunConfiguration` |
| vstest.console can't find tests with MSTest.Sdk after the v4 upgrade | MSTest.Sdk defaults to MTP; v4 stopped adding `Microsoft.NET.Test.Sdk` in MTP mode (4.5) | Add an explicit package while preserving MTP, set `UseVSTest`, or switch CI to `dotnet test` |
| New warnings from analyzers | Analyzer severities upgraded (4.6) | Fix warnings or suppress in .editorconfig |
| Discovery fails with `ReflectionTypeLoadException` | v4 fails discovery when any types in the test assembly cannot load | Fix the underlying loader error, often a missing or mismatched dependency (4.7) |
| A custom inherited data-source attribute now applies to overrides | v4 always includes inherited attributes | Set `Inherited = false` in the custom attribute's `AttributeUsage` if that is not intended (4.8) |
| Custom data rows have a different display name | A null `ITestDataSource.GetDisplayName` result now falls back to a name containing row arguments | Return an explicit display name if the old method-name fallback is required (4.9) |

Read the [breaking-change reference](references/mstest-v3-to-v4-breaking-changes.md) for the relevant runtime
configuration, discovery, attribute-inheritance, and custom data-source details.

### Step 5: Verify

1. Run `dotnet build` -- confirm zero errors and review any new warnings
2. Run `dotnet test` -- confirm all tests pass
3. Compare test results (pass/fail counts) to the pre-migration baseline
4. If using Azure DevOps test tracking, be aware that `TestCase.Id` changes may affect history continuity
5. Check that no tests were silently dropped due to stricter discovery
6. Check custom data-source inheritance and display-name behavior, and ensure the new discovery failure mode does not hide a loader error

## Validation

- [ ] All MSTest packages updated to 4.x
- [ ] Project builds with zero errors
- [ ] All tests pass with `dotnet test`
- [ ] Custom `TestMethodAttribute` subclasses updated for `ExecuteAsync` and CallerInfo
- [ ] `ExpectedExceptionAttribute` replaced with `Assert.ThrowsExactly`
- [ ] `Assert.ThrowsException` replaced with `Assert.ThrowsExactly` (or `Assert.Throws`)
- [ ] `ClassCleanupBehavior` enum usages removed
- [ ] `TestContext.Properties.Contains` updated to `ContainsKey`
- [ ] Removed `TestContext` properties replaced with the correct directory/name property
- [ ] TestFramework `ITestMethod` callers use `InvokeAsync` and updated attribute lookup signatures
- [ ] Removed cleanup attributes/settings, assertion APIs, and custom data-source interfaces addressed
- [ ] Assembly names, executor URI, and adapter target compatibility checked where referenced
- [ ] All target frameworks are net8.0+, net9.0, net462+, uap10.0.16299, or WinUI
- [ ] Behavioral changes reviewed and addressed
- [ ] Discovery loader failures, inherited custom attributes, and custom data-source names reviewed
- [ ] No tests were lost during migration (compare test counts)

## Related Skills

- `writing-mstest-tests` -- for modern MSTest v4 assertion APIs and test authoring best practices
- `run-tests` -- for running tests after migration

## Common Pitfalls

| Pitfall | Solution |
|---------|----------|
| Custom `TestMethodAttribute` still overrides `Execute` | Change to `ExecuteAsync` returning `Task<TestResult[]>` |
| `TestMethodAttribute("display name")` is silently ignored | Use `TestMethodAttribute(DisplayName = "display name")` |
| `ClassCleanupBehavior` enum not found | Remove the enum argument; `[ClassCleanup]` now always runs at end of class. For end-of-assembly cleanup, use `[AssemblyCleanup]` |
| `TestContext.Properties.Contains` missing | Use `ContainsKey` -- `Properties` is now `IDictionary<string, object>` |
| `ExpectedException` attribute not found | Replace with `Assert.ThrowsExactly<T>(() => ...)` inside the test body |
| `Assert.ThrowsException` not found | Replace with `Assert.ThrowsExactly` (or `Assert.Throws` for derived types) |
| `Assert.AreEqual` with format string args fails | Use string interpolation: `$"message {value}"` |
| `TestContext.TestDeploymentDir` or `TestContext.ManagedMethod` is missing | Use `DeploymentDirectory` or `TestName`; verify that the replacement preserves the required semantics |
| `ITestMethod.Invoke` is missing | Use `InvokeAsync`; update attribute lookup calls to omit the `inherit` parameter |
| `vstest.console` or assembly lookup stops matching after upgrade | Update renamed assembly references and the executor URI to v4 |
| Custom `ITestDataSource` now applies to an override | Set `Inherited = false` in the attribute's `AttributeUsage` if inheritance is not intended |
| Discovery fails after a loader warning in v3 | Resolve the `ReflectionTypeLoadException`, commonly by fixing a missing or mismatched dependency |
| A custom data-source test gets a different display name | Return a non-null name from `GetDisplayName` when row arguments should not appear |
| .NET Framework tests hang under MTP | Stop lingering foreground threads or enable required AppDomain isolation; this default change is specific to MTP |
| Azure DevOps test history breaks | Expected -- `TestCase.Id` generation changed; no code fix, results will re-baseline |
| Discovery warnings now fail the run | `TreatDiscoveryWarningsAsErrors` is true by default; fix the discovery warnings |
| Net6.0/net7.0 targets don't compile | Update to net8.0 -- MSTest v4 supports net8.0, net9.0, net462, uap10.0.16299, modern UWP, and WinUI |
references/
mstest-v3-to-v4-breaking-changes.md 25.1 KB
# MSTest v3 to v4 breaking-change details

Use this reference when a migration matches one of the source-breaking or runtime-behavior changes listed in the parent skill. Apply the specific replacement to the user's actual code and verify the resulting project; examples here are patterns, not substitutes for inspecting the project.

Source: [MSTest v3-to-v4 migration guide](https://learn.microsoft.com/dotnet/core/testing/unit-testing-mstest-migration-v3-v4),
incorporating dotnet/docs#56941 at revision `897da0c7f276f12b184beadf4b7d758eb2eff699`.

## Source-breaking changes

### 3.1 TestMethodAttribute.Execute -> ExecuteAsync

If you have custom `TestMethodAttribute` subclasses that override `Execute`, change to `ExecuteAsync`. This change was made because the v3 synchronous `Execute` API caused deadlocks when test code used `async`/`await` internally -- the synchronous wrapper would block the thread while the async operation needed that same thread to complete.

```csharp
// Before (v3)
public sealed class MyTestMethodAttribute : TestMethodAttribute
{
    public override TestResult[] Execute(ITestMethod testMethod)
    {
        // custom logic
        return result;
    }
}

// After (v4) -- Option A: wrap synchronous logic with Task.FromResult
public sealed class MyTestMethodAttribute : TestMethodAttribute
{
    public override Task<TestResult[]> ExecuteAsync(ITestMethod testMethod)
    {
        // custom logic (synchronous)
        return Task.FromResult(result);
    }
}

// After (v4) -- Option B: make properly async
public sealed class MyTestMethodAttribute : TestMethodAttribute
{
    public override async Task<TestResult[]> ExecuteAsync(ITestMethod testMethod)
    {
        // custom async logic
        return await base.ExecuteAsync(testMethod);
    }
}
```

Use `Task.FromResult` when your override logic is purely synchronous. Use `async`/`await` when you call `base.ExecuteAsync` or other async methods.

### 3.2 TestMethodAttribute CallerInfo constructor

`TestMethodAttribute` now uses `[CallerFilePath]` and `[CallerLineNumber]` parameters in its constructor.

**If you inherit from TestMethodAttribute**, propagate caller info to the base class:

```csharp
public class MyTestMethodAttribute : TestMethodAttribute
{
    public MyTestMethodAttribute(
        [CallerFilePath] string callerFilePath = "",
        [CallerLineNumber] int callerLineNumber = -1)
        : base(callerFilePath, callerLineNumber)
    {
    }
}
```

If the subclass has its own display-name constructor, do not pass that string to
the v4 base constructor. Propagate only caller information and assign the
`DisplayName` property:

```csharp
public sealed class NamedTestMethodAttribute : TestMethodAttribute
{
    public NamedTestMethodAttribute(
        string displayName,
        [CallerFilePath] string callerFilePath = "",
        [CallerLineNumber] int callerLineNumber = -1)
        : base(callerFilePath, callerLineNumber)
    {
        DisplayName = displayName;
    }
}
```

**If you use `[TestMethodAttribute("Custom display name")]`**, switch to the named parameter syntax:

```csharp
// Before (v3)
[TestMethodAttribute("Custom display name")]

// After (v4)
[TestMethodAttribute(DisplayName = "Custom display name")]
```

### 3.3 ClassCleanupBehavior enum removed

The `ClassCleanupBehavior` enum is removed. In v3, this enum controlled whether class cleanup ran at end of class (`EndOfClass`) or end of assembly (`EndOfAssembly`). In v4, class cleanup always runs at end of class. Remove the enum argument:

```csharp
// Before (v3)
[ClassCleanup(ClassCleanupBehavior.EndOfClass)]
public static void ClassCleanup(TestContext testContext) { }

// After (v4)
[ClassCleanup]
public static void ClassCleanup(TestContext testContext) { }
```

If you previously used `ClassCleanupBehavior.EndOfAssembly`, move that cleanup logic to an `[AssemblyCleanup]` method instead.

### 3.4 TestContext.Properties type change

`TestContext.Properties` changed from `IDictionary` to `IDictionary<string, object>`. Update any `Contains` calls to `ContainsKey`:

```csharp
// Before (v3)
testContext.Properties.Contains("key");

// After (v4)
testContext.Properties.ContainsKey("key");
```

### 3.5 TestTimeout enum removed

The `TestTimeout` enum (with only `TestTimeout.Infinite`) is removed. Replace with `int.MaxValue`:

```csharp
// Before (v3)
[Timeout(TestTimeout.Infinite)]

// After (v4)
[Timeout(int.MaxValue)]
```

### 3.6 TestContext.ManagedType removed

The `TestContext.ManagedType` property is removed. Use `TestContext.FullyQualifiedTestClassName` instead.

### 3.7 Assert API signature changes

- **Message + params removed**: Assert methods that accepted both `message` and `object[]` parameters now accept only `message`. Use string interpolation instead of format strings:

```csharp
// Before (v3)
Assert.AreEqual(expected, actual, "Expected {0} but got {1}", expected, actual);

// After (v4)
Assert.AreEqual(expected, actual, $"Expected {expected} but got {actual}");
```

- **Assert.ThrowsException renamed**: The `Assert.ThrowsException` APIs are renamed. Use `Assert.ThrowsExactly` (strict type match) or `Assert.Throws` (accepts derived exception types):

```csharp
// Before (v3)
Assert.ThrowsException<InvalidOperationException>(() => DoSomething());

// After (v4) -- exact type match (same behavior as old ThrowsException)
Assert.ThrowsExactly<InvalidOperationException>(() => DoSomething());

// After (v4) -- also catches derived exception types
Assert.Throws<InvalidOperationException>(() => DoSomething());
```

- **Assert.IsInstanceOfType out parameter changed**: `Assert.IsInstanceOfType<T>(x, out var t)` changes to `var t = Assert.IsInstanceOfType<T>(x)`:

```csharp
// Before (v3)
Assert.IsInstanceOfType<MyType>(obj, out var typed);

// After (v4)
var typed = Assert.IsInstanceOfType<MyType>(obj);
```

Apply this assignment rewrite to every occurrence, preserving the concrete asserted type and all
later uses of the typed variable. When source is available, show or edit the actual method rather
than substituting a generic `MyType` example, then verify that the project compiles.

- **Assert.AreEqual for IEquatable\<T\> removed**: If you get generic type inference errors, explicitly specify the type argument as `object`.

### 3.8 ExpectedExceptionAttribute removed

The `[ExpectedException]` attribute is removed in v4. In MSTest 3.2, the `MSTEST0006` analyzer was introduced to flag `[ExpectedException]` usage and suggest migrating to `Assert.ThrowsExactly` while still on v3 (a non-breaking change). In v4, the attribute is gone entirely. Migrate to `Assert.ThrowsExactly`:

```csharp
// Before (v3)
[ExpectedException(typeof(InvalidOperationException))]
[TestMethod]
public void TestMethod()
{
    MyCall();
}

// After (v4)
[TestMethod]
public void TestMethod()
{
    Assert.ThrowsExactly<InvalidOperationException>(() => MyCall());
}
```

**When the test has setup code before the throwing call**, wrap only the throwing call in the lambda -- keep Arrange/Act separation clear:

```csharp
// Before (v3)
[ExpectedException(typeof(ArgumentNullException))]
[TestMethod]
public void Validate_NullInput_Throws()
{
    var service = new ValidationService();
    service.Validate(null);  // throws here
}

// After (v4)
[TestMethod]
public void Validate_NullInput_Throws()
{
    var service = new ValidationService();
    Assert.ThrowsExactly<ArgumentNullException>(() => service.Validate(null));
}
```

**For async test methods**, use `Assert.ThrowsExactlyAsync`:

```csharp
// Before (v3)
[ExpectedException(typeof(HttpRequestException))]
[TestMethod]
public async Task FetchData_BadUrl_Throws()
{
    await client.GetAsync("https://localhost:0");
}

// After (v4)
[TestMethod]
public async Task FetchData_BadUrl_Throws()
{
    await Assert.ThrowsExactlyAsync<HttpRequestException>(
        () => client.GetAsync("https://localhost:0"));
}
```

**If `[ExpectedException]` used the `AllowDerivedTypes` property**, use `Assert.ThrowsAsync<T>` (base type matching) instead of `Assert.ThrowsExactlyAsync<T>` (exact type matching).

For a focused migration, convert every attributed method in the supplied source, wrap only the
statement expected to throw, preserve arrange/setup statements outside the lambda, and run the
affected tests. A prose-only API substitution is incomplete when editable project files are present.

### 3.9 Dropped target frameworks

MSTest v4 supports **.NET 8 and later** and **.NET Framework 4.6.2 and later**. Platform-specific supported targets also include **uap10.0.16299** (UWP), with modern UWP and WinUI using their corresponding supported Windows-specific .NET TFMs. .NET Core 3.1 through .NET 7 are dropped.

If the test project targets an unsupported framework, update `TargetFramework`:

```xml
<!-- Before -->
<TargetFramework>net6.0</TargetFramework>

<!-- After -->
<TargetFramework>net8.0</TargetFramework>
```

### 3.10 Unfolding strategy moved to TestMethodAttribute

The `UnfoldingStrategy` property (introduced in MSTest 3.7) has moved from individual data source attributes (`DataRowAttribute`, `DynamicDataAttribute`) to `TestMethodAttribute`.

### 3.11 ConditionBaseAttribute.ShouldRun renamed

The `ConditionBaseAttribute.ShouldRun` property is renamed to `IsConditionMet`.

### 3.12 Internal/removed types

Several types previously public are now internal or removed:

- `MSTestDiscoverer`, `MSTestExecutor`, `AssemblyResolver`, `LogMessageListener`
- `TestExecutionManager`, `TestMethodInfo`, `TestResultExtensions`
- `UnitTestOutcomeExtensions`, `GenericParameterHelper`
- `ITestMethod` in the PlatformServices assembly is now internal. The separate
  TestFramework `ITestMethod` remains public but has API changes; see 3.14.

If your code references any of these, find alternative approaches or remove the dependency.

### 3.13 Test-method attribute display names

The constructors that accept a display name are removed from
`DataTestMethodAttribute`, `STATestMethodAttribute`, and `UITestMethodAttribute`.
Set `DisplayName` instead. For example, change
`[DataTestMethod("custom name")]` to `[DataTestMethod(DisplayName = "custom name")]`.
The same applies to the STA and UI attributes.

The `TestMethodAttribute` caller-info constructor has a subtle failure mode:
`[TestMethod("custom name")]` still compiles because the string binds to
`callerFilePath`, but it is then ignored as a display name. Always use
`[TestMethod(DisplayName = "custom name")]`. When deriving custom attributes,
propagate `[CallerFilePath]` and `[CallerLineNumber]` to the base constructor.
`UITestMethodAttribute` overrides `ExecuteAsync` instead of `Execute`; update
subclasses accordingly. MSTEST0056 and MSTEST0057 include code fixes for these
constructor migration problems.

### 3.14 TestFramework ITestMethod changes

The `Microsoft.VisualStudio.TestTools.UnitTesting.ITestMethod` interface in
TestFramework changed: `Invoke` was removed in favor of `InvokeAsync`, and the
`inherit` parameter was removed from `GetAllAttributes` and
`GetAttributes<TAttributeType>`. MSTest now always includes inherited
attributes; see 4.8 for how custom attributes can opt out. Do not confuse this
interface with the separate PlatformServices `ITestMethod`, which was made
internal.

### 3.15 TestContext property replacements

The deprecated `TestContext` properties were removed. Choose the replacement
that matches what the old path represented:

| Removed property | Replacement |
|------------------|-------------|
| `TestContext.TestDir` | `TestContext.TestRunDirectory` |
| `TestContext.TestDeploymentDir` | `TestContext.DeploymentDirectory` |
| `TestContext.TestLogsDir` | `TestContext.TestRunResultsDirectory` for run-level result files, or `TestContext.TestResultsDirectory` for test-specific result files |
| `TestContext.ManagedType` | `TestContext.FullyQualifiedTestClassName` |
| `TestContext.ManagedMethod` | `TestContext.TestName` |

`TestName` contains only the method name; `ManagedMethod` also included generic
arity and parameter types. `FullyQualifiedTestClassName` and `TestName` are
non-nullable in v4, but remain subject to the lifecycle restrictions in 4.2.

### 3.16 Class-cleanup settings removed

In addition to `ClassCleanupBehavior`, v4 removes the assembly-level
`ClassCleanupExecutionAttribute`. Remove usages such as
`[assembly: ClassCleanupExecution(...)]`; they no longer compile.

MSTest v4 also no longer reads `ClassCleanupLifecycle` from runsettings or
`classCleanupLifecycle` from the `mstest` section of `testconfig.json`.
Remove these settings; they have no effect in v4. Class cleanup always runs
at the end of each class. If cleanup must run once after the whole assembly,
move that work to `[AssemblyCleanup]`.

### 3.17 Other assertion and API removals

- The `StringAssert.Contains`, `StartsWith`, and `EndsWith` overloads that take
  both `message` and `StringComparison` now take `StringComparison` first.
  For example, change `StringAssert.Contains(value, part, "message",
  StringComparison.Ordinal)` to
  `StringAssert.Contains(value, part, StringComparison.Ordinal, "message")`.
- Named-argument callers must update renamed parameters: `expected` becomes
  `notExpected` in `Assert.DoesNotContain` and `CollectionAssert.AreNotEquivalent`;
  `substring` becomes `expectedPrefix`/`expectedSuffix` in `Assert.StartsWith`/
  `EndsWith`, and `notExpectedPrefix`/`notExpectedSuffix` in
  `DoesNotStartWith`/`DoesNotEndWith`.
- `Assert.ReplaceNullChars` is removed. Remove the call or implement the
  required transformation in application code.
- `ExpectedExceptionBaseAttribute` is removed along with
  `ExpectedExceptionAttribute`. Replace custom derived attributes with
  `Assert.Throws`, `Assert.ThrowsExactly`, or async counterparts inside tests.
- `TestIdGenerationStrategy`, `TestIdGenerationStrategyAttribute`, and
  `DataRowAttribute.TestIdGenerationStrategy` are removed. Remove attempts to
  configure test IDs; see 4.3 for the resulting ID/history behavior.
- `CssIterationAttribute` and `CssProjectStructureAttribute` are removed;
  remove them from tests. `InternalTestFailureException` is also removed; use
  another appropriate exception type.

### 3.18 Assembly, executor, and adapter compatibility

MSTest assemblies were renamed to match their package names. Their namespaces
did not change:

| v3 assembly | v4 assembly |
|-------------|-------------|
| `Microsoft.VisualStudio.TestPlatform.TestFramework.dll` | `MSTest.TestFramework.dll` |
| `Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll` | `MSTest.TestFramework.Extensions.dll` |
| `Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.dll` | `MSTest.TestAdapter.dll` |
| `Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.dll` | `MSTestAdapter.PlatformServices.dll` |

The assembly version is no longer fixed at `14.0.0.0`, and the executor URI
changed from `executor://MSTestAdapter/v2` to `executor://MSTestAdapter/v4`.
Update binding redirects, assembly-qualified type names, code coverage filters,
and any tools that match assembly names, versions, or executor URIs.

`MSTest.TestAdapter` no longer ships a `netstandard2.0` build. The
`MSTest.TestFramework` package still targets `netstandard2.0`; do not infer
that the framework package was dropped along with the adapter asset.

### 3.19 Other extension API changes

- `ITestDataSourceUnfoldingCapability` is removed. Remove its implementation
  from custom data sources and set `UnfoldingStrategy` on `TestMethodAttribute`.
- `ConditionBaseAttribute.IgnoreMessage` is no longer virtual. Remove
  overrides and set the property directly, such as in the custom attribute's
  constructor.

## Runtime behavior changes

### 4.1 DisableAppDomain defaults to true under MTP

When running with Microsoft.Testing.Platform (MTP), MSTest v4 disables
AppDomain isolation by default. This is relevant to .NET Framework; do not
infer the runner from `dotnet test` alone or apply this MTP default to VSTest.
If AppDomain isolation is required, explicitly enable it via `.runsettings`:

```xml
<RunSettings>
  <RunConfiguration>
    <DisableAppDomain>false</DisableAppDomain>
  </RunConfiguration>
</RunSettings>
```

MSTest v4 reads `DisableAppDomain` only from
`RunSettings/RunConfiguration/DisableAppDomain`; v3 used the first element with
that name anywhere in the file. Move misplaced elements under `RunConfiguration`.
The equivalent `testconfig.json` setting is:

```json
{
  "mstest": {
    "execution": {
      "disableAppDomain": false
    }
  }
}
```

AppDomain unloading aborts its threads, including foreground threads. A
foreground thread that ran forever but was terminated by unloading in v3 can
therefore keep an MTP run alive in v4. Stop such threads as part of test cleanup;
enable AppDomain isolation only when the scenario requires it.

### 4.2 TestContext throws when used incorrectly

MSTest v4 now throws when accessing test-specific properties in the wrong lifecycle stage:

- `TestContext.FullyQualifiedTestClassName` -- cannot be accessed in `[AssemblyInitialize]`
- `TestContext.TestName` -- cannot be accessed in `[AssemblyInitialize]` or `[ClassInitialize]`

**Fix**: Move any code that accesses `TestContext.TestName` from `[ClassInitialize]` to `[TestInitialize]` or individual test methods, where per-test context is available. Do not replace `TestName` with `FullyQualifiedTestClassName` as a workaround -- they have different semantics.

### 4.3 TestCase.Id generation changed

The generation algorithm for `TestCase.Id` has changed to fix long-standing bugs. This may affect Azure DevOps test result tracking (e.g., test failure tracking over time). There is no code fix needed, but be aware of test result history discontinuity.

### 4.4 TreatDiscoveryWarningsAsErrors defaults to true

v4 uses stricter defaults. Discovery warnings are now treated as errors, which means tests that previously ran despite discovery issues may now fail entirely. If you see unexpected test failures after upgrading (not build errors, but tests not being discovered), check for discovery warnings. To restore v3 behavior while you investigate:

```xml
<RunSettings>
  <MSTest>
    <TreatDiscoveryWarningsAsErrors>false</TreatDiscoveryWarningsAsErrors>
  </MSTest>
</RunSettings>
```

> **Recommended**: Fix the underlying discovery warnings rather than suppressing this setting.

### 4.5 MSTest.Sdk and vstest.console compatibility

MSTest.Sdk defaults to Microsoft.Testing.Platform (MTP) mode. MSTest.Sdk v3
still added `Microsoft.NET.Test.Sdk` in that mode; v4 removes the unnecessary
reference. A CI pipeline that separately invokes `vstest.console` can therefore
drop to zero discovered tests immediately after the v4 upgrade.

**Option A -- Preserve MTP and transitional VSTest discovery**: Add the exact
compatible `Microsoft.NET.Test.Sdk` package explicitly. This is the least
disruptive fix when MTP remains the primary runner but an existing
`vstest.console` job cannot be removed yet:

Use a direct `PackageReference` with the exact compatible version resolved from
the configured feed. Under Central Package Management, add or update the
`Microsoft.NET.Test.Sdk` `PackageVersion` in `Directory.Packages.props` and keep
the project reference versionless. Do not copy a fixed example version.

Verify with the actual `vstest.console` command; a passing `dotnet test` MTP run
does not prove VSTest discovery.

**Option B -- Switch the project to VSTest mode**: Set the `UseVSTest` property.
MSTest.Sdk then adds `Microsoft.NET.Test.Sdk`:

```xml
<PropertyGroup>
  <UseVSTest>true</UseVSTest>
</PropertyGroup>
```

Keep the resolved exact `MSTest.Sdk` v4 pin from Step 2; this option changes the runner, not the
selected MSTest version or target framework.

**Option C -- Switch CI to `dotnet test`**: Replace `vstest.console` invocations
only after configuring the SDK's MTP integration. Choose the mode from the
repository/CI SDK version, not the test project's target framework:

- **.NET 8/9 SDKs**: Ensure the effective property below is set for the test
  project (in its project file or applicable `Directory.Build.props`):

  ```xml
  <PropertyGroup>
    <TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
  </PropertyGroup>
  ```

  Keep build arguments before `--` and pass MTP arguments after it.
- **.NET 10+ SDK**: Before changing `global.json`, inventory every `dotnet test`
  invocation governed by that file, including solution-level CI commands.
  Check every affected test project and target framework for MTP support,
  including the effective `UseVSTest` value after conditional/imported properties
  are evaluated. Native MTP cannot run VSTest-only projects; an `MSTest.Sdk`
  project with effective `UseVSTest=true` is not ready for this mode.

  Only when the affected test projects and target frameworks all support MTP,
  merge this `test` section into `global.json`, preserving existing SDK pins and
  other settings:

  ```json
  {
    "test": {
      "runner": "Microsoft.Testing.Platform"
    }
  }
  ```

  Pass MTP arguments directly, without `--`; the compatibility property above
  is not needed in this mode.

If any affected project or target framework must remain on VSTest, keep Option A
or B for that CI path instead of changing its shared `global.json`. Alternatively,
use a separately scoped `global.json` and CI invocation that selects only
MTP-compatible projects/target frameworks. Run that invocation from the intended
configuration's working directory; passing `--project` alone does not select a
different `global.json`. Keep the VSTest jobs in their original scope, and verify
both paths rather than dropping incompatible projects from CI.

Without the matching integration configuration, `dotnet test` may still use
VSTest and fail to discover the tests. Translate the existing CI arguments
rather than dropping filters, settings, or result publishing:

| Existing VSTest argument | MSTest on MTP |
|---|---|
| `/TestCaseFilter:<expression>` or `--filter <expression>` | `--filter <expression>`; preserve the MSTest filter expression unchanged |
| `/Logger:trx` or `--logger trx` | `--report-trx`; requires `Microsoft.Testing.Extensions.TrxReport` |
| TRX logger's `LogFileName=<name>` | `--report-trx-filename <name>`; retain unique filenames per project/TFM when sharing a results directory |
| `/ResultsDirectory:<dir>` or `--results-directory <dir>` | `--results-directory <dir>`; preserve the directory consumed by CI artifact publishing |
| `/Settings:<file>` or `--settings <file>` | `--settings <file>`; MSTest still supports `.runsettings` |
| `/ListTests` or `--list-tests` | `--list-tests` |
| `--collect "Code Coverage;Format=cobertura"` | `--coverage --coverage-output-format cobertura`; requires `Microsoft.Testing.Extensions.CodeCoverage` |
| `--blame-crash` | `--crashdump`; requires `Microsoft.Testing.Extensions.CrashDump` |
| `--blame-hang` | `--hangdump`; requires `Microsoft.Testing.Extensions.HangDump` |

Ensure each required extension is included by the `MSTest.Sdk` profile or an
explicit compatible package reference, following the exact-version and Central
Package Management rules above. Preserve existing build arguments such as
`--configuration` and `--framework`. For any other VSTest option or logger
parameter, confirm its replacement with the MTP test application's `--help`;
do not silently discard unsupported CI behavior.

For example, after configuring the selected mode and TRX extension:

```shell
# .NET 8/9 SDKs
dotnet test --configuration Release -- --filter "TestCategory=Smoke" --report-trx --results-directory TestResults

# .NET 10+ SDK in native MTP mode
dotnet test --configuration Release --filter "TestCategory=Smoke" --report-trx --results-directory TestResults
```

Run the actual translated CI command, compare selected test counts with the
baseline, and verify that the expected TRX/coverage/dump artifacts exist where
CI publishes them. A zero-test run is not proof of a successful migration.

Do not say this behavior predates v4: removal of the transitive
`Microsoft.NET.Test.Sdk` reference in MTP mode is one of the v4 behavioral
breaking changes.

### 4.6 Analyzer severity changes

Multiple analyzers have been upgraded from Info to Warning by default:

- MSTEST0001, MSTEST0007, MSTEST0017, MSTEST0023, MSTEST0024, MSTEST0025
- MSTEST0030, MSTEST0031, MSTEST0032, MSTEST0035, MSTEST0037, MSTEST0045

Review and fix any new warnings, or suppress them in `.editorconfig` if intentional.

### 4.7 Discovery fails when test-assembly types cannot load

In v3, a `ReflectionTypeLoadException` during discovery produced a warning and
MSTest continued with the types that loaded. In v4, discovery of that assembly
fails. When there is one loader exception, MSTest reports it directly. Fix the
underlying load failure, commonly a missing or mismatched dependency, rather
than treating the change as a test-discovery setting.

### 4.8 Inherited attributes are always read

MSTest v4 always includes inherited attributes in lookups, including custom
`ITestDataSource` attributes applied to an overridden method. Built-in
attributes that should not inherit declare `Inherited = false`. If a custom
attribute should not apply to derived classes or overrides, add
`Inherited = false` to its `AttributeUsage`.

### 4.9 Default display name for custom data sources

If a custom `ITestDataSource.GetDisplayName` returns `null`, v4 generates a
default display name that includes the data-row arguments. V3 used the test
method's display name instead. Return an explicit name from custom data sources
when the desired display name should not include row arguments.

License (MIT)

View full license text
The MIT License (MIT)

Copyright (c) .NET Foundation and Contributors

All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.