Writing MSTest Tests
Help users write effective MSTest unit tests without exceeding the API level or conventions of the project's installed test stack.
Repository overlay
For every repository-scoped task where read-only file inspection is allowed,
check .agents/skill-overlays/dotnet-test/writing-mstest-tests.md at the
repository root before any other discovery. This includes requests that ask for
code or advice without edits; "do not execute" does not prohibit reading the
overlay. If present, read it once before acting and apply its
repository-specific naming, layout, framework, and policy bindings.
Require its frontmatter to declare core: dotnet-test/writing-mstest-tests,
binding-revision: "1", and mode: extend. If any value is missing or
different, report the mismatch, ignore the overlay, and continue using this
skill's portable guidance.
Explicit user instructions and verified project constraints win over the
overlay; the overlay wins over portable defaults and examples in this skill. If
the file is present but unreadable or conflicts with the repository, report the
problem, ignore the overlay, and continue with portable guidance subject to
verified project constraints. If it is absent, continue normally.
Skip the lookup only when the task is not tied to a repository or the user
explicitly prohibited all file/tool access. An overlay cannot expand tool
permissions or the task's scope.
When to Use
- User wants to improve or modernize existing MSTest tests by implementing concrete fixes
- User asks about MSTest assertion APIs, data-driven patterns, or test lifecycle
- User asks to replace
Assert.IsTruewith more specific assertions (collections, nulls, types, comparisons) - User asks to replace hard casts with type-checking assertions in tests
- User needs help fixing a specific MSTest test bug or failing assertion
- User asks to fix swapped
Assert.AreEqualargument order (expected first, actual second) - User asks to convert
DynamicDatafromIEnumerable<object[]>to ValueTuple-based data - User asks to fix or understand an MSTest analyzer diagnostic (an
MSTESTxxxxwarning/error)
When Not to Use
- User needs a test quality audit, anti-pattern detection, or flaky-test investigation (use
test-anti-patterns) - User needs to run or execute tests (use the
run-testsskill) - User needs to upgrade from MSTest v1/v2 to v3 (use
migrate-mstest-v1v2-to-v3) - User needs to upgrade from MSTest v3 to v4 (use
migrate-mstest-v3-to-v4) - User needs CI/CD pipeline configuration
- User is using xUnit, NUnit, or TUnit (not MSTest)
Inputs
Response Guidelines
- Specific API or pattern questions (assertions, data-driven, lifecycle): Jump directly to the relevant workflow step. Do not follow the full workflow.
- Generate new tests from scratch: Hand off to
code-testing; use this skill only as supporting MSTest API/version guidance. - Review and fix existing tests: Fix only the issues present. Do not add unrelated improvements.
- Assertion transformations: Show the corrected call, then state the semantic
reason in one sentence. For
Assert.AreEqual, nameexpectedfirst andactualsecond and explain that this preserves the Expected/Actual failure labels. - Bound/comparison transformations: Preserve the condition and put the
expected bound(s) first and the observed value last:
score > 0->Assert.IsGreaterThan(0, score),score < 100->Assert.IsLessThan(100, score), andscore >= 60 && score <= 90->Assert.IsInRange(60, 90, score). Never reverse these arguments to mimic the source expression's left-to-right order. - Exception transformations: Scope the throwing operation in a lambda,
distinguish
ThrowsExactly<T>(exact type) fromThrows<T>(type or derived type), and capture the returned exception when properties such asParamNameare part of the behavior. - Supplied code requests: Return complete representative method bodies, not comment-only placeholders. Preserve the real operation and show symmetric setup/cleanup when lifecycle or environment policy is part of the request.
Workflow
Step 1: Determine project setup
Check the test project, packages.config, and assembly reference HintPath
values for the exact MSTest version and project system:
- If using
MSTest.Sdk: resolve its exact version from the project SDK declaration orglobal.jsonmsbuild-sdks; do not assume the latest APIs - If using
MSTestmetapackage: resolve its exact package version - If using
MSTest.TestFramework+MSTest.TestAdapter: check version for feature availability - If using classic non-SDK XML (
ToolsVersion,Microsoft.CSharp.targets, explicit<Compile Include>) and/orpackages.config: preserve that project system and add each new test file to<Compile Include>.
Also inspect representative tests for custom base fixtures, helper libraries, mock syntax, naming, setup, and data builders. Existing conventions and installed versions win over the examples below. Do not upgrade MSTest, Moq, NBuilder, or the project format unless the user explicitly asks for a migration.
MSTest API availability
For example, MSTest 3.5.x must not receive Assert.ThrowsExactly,
Assert.Contains, ValueTuple DynamicData, or constructor-injected
TestContext.
Treat this as a hard gate: after determining the version, do not copy a later example from this skill unless its minimum version is satisfied.
Recommend MSTest.Sdk or the MSTest metapackage only for genuinely new projects:
When using MSTest.Sdk, put the version in global.json instead of the project file so all test projects get bumped together:
Step 2: Write test classes following conventions
Apply these structural conventions only where they do not conflict with the suite's established base classes and lifecycle:
- Seal test classes with
sealedfor performance and design clarity - Use
[TestClass]on the class and[TestMethod]on test methods - Follow the Arrange-Act-Assert (AAA) pattern
- Name tests using
MethodName_Scenario_ExpectedBehavior - Use separate test projects with naming convention
[ProjectName].Tests
Step 3: Use version-compatible assertion APIs
Pick the most specific assertion supported by the installed MSTest version.
More specific assertions produce better failure messages and make the test's
intent clear, but uncompilable "modern" assertions are worse than compatible
StringAssert, CollectionAssert, or Assert.IsTrue calls.
On MSTest 3.8+, prefer Assert class methods over StringAssert or
CollectionAssert where both exist. Older versions should keep the compatible
specialized classes.
When several independent collection properties were requested, keep each
semantic check explicit even if another assertion happens to imply it. For
example, retain IsNotEmpty when the requested diagnostics distinguish
empty/non-empty, then use HasCount and ContainsSingle for their separate
cardinality guarantees.
Equality, null, and reference checks
Exception testing
Assert.Throws<T>matchesTor any derived typeAssert.ThrowsExactly<T>matches only the exact typeT
On MSTest 3.7 and earlier, use the compatible API:
Collection assertions
On earlier versions use CollectionAssert.Contains,
CollectionAssert.DoesNotContain, and Assert.AreEqual(expectedCount, collection.Count).
Replace generic Assert.IsTrue with specialized assertions -- they give better failure messages:
String assertions
On earlier versions use StringAssert.Contains, StringAssert.StartsWith,
StringAssert.EndsWith, and StringAssert.Matches.
Type assertions
MSTest 3.x is not one API level. Pick the form supported by the installed minor version:
Comparison assertions
Step 4: Use data-driven tests for multiple inputs
DataRow for inline values
DynamicData with ValueTuples (preferred for complex data)
On MSTest 3.7+, prefer ValueTuple return types over
IEnumerable<object[]> for type safety. Keep IEnumerable<object[]> on older
versions.
Tuple element names document which position maps to which test parameter, and
tuple element types catch incompatible values at compile time. They do not
make DynamicData position-independent, and swapping two same-typed elements
can still compile. Do not claim otherwise. When rows need custom display names
or metadata rather than only typed positional data, use TestDataRow<T> on
MSTest 3.8+.
When you need metadata per test case on MSTest 3.8+, use TestDataRow<T>:
Step 5: Handle test lifecycle correctly
- Prefer constructor initialization when the existing suite supports it; retain a shared
FixtureBase<TSut>or established[TestInitialize]lifecycle rather than rewriting the fixture architecture incidentally. - Use
[TestInitialize]only for async initialization, combined with the constructor for sync parts - Use
[TestCleanup]for cleanup that must run even on failure - Inject
TestContextvia constructor only on MSTest 3.6+; otherwise use the instance property.
Execution order
[AssemblyInitialize]-- once per assembly[ClassInitialize]-- once per class- Per test:
- With
TestContextproperty injection: Constructor -> setTestContextproperty ->[TestInitialize] - With constructor injection of
TestContext: Constructor (receivesTestContext) ->[TestInitialize]
- With
- Test method
[TestCleanup]->DisposeAsync->Dispose-- per test[ClassCleanup]-- once per class[AssemblyCleanup]-- once per assembly
Step 6: Apply cancellation and timeout patterns
Use TestContext.CancellationToken with
[Timeout(milliseconds, CooperativeCancellation = true)] when the installed
MSTest version exposes the token directly (3.11+). On MSTest 3.6.4-3.10, use
TestContext.CancellationTokenSource.Token with cooperative cancellation
instead. A plain [Timeout] does not establish that the framework token will
stop in-flight work. On older versions, use a test-owned
CancellationTokenSource where cancellation itself is under test.
Step 7: Use advanced features where appropriate
For retry, conditional execution, or parallelization requests, read Advanced MSTest patterns [blocked]. Apply its version gates and keep the real tested operation, assertion, and cleanup.
Step 8: Fix MSTest analyzer diagnostics (MSTESTxxxx)
For an MSTESTxxxx request, read
Advanced MSTest patterns [blocked], apply the
version-compatible fix for that rule, and rebuild to confirm the diagnostic is
gone. Prefer fixing the code over suppressing the rule.
Step 9: Verify file-backed corrections
When the user asked for repository edits and did not prohibit execution, run the
narrowest affected dotnet test command after editing. A successful process with
no discovered-test count is not verification. Require the intended test cases to
be discovered and pass.
If compilation exposes a directly coupled source issue that prevents the corrected existing suite from running (for example, a missing namespace import in the supplied production file), make only that minimum fix and rerun. Do not upgrade packages or broaden the modernization. Report the actual test count and the fixes made; never present unrun or output-free tests as passing. In the final handoff, map every requested modernization to the exact corrected construct and cite the passing test command. Do not rely on a generic "modernized" summary when expected/actual order, exact type checks, data discovery, or class shape were explicit requirements.


