Source profileQuality 97/100

dotnet/skills/plugins/dotnet-test/skills/writing-mstest-tests/SKILL.md

writing-mstest-tests

Fix, modernize, review, or explain supplied MSTest code and MSTest-specific configuration while honoring installed versions and project style. ALWAYS USE for direct corrections: expected/actual order; generic/manual assertions; exception, hard-cast, or object[] patterns; TestContext/lifecycle; timeout/cancellation; condition/retry/cleanup; parallelization; MSTest.Sdk setup; or MSTESTxxxx. Use for "review" only when corrected code or edits are wanted. DO NOT USE for new test-case design (code-tes

Source repository stars
5,248
Declared platforms
0
Static risk flags
0
Last source update
2026-08-26
Source checked
2026-08-26

Decision brief

What it does: where it fits

Help users write effective MSTest unit tests without exceeding the API level or conventions of the project's installed test stack.

Best for

  • 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.IsTrue with more specific assertions (collections, nulls, types, comparisons)

Not for

  • 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-tests skill)

Compatibility matrix

Platform support, with evidence labels

PlatformStatusEvidenceWhat to check
CodexNot declaredNo explicit evidencePortability before use
Claude CodeNot declaredNo explicit evidencePortability before use
CursorNot declaredNo explicit evidencePortability before use
Gemini CLINot declaredNo explicit evidencePortability before use
Open the compatibility checker

Installation

Inspect first. Install second.

The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

Source-detected install commandSource
npx skills add https://github.com/dotnet/skills --skill "plugins/dotnet-test/skills/writing-mstest-tests"
Safe inspection promptEditorial

Inspect the Agent Skill "writing-mstest-tests" from https://github.com/dotnet/skills/blob/1b896e91feb0f613cb54a914f1efd2897810ae02/plugins/dotnet-test/skills/writing-mstest-tests/SKILL.md at commit 1b896e91feb0f613cb54a914f1efd2897810ae02. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

Workflow

What the source asks the agent to do

  1. 01

    Workflow

    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 SDKIf using MSTest metapackage: resolve its exact package versionIf using MSTest.TestFramework + MSTest.TestAdapter: check version for feature availability
  2. 02

    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 SDKIf using MSTest metapackage: resolve its exact package versionIf using MSTest.TestFramework + MSTest.TestAdapter: check version for feature availability
  3. 03

    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 sealed for performance and design clarityUse [TestClass] on the class and [TestMethod] on test methodsFollow the Arrange-Act-Assert (AAA) pattern
  4. 04

    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…

    Assert.Throws matches T or any derived typeAssert.ThrowsExactly matches only the exact type TPick 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…
  5. 05

    Step 4: Use data-driven tests for multiple inputs

    On MSTest 3.7+, prefer ValueTuple return types over IEnumerable for type safety. Keep IEnumerable on older versions.

    On MSTest 3.7+, prefer ValueTuple return types over IEnumerable for type safety. Keep IEnumerable on older versions.When you need metadata per test case on MSTest 3.8+, use TestDataRow:

Permission review

Static risk signals and limitations

No configured static risk pattern was detected

This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.

Evidence record

Why each signal appears

EvidenceSourceComputedTestedEditorial
SignalValueEvidence typeMeaning
Quality score97/100ComputedDocumentation, specificity, maintenance, and trust rules
Repository stars5,248SourceRepository attention, not individual Skill quality
Compatibility0 platformsSourceDeclared in the catalog source record
Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

Pinned source

Provenance and original SKILL.md

Repository
dotnet/skills
Skill path
plugins/dotnet-test/skills/writing-mstest-tests/SKILL.md
Commit
1b896e91feb0f613cb54a914f1efd2897810ae02
License
MIT
Collected
2026-08-26
Default branch
main
View the original SKILL.md

Writing MSTest Tests

Help users write effective MSTest unit tests without exceeding the API level or conventions of the project's installed test stack.

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.IsTrue with 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.AreEqual argument order (expected first, actual second)
  • User asks to convert DynamicData from IEnumerable<object[]> to ValueTuple-based data
  • User asks to fix or understand an MSTest analyzer diagnostic (an MSTESTxxxx warning/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-tests skill)
  • 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

InputRequiredDescription
Code under testNoThe production code to be tested
Existing test codeNoCurrent tests to fix, update, or modernize
Test scenario descriptionNoWhat behavior the user wants to test

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-agent; 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, name expected first and actual second and explain that this preserves the Expected/Actual failure labels.
  • Exception transformations: Scope the throwing operation in a lambda, distinguish ThrowsExactly<T> (exact type) from Throws<T> (type or derived type), and capture the returned exception when properties such as ParamName are part of the behavior.

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 or global.json msbuild-sdks; do not assume the latest APIs
  • If using MSTest metapackage: 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/or packages.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

API/patternMinimum versionCompatible fallback
Assert.ThrowsExactly*, unified Assert.Contains / HasCount / IsEmpty / IsNotEmpty3.8Assert.ThrowsException*, CollectionAssert, StringAssert
Assert.IsGreaterThan, IsLessThan, IsInRange, StartsWith, EndsWith, MatchesRegex3.10Assert.IsTrue with a clear message, or StringAssert
ValueTuple DynamicData3.7IEnumerable<object[]>
Constructor injection of TestContext3.6Instance TestContext property
[Retry], [OSCondition]3.8No built-in retry/OS condition; fix flakiness or retain the existing condition mechanism
[CICondition]3.10Existing project-specific condition mechanism

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:

<!-- Option 1: MSTest SDK (simplest, recommended for new projects) -->
<Project Sdk="MSTest.Sdk">
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
  </PropertyGroup>
</Project>

When using MSTest.Sdk, put the version in global.json instead of the project file so all test projects get bumped together:

{
  "msbuild-sdks": {
    "MSTest.Sdk": "3.8.2"
  }
}
<!-- Option 2: MSTest metapackage -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="MSTest" Version="3.8.2" />
  </ItemGroup>
</Project>

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 sealed for 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
[TestClass]
public sealed class OrderServiceTests
{
    [TestMethod]
    public void CalculateTotal_WithDiscount_ReturnsReducedPrice()
    {
        // Arrange
        var service = new OrderService();
        var order = new Order { Price = 100m, DiscountPercent = 10 };

        // Act
        var total = service.CalculateTotal(order);

        // Assert
        Assert.AreEqual(90m, total);
    }
}

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.

What you are testingAssertion
Two values are equalAssert.AreEqual(expected, actual)
Same object instance (reference identity)Assert.AreSame(expected, actual)
Value is nullAssert.IsNull(value)
Value is not nullAssert.IsNotNull(value)
Collection is emptyAssert.IsEmpty(collection) (3.8+) or CollectionAssert / count assertion
Collection is not emptyAssert.IsNotEmpty(collection) (3.8+) or count assertion
Collection has exactly N itemsAssert.HasCount(N, collection) (3.8+) or Assert.AreEqual on count
Collection contains an itemAssert.Contains(item, collection) (3.8+) or CollectionAssert.Contains
Collection does not contain an itemAssert.DoesNotContain(item, collection) (3.8+) or CollectionAssert.DoesNotContain
Object is a specific typeAssert.IsInstanceOfType<T>(value)
Code throws an exceptionAssert.ThrowsExactly<T> (3.8+) or Assert.ThrowsException<T> (earlier)

On MSTest 3.8+, prefer Assert class methods over StringAssert or CollectionAssert where both exist. Older versions should keep the compatible specialized classes.

Equality, null, and reference checks

Assert.AreEqual(expected, actual);      // Value equality
Assert.AreSame(expected, actual);       // Reference equality -- same object instance
Assert.IsNull(value);
Assert.IsNotNull(value);

Exception testing

// MSTest 3.8+
var ex = Assert.ThrowsExactly<ArgumentNullException>(() => service.Process(null));
Assert.AreEqual("input", ex.ParamName);

// Async
var ex = await Assert.ThrowsExactlyAsync<InvalidOperationException>(
    async () => await service.ProcessAsync(null));
  • Assert.Throws<T> matches T or any derived type
  • Assert.ThrowsExactly<T> matches only the exact type T

On MSTest 3.7 and earlier, use the compatible API:

var ex = Assert.ThrowsException<ArgumentNullException>(
    () => service.Process(null));

Collection assertions

// MSTest 3.8+
Assert.Contains(expectedItem, collection);
Assert.DoesNotContain(unexpectedItem, collection);
var single = Assert.ContainsSingle(collection);  // Returns the single element
Assert.HasCount(3, collection);
Assert.IsEmpty(collection);
Assert.IsNotEmpty(collection);

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:

Instead ofUse
Assert.IsTrue(list.Count > 0)Assert.IsNotEmpty(list)
Assert.IsTrue(list.Count == 0)Assert.IsEmpty(list)
Assert.IsTrue(list.Count() == 3)Assert.HasCount(3, list)
Assert.IsTrue(x != null)Assert.IsNotNull(x)
Assert.IsTrue(x == null)Assert.IsNull(x)
Assert.AreEqual(a, b) for same instanceAssert.AreSame(a, b) -- reference identity
Assert.IsTrue(!list.Contains(item))Assert.DoesNotContain(item, list)
list.Single(predicate) + Assert.IsNotNullAssert.ContainsSingle(list)
Assert.IsTrue(list.Contains(item))Assert.Contains(item, list)

String assertions

// MSTest 3.10+
Assert.Contains("expected", actualString);
Assert.StartsWith("prefix", actualString);
Assert.EndsWith("suffix", actualString);
Assert.MatchesRegex(@"\d{3}-\d{4}", phoneNumber);

On earlier versions use StringAssert.Contains, StringAssert.StartsWith, StringAssert.EndsWith, and StringAssert.Matches.

Type assertions

// MSTest 3.x -- out parameter
Assert.IsInstanceOfType<MyHandler>(result, out var typed);
typed.Handle();

// MSTest 4.x -- returns directly
var typed = Assert.IsInstanceOfType<MyHandler>(result);

Comparison assertions

Assert.IsGreaterThan(lowerBound, actual);
Assert.IsLessThan(upperBound, actual);
Assert.IsInRange(low, high, actual);

Step 4: Use data-driven tests for multiple inputs

DataRow for inline values

[TestMethod]
[DataRow(1, 2, 3)]
[DataRow(0, 0, 0, DisplayName = "Zeros")]
[DataRow(-1, 1, 0)]
public void Add_ReturnsExpectedSum(int a, int b, int expected)
{
    Assert.AreEqual(expected, Calculator.Add(a, b));
}

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.

[TestMethod]
[DynamicData(nameof(DiscountTestData))]
public void ApplyDiscount_ReturnsExpectedPrice(decimal price, int percent, decimal expected)
{
    var result = PriceCalculator.ApplyDiscount(price, percent);
    Assert.AreEqual(expected, result);
}

// ValueTuple -- preferred (MSTest 3.7+)
public static IEnumerable<(decimal price, int percent, decimal expected)> DiscountTestData =>
[
    (100m, 10, 90m),
    (200m, 25, 150m),
    (50m, 0, 50m),
];

When you need metadata per test case on MSTest 3.8+, use TestDataRow<T>:

public static IEnumerable<TestDataRow<(decimal price, int percent, decimal expected)>> DiscountTestDataWithMetadata =>
[
    new((100m, 10, 90m)) { DisplayName = "10% discount" },
    new((200m, 25, 150m)) { DisplayName = "25% discount" },
    new((50m, 0, 50m)) { DisplayName = "No discount" },
];

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 TestContext via constructor only on MSTest 3.6+; otherwise use the instance property.
[TestClass]
public sealed class RepositoryTests
{
    private readonly TestContext _testContext;
    private readonly FakeDatabase _db;  // readonly -- guaranteed by constructor

    public RepositoryTests(TestContext testContext)
    {
        _testContext = testContext;
        _db = new FakeDatabase();  // sync init in ctor
    }

    [TestInitialize]
    public async Task InitAsync()
    {
        // Use TestInitialize ONLY for async setup
        await _db.SeedAsync();
    }

    [TestCleanup]
    public void Cleanup() => _db.Reset();
}

Execution order

  1. [AssemblyInitialize] -- once per assembly
  2. [ClassInitialize] -- once per class
  3. Per test:
    • With TestContext property injection: Constructor -> set TestContext property -> [TestInitialize]
    • With constructor injection of TestContext: Constructor (receives TestContext) -> [TestInitialize]
  4. Test method
  5. [TestCleanup] -> DisposeAsync -> Dispose -- per test
  6. [ClassCleanup] -- once per class
  7. [AssemblyCleanup] -- once per assembly

Step 6: Apply cancellation and timeout patterns

Use TestContext.CancellationToken with [Timeout] only when the installed MSTest version exposes it. On older versions, use a test-owned CancellationTokenSource where cancellation itself is under test.

[TestMethod]
[Timeout(5000)]
public async Task FetchData_ReturnsWithinTimeout()
{
    var result = await _client.GetDataAsync(_testContext.CancellationToken);
    Assert.IsNotNull(result);
}

Step 7: Use advanced features where appropriate

Retry flaky tests (MSTest 3.8+)

Use only for genuinely flaky external dependencies (network, file system), not to paper over race conditions or shared state issues.

[TestMethod]
[Retry(3)]
public void ExternalService_EventuallyResponds() { }

Conditional execution

OSCondition requires MSTest 3.8+; CICondition requires MSTest 3.10+.

[TestMethod]
[OSCondition(OperatingSystems.Windows)]
public void WindowsRegistry_ReadsValue() { }

[TestMethod]
[CICondition(ConditionMode.Exclude)]
public void LocalOnly_InteractiveTest() { }

Parallelization

[assembly: Parallelize(Workers = 4, Scope = ExecutionScope.MethodLevel)]

[TestClass]
[DoNotParallelize]  // Opt out specific classes
public sealed class DatabaseIntegrationTests { }

Step 8: Fix MSTest analyzer diagnostics (MSTESTxxxx)

The MSTest.Analyzers package reports MSTESTxxxx diagnostics during build and in the IDE. The analyzers come in automatically with the modern MSTest metapackage and MSTest.Sdk (and are bundled with MSTest.TestFramework 3.7+); for other setups, reference MSTest.Analyzers explicitly only when the user asks to adopt analyzers. Most rules have an automated code fix (light bulb) in Visual Studio. When fixing one by hand, apply the idiomatic, version-compatible change below rather than suppressing the rule.

When asked to "fix MSTESTxxxx", look it up in the table of common diagnostics below, apply the fix, and rebuild to confirm the diagnostic is gone. The table is not exhaustive — for any rule it does not list, consult the full reference and apply the documented guidance: https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/overview.

Common diagnostics and their fixes

RuleProblemFix
MSTEST0006[ExpectedException] usedOn 3.8+, replace with Assert.Throws<T> / Assert.ThrowsExactly<T>; otherwise use Assert.ThrowsException<T>
MSTEST0017Assert.AreEqual args swappedPut expected first, actual second
MSTEST0023Negated boolean assertion (Assert.IsTrue(!x))Use Assert.IsFalse(x)
MSTEST0025Always-false condition assertedUse Assert.Fail("reason")
MSTEST0032Always-true assert conditionRemove or correct the assertion
MSTEST0037Sub-optimal assert (IsTrue(x == null))Use the specific assert (Assert.IsNull, HasCount, etc.) (Step 3)
MSTEST0038Assert.AreSame on value typesUse Assert.AreEqual (value types box to distinct references)
MSTEST0039Legacy Assert.ThrowsExceptionOn 3.8+, use Assert.Throws / Assert.ThrowsExactly (+ Async variants)
MSTEST0044[DataTestMethod] usedReplace with [TestMethod] only on a version where it supports data rows
MSTEST0046StringAssert usedOn 3.10+, use the equivalent Assert method (Assert.Contains, StartsWith, ...)
MSTEST0052Explicit DynamicDataSourceTypeDrop it — the source type is inferred
MSTEST0042 / MSTEST0060Duplicate [DataRow] / [TestMethod]Remove the duplicate attribute
MSTEST0024Static TestContext fieldMake it an instance member (Step 5)
MSTEST0045 / MSTEST0049 / MSTEST0054Timeout/token not cooperativeFlow TestContext.CancellationToken into the awaited call (Step 6)
MSTEST0036Member shadows a base test memberRename or use override instead of new
MSTEST0061Runtime OS check inside a testUse [OSCondition(...)] (Step 7)
MSTEST0002 / MSTEST0003 / MSTEST0005 / MSTEST0007–0014Invalid test class / method / fixture / TestContext / data-source layoutCorrect the signature named by the rule (e.g. make it public, fix the return type and parameters, add static where required)

Tuning which rules are enforced

Use the MSTestAnalysisMode MSBuild property (MSTest 3.8+) to control the rule set globally:

<PropertyGroup>
  <!-- None | Default | Recommended | All -->
  <MSTestAnalysisMode>Recommended</MSTestAnalysisMode>
</PropertyGroup>
  • Recommended escalates info-level rules to warnings and is the mode most projects should adopt.
  • A handful of rules are completely opt-in (e.g. MSTEST0015, MSTEST0019–0022); enable them per project via .editorconfig when you want their convention enforced.
  • Prefer fixing the underlying code over suppressing a diagnostic. Suppress only with a documented justification.

Frequently asked questions

What to verify before installation and use

What does the writing-mstest-tests source document cover?

Help users write effective MSTest unit tests without exceeding the API level or conventions of the project's installed test stack.

How do I install writing-mstest-tests?

The source record exposes this install command: npx skills add https://github.com/dotnet/skills --skill "plugins/dotnet-test/skills/writing-mstest-tests". Inspect the command and pinned source before running it.

Alternatives

Compare before choosing