{"slug":"writing-mstest-tests","title":"writing-mstest-tests","summary":"Review, modernize, fix, or explain MSTest APIs using the installed version, including classic non-SDK packages.config projects and older MSTest 3.x. ALWAYS USE to \"fix swapped Assert.AreEqual arguments\", \"replace ExpectedException with Assert.Throws/ThrowsExactly\", choose specifi","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-08-24T05:37:35.026977Z","repo":{"url":"https://github.com/dotnet/skills","stars":6296,"forks":500,"license":"MIT","updatedAt":"2026-11-19T18:23:42Z"},"bodyHtml":"<hr>\n<h2>name: writing-mstest-tests\ndescription: &gt;\nReview, modernize, fix, or explain MSTest APIs using the installed version,\nincluding classic non-SDK packages.config projects and older MSTest 3.x.\nALWAYS USE to \"fix swapped Assert.AreEqual arguments\", \"replace\nExpectedException with Assert.Throws/ThrowsExactly\", choose specific assertions,\nfix StringAssert/CollectionAssert/IsInstanceOfType, modernize DataRow or\nDynamicData, configure lifecycle/TestContext/cancellation/retry/parallelization,\nset up MSTest.Sdk, or fix MSTESTxxxx diagnostics. Preserves FixtureBase,\nMoq/NBuilder, project format, and package versions unless migration is requested.\nDO NOT USE for generating new tests (code-testing-agent), audits, running tests,\nframework migration, xUnit/NUnit/TUnit, or non-.NET.\nlicense: MIT</h2>\n<h1>Writing MSTest Tests</h1>\n<p>Help users write effective MSTest unit tests without exceeding the API level or\nconventions of the project's installed test stack.</p>\n<h2>When to Use</h2>\n<ul>\n<li>User wants to improve or modernize existing MSTest tests by implementing concrete fixes</li>\n<li>User asks about MSTest assertion APIs, data-driven patterns, or test lifecycle</li>\n<li>User asks to replace <code>Assert.IsTrue</code> with more specific assertions (collections, nulls, types, comparisons)</li>\n<li>User asks to replace hard casts with type-checking assertions in tests</li>\n<li>User needs help fixing a specific MSTest test bug or failing assertion</li>\n<li>User asks to fix swapped <code>Assert.AreEqual</code> argument order (expected first, actual second)</li>\n<li>User asks to convert <code>DynamicData</code> from <code>IEnumerable&lt;object[]&gt;</code> to ValueTuple-based data</li>\n<li>User asks to fix or understand an MSTest analyzer diagnostic (an <code>MSTESTxxxx</code> warning/error)</li>\n</ul>\n<h2>When Not to Use</h2>\n<ul>\n<li>User needs a test quality audit, anti-pattern detection, or flaky-test investigation (use <code>test-anti-patterns</code>)</li>\n<li>User needs to run or execute tests (use the <code>run-tests</code> skill)</li>\n<li>User needs to upgrade from MSTest v1/v2 to v3 (use <code>migrate-mstest-v1v2-to-v3</code>)</li>\n<li>User needs to upgrade from MSTest v3 to v4 (use <code>migrate-mstest-v3-to-v4</code>)</li>\n<li>User needs CI/CD pipeline configuration</li>\n<li>User is using xUnit, NUnit, or TUnit (not MSTest)</li>\n</ul>\n<h2>Inputs</h2>\n<table>\n<thead>\n<tr>\n<th>Input</th>\n<th>Required</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Code under test</td>\n<td>No</td>\n<td>The production code to be tested</td>\n</tr>\n<tr>\n<td>Existing test code</td>\n<td>No</td>\n<td>Current tests to fix, update, or modernize</td>\n</tr>\n<tr>\n<td>Test scenario description</td>\n<td>No</td>\n<td>What behavior the user wants to test</td>\n</tr>\n</tbody>\n</table>\n<h2>Response Guidelines</h2>\n<ul>\n<li><strong>Specific API or pattern questions</strong> (assertions, data-driven, lifecycle): Jump directly to the relevant workflow step. Do not follow the full workflow.</li>\n<li><strong>Generate new tests from scratch</strong>: Hand off to <code>code-testing-agent</code>; use this\nskill only as supporting MSTest API/version guidance.</li>\n<li><strong>Review and fix existing tests</strong>: Fix only the issues present. Do not add unrelated improvements.</li>\n<li><strong>Assertion transformations</strong>: Show the corrected call, then state the semantic\nreason in one sentence. For <code>Assert.AreEqual</code>, name <code>expected</code> first and\n<code>actual</code> second and explain that this preserves the Expected/Actual failure\nlabels.</li>\n<li><strong>Exception transformations</strong>: Scope the throwing operation in a lambda,\ndistinguish <code>ThrowsExactly&lt;T&gt;</code> (exact type) from <code>Throws&lt;T&gt;</code> (type or derived\ntype), and capture the returned exception when properties such as <code>ParamName</code>\nare part of the behavior.</li>\n</ul>\n<h2>Workflow</h2>\n<h3>Step 1: Determine project setup</h3>\n<p>Check the test project, <code>packages.config</code>, and assembly reference <code>HintPath</code>\nvalues for the exact MSTest version and project system:</p>\n<ul>\n<li>If using <code>MSTest.Sdk</code>: resolve its exact version from the project SDK\ndeclaration or <code>global.json</code> <code>msbuild-sdks</code>; do not assume the latest APIs</li>\n<li>If using <code>MSTest</code> metapackage: resolve its exact package version</li>\n<li>If using <code>MSTest.TestFramework</code> + <code>MSTest.TestAdapter</code>: check version for feature availability</li>\n<li>If using classic non-SDK XML (<code>ToolsVersion</code>, <code>Microsoft.CSharp.targets</code>,\nexplicit <code>&lt;Compile Include&gt;</code>) and/or <code>packages.config</code>: preserve that project\nsystem and add each new test file to <code>&lt;Compile Include&gt;</code>.</li>\n</ul>\n<p>Also inspect representative tests for custom base fixtures, helper libraries,\nmock syntax, naming, setup, and data builders. Existing conventions and installed\nversions win over the examples below. Do not upgrade MSTest, Moq, NBuilder, or\nthe project format unless the user explicitly asks for a migration.</p>\n<h3>MSTest API availability</h3>\n<table>\n<thead>\n<tr>\n<th>API/pattern</th>\n<th style=\"text-align: right\">Minimum version</th>\n<th>Compatible fallback</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>Assert.ThrowsExactly*</code>, unified <code>Assert.Contains</code> / <code>HasCount</code> / <code>IsEmpty</code> / <code>IsNotEmpty</code></td>\n<td style=\"text-align: right\">3.8</td>\n<td><code>Assert.ThrowsException*</code>, <code>CollectionAssert</code>, <code>StringAssert</code></td>\n</tr>\n<tr>\n<td><code>Assert.IsGreaterThan</code>, <code>IsLessThan</code>, <code>IsInRange</code>, <code>StartsWith</code>, <code>EndsWith</code>, <code>MatchesRegex</code></td>\n<td style=\"text-align: right\">3.10</td>\n<td><code>Assert.IsTrue</code> with a clear message, or <code>StringAssert</code></td>\n</tr>\n<tr>\n<td>ValueTuple <code>DynamicData</code></td>\n<td style=\"text-align: right\">3.7</td>\n<td><code>IEnumerable&lt;object[]&gt;</code></td>\n</tr>\n<tr>\n<td>Constructor injection of <code>TestContext</code></td>\n<td style=\"text-align: right\">3.6</td>\n<td>Instance <code>TestContext</code> property</td>\n</tr>\n<tr>\n<td><code>[Retry]</code>, <code>[OSCondition]</code></td>\n<td style=\"text-align: right\">3.8</td>\n<td>No built-in retry/OS condition; fix flakiness or retain the existing condition mechanism</td>\n</tr>\n<tr>\n<td><code>[CICondition]</code></td>\n<td style=\"text-align: right\">3.10</td>\n<td>Existing project-specific condition mechanism</td>\n</tr>\n</tbody>\n</table>\n<p>For example, MSTest 3.5.x must not receive <code>Assert.ThrowsExactly</code>,\n<code>Assert.Contains</code>, ValueTuple <code>DynamicData</code>, or constructor-injected\n<code>TestContext</code>.</p>\n<p>Treat this as a hard gate: after determining the version, do not copy a later\nexample from this skill unless its minimum version is satisfied.</p>\n<p>Recommend MSTest.Sdk or the MSTest metapackage only for genuinely new projects:</p>\n<pre><code>&lt;!-- Option 1: MSTest SDK (simplest, recommended for new projects) --&gt;\n&lt;Project Sdk=\"MSTest.Sdk\"&gt;\n  &lt;PropertyGroup&gt;\n    &lt;TargetFramework&gt;net9.0&lt;/TargetFramework&gt;\n  &lt;/PropertyGroup&gt;\n&lt;/Project&gt;\n</code></pre>\n<p>When using <code>MSTest.Sdk</code>, put the version in <code>global.json</code> instead of the project file so all test projects get bumped together:</p>\n<pre><code>{\n  \"msbuild-sdks\": {\n    \"MSTest.Sdk\": \"3.8.2\"\n  }\n}\n</code></pre>\n<pre><code>&lt;!-- Option 2: MSTest metapackage --&gt;\n&lt;Project Sdk=\"Microsoft.NET.Sdk\"&gt;\n  &lt;PropertyGroup&gt;\n    &lt;TargetFramework&gt;net9.0&lt;/TargetFramework&gt;\n  &lt;/PropertyGroup&gt;\n  &lt;ItemGroup&gt;\n    &lt;PackageReference Include=\"MSTest\" Version=\"3.8.2\" /&gt;\n  &lt;/ItemGroup&gt;\n&lt;/Project&gt;\n</code></pre>\n<h3>Step 2: Write test classes following conventions</h3>\n<p>Apply these structural conventions only where they do not conflict with the\nsuite's established base classes and lifecycle:</p>\n<ul>\n<li><strong>Seal test classes</strong> with <code>sealed</code> for performance and design clarity</li>\n<li>Use <code>[TestClass]</code> on the class and <code>[TestMethod]</code> on test methods</li>\n<li>Follow the <strong>Arrange-Act-Assert</strong> (AAA) pattern</li>\n<li>Name tests using <code>MethodName_Scenario_ExpectedBehavior</code></li>\n<li>Use separate test projects with naming convention <code>[ProjectName].Tests</code></li>\n</ul>\n<pre><code>[TestClass]\npublic sealed class OrderServiceTests\n{\n    [TestMethod]\n    public void CalculateTotal_WithDiscount_ReturnsReducedPrice()\n    {\n        // Arrange\n        var service = new OrderService();\n        var order = new Order { Price = 100m, DiscountPercent = 10 };\n\n        // Act\n        var total = service.CalculateTotal(order);\n\n        // Assert\n        Assert.AreEqual(90m, total);\n    }\n}\n</code></pre>\n<h3>Step 3: Use version-compatible assertion APIs</h3>\n<p>Pick the most specific assertion supported by the installed MSTest version.\nMore specific assertions produce better failure messages and make the test's\nintent clear, but uncompilable \"modern\" assertions are worse than compatible\n<code>StringAssert</code>, <code>CollectionAssert</code>, or <code>Assert.IsTrue</code> calls.</p>\n<table>\n<thead>\n<tr>\n<th>What you are testing</th>\n<th>Assertion</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Two values are equal</td>\n<td><code>Assert.AreEqual(expected, actual)</code></td>\n</tr>\n<tr>\n<td>Same object instance (reference identity)</td>\n<td><code>Assert.AreSame(expected, actual)</code></td>\n</tr>\n<tr>\n<td>Value is null</td>\n<td><code>Assert.IsNull(value)</code></td>\n</tr>\n<tr>\n<td>Value is not null</td>\n<td><code>Assert.IsNotNull(value)</code></td>\n</tr>\n<tr>\n<td>Collection is empty</td>\n<td><code>Assert.IsEmpty(collection)</code> (3.8+) or <code>CollectionAssert</code> / count assertion</td>\n</tr>\n<tr>\n<td>Collection is not empty</td>\n<td><code>Assert.IsNotEmpty(collection)</code> (3.8+) or count assertion</td>\n</tr>\n<tr>\n<td>Collection has exactly N items</td>\n<td><code>Assert.HasCount(N, collection)</code> (3.8+) or <code>Assert.AreEqual</code> on count</td>\n</tr>\n<tr>\n<td>Collection contains an item</td>\n<td><code>Assert.Contains(item, collection)</code> (3.8+) or <code>CollectionAssert.Contains</code></td>\n</tr>\n<tr>\n<td>Collection does not contain an item</td>\n<td><code>Assert.DoesNotContain(item, collection)</code> (3.8+) or <code>CollectionAssert.DoesNotContain</code></td>\n</tr>\n<tr>\n<td>Object is a specific type</td>\n<td><code>Assert.IsInstanceOfType&lt;T&gt;(value)</code></td>\n</tr>\n<tr>\n<td>Code throws an exception</td>\n<td><code>Assert.ThrowsExactly&lt;T&gt;</code> (3.8+) or <code>Assert.ThrowsException&lt;T&gt;</code> (earlier)</td>\n</tr>\n</tbody>\n</table>\n<p>On MSTest 3.8+, prefer <code>Assert</code> class methods over <code>StringAssert</code> or\n<code>CollectionAssert</code> where both exist. Older versions should keep the compatible\nspecialized classes.</p>\n<h4>Equality, null, and reference checks</h4>\n<pre><code>Assert.AreEqual(expected, actual);      // Value equality\nAssert.AreSame(expected, actual);       // Reference equality -- same object instance\nAssert.IsNull(value);\nAssert.IsNotNull(value);\n</code></pre>\n<h4>Exception testing</h4>\n<pre><code>// MSTest 3.8+\nvar ex = Assert.ThrowsExactly&lt;ArgumentNullException&gt;(() =&gt; service.Process(null));\nAssert.AreEqual(\"input\", ex.ParamName);\n\n// Async\nvar ex = await Assert.ThrowsExactlyAsync&lt;InvalidOperationException&gt;(\n    async () =&gt; await service.ProcessAsync(null));\n</code></pre>\n<ul>\n<li><code>Assert.Throws&lt;T&gt;</code> matches <code>T</code> or any derived type</li>\n<li><code>Assert.ThrowsExactly&lt;T&gt;</code> matches only the exact type <code>T</code></li>\n</ul>\n<p>On MSTest 3.7 and earlier, use the compatible API:</p>\n<pre><code>var ex = Assert.ThrowsException&lt;ArgumentNullException&gt;(\n    () =&gt; service.Process(null));\n</code></pre>\n<h4>Collection assertions</h4>\n<pre><code>// MSTest 3.8+\nAssert.Contains(expectedItem, collection);\nAssert.DoesNotContain(unexpectedItem, collection);\nvar single = Assert.ContainsSingle(collection);  // Returns the single element\nAssert.HasCount(3, collection);\nAssert.IsEmpty(collection);\nAssert.IsNotEmpty(collection);\n</code></pre>\n<p>On earlier versions use <code>CollectionAssert.Contains</code>,\n<code>CollectionAssert.DoesNotContain</code>, and <code>Assert.AreEqual(expectedCount, collection.Count)</code>.</p>\n<p>Replace generic <code>Assert.IsTrue</code> with specialized assertions -- they give better failure messages:</p>\n<table>\n<thead>\n<tr>\n<th>Instead of</th>\n<th>Use</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>Assert.IsTrue(list.Count &gt; 0)</code></td>\n<td><code>Assert.IsNotEmpty(list)</code></td>\n</tr>\n<tr>\n<td><code>Assert.IsTrue(list.Count == 0)</code></td>\n<td><code>Assert.IsEmpty(list)</code></td>\n</tr>\n<tr>\n<td><code>Assert.IsTrue(list.Count() == 3)</code></td>\n<td><code>Assert.HasCount(3, list)</code></td>\n</tr>\n<tr>\n<td><code>Assert.IsTrue(x != null)</code></td>\n<td><code>Assert.IsNotNull(x)</code></td>\n</tr>\n<tr>\n<td><code>Assert.IsTrue(x == null)</code></td>\n<td><code>Assert.IsNull(x)</code></td>\n</tr>\n<tr>\n<td><code>Assert.AreEqual(a, b)</code> for same instance</td>\n<td><code>Assert.AreSame(a, b)</code> -- reference identity</td>\n</tr>\n<tr>\n<td><code>Assert.IsTrue(!list.Contains(item))</code></td>\n<td><code>Assert.DoesNotContain(item, list)</code></td>\n</tr>\n<tr>\n<td><code>list.Single(predicate)</code> + <code>Assert.IsNotNull</code></td>\n<td><code>Assert.ContainsSingle(list)</code></td>\n</tr>\n<tr>\n<td><code>Assert.IsTrue(list.Contains(item))</code></td>\n<td><code>Assert.Contains(item, list)</code></td>\n</tr>\n</tbody>\n</table>\n<h4>String assertions</h4>\n<pre><code>// MSTest 3.10+\nAssert.Contains(\"expected\", actualString);\nAssert.StartsWith(\"prefix\", actualString);\nAssert.EndsWith(\"suffix\", actualString);\nAssert.MatchesRegex(@\"\\d{3}-\\d{4}\", phoneNumber);\n</code></pre>\n<p>On earlier versions use <code>StringAssert.Contains</code>, <code>StringAssert.StartsWith</code>,\n<code>StringAssert.EndsWith</code>, and <code>StringAssert.Matches</code>.</p>\n<h4>Type assertions</h4>\n<pre><code>// MSTest 3.x -- out parameter\nAssert.IsInstanceOfType&lt;MyHandler&gt;(result, out var typed);\ntyped.Handle();\n\n// MSTest 4.x -- returns directly\nvar typed = Assert.IsInstanceOfType&lt;MyHandler&gt;(result);\n</code></pre>\n<h4>Comparison assertions</h4>\n<pre><code>Assert.IsGreaterThan(lowerBound, actual);\nAssert.IsLessThan(upperBound, actual);\nAssert.IsInRange(low, high, actual);\n</code></pre>\n<h3>Step 4: Use data-driven tests for multiple inputs</h3>\n<h4>DataRow for inline values</h4>\n<pre><code>[TestMethod]\n[DataRow(1, 2, 3)]\n[DataRow(0, 0, 0, DisplayName = \"Zeros\")]\n[DataRow(-1, 1, 0)]\npublic void Add_ReturnsExpectedSum(int a, int b, int expected)\n{\n    Assert.AreEqual(expected, Calculator.Add(a, b));\n}\n</code></pre>\n<h4>DynamicData with ValueTuples (preferred for complex data)</h4>\n<p>On MSTest 3.7+, prefer <code>ValueTuple</code> return types over\n<code>IEnumerable&lt;object[]&gt;</code> for type safety. Keep <code>IEnumerable&lt;object[]&gt;</code> on older\nversions.</p>\n<pre><code>[TestMethod]\n[DynamicData(nameof(DiscountTestData))]\npublic void ApplyDiscount_ReturnsExpectedPrice(decimal price, int percent, decimal expected)\n{\n    var result = PriceCalculator.ApplyDiscount(price, percent);\n    Assert.AreEqual(expected, result);\n}\n\n// ValueTuple -- preferred (MSTest 3.7+)\npublic static IEnumerable&lt;(decimal price, int percent, decimal expected)&gt; DiscountTestData =&gt;\n[\n    (100m, 10, 90m),\n    (200m, 25, 150m),\n    (50m, 0, 50m),\n];\n</code></pre>\n<p>When you need metadata per test case on MSTest 3.8+, use <code>TestDataRow&lt;T&gt;</code>:</p>\n<pre><code>public static IEnumerable&lt;TestDataRow&lt;(decimal price, int percent, decimal expected)&gt;&gt; DiscountTestDataWithMetadata =&gt;\n[\n    new((100m, 10, 90m)) { DisplayName = \"10% discount\" },\n    new((200m, 25, 150m)) { DisplayName = \"25% discount\" },\n    new((50m, 0, 50m)) { DisplayName = \"No discount\" },\n];\n</code></pre>\n<h3>Step 5: Handle test lifecycle correctly</h3>\n<ul>\n<li>Prefer constructor initialization when the existing suite supports it; retain a shared <code>FixtureBase&lt;TSut&gt;</code> or established <code>[TestInitialize]</code> lifecycle rather than rewriting the fixture architecture incidentally.</li>\n<li>Use <code>[TestInitialize]</code> <strong>only</strong> for async initialization, combined with the constructor for sync parts</li>\n<li>Use <code>[TestCleanup]</code> for cleanup that must run even on failure</li>\n<li>Inject <code>TestContext</code> via constructor only on MSTest 3.6+; otherwise use the instance property.</li>\n</ul>\n<pre><code>[TestClass]\npublic sealed class RepositoryTests\n{\n    private readonly TestContext _testContext;\n    private readonly FakeDatabase _db;  // readonly -- guaranteed by constructor\n\n    public RepositoryTests(TestContext testContext)\n    {\n        _testContext = testContext;\n        _db = new FakeDatabase();  // sync init in ctor\n    }\n\n    [TestInitialize]\n    public async Task InitAsync()\n    {\n        // Use TestInitialize ONLY for async setup\n        await _db.SeedAsync();\n    }\n\n    [TestCleanup]\n    public void Cleanup() =&gt; _db.Reset();\n}\n</code></pre>\n<h4>Execution order</h4>\n<ol>\n<li><code>[AssemblyInitialize]</code> -- once per assembly</li>\n<li><code>[ClassInitialize]</code> -- once per class</li>\n<li>Per test:\n<ul>\n<li>With <code>TestContext</code> property injection: Constructor -&gt; set <code>TestContext</code> property -&gt; <code>[TestInitialize]</code></li>\n<li>With constructor injection of <code>TestContext</code>: Constructor (receives <code>TestContext</code>) -&gt; <code>[TestInitialize]</code></li>\n</ul>\n</li>\n<li>Test method</li>\n<li><code>[TestCleanup]</code> -&gt; <code>DisposeAsync</code> -&gt; <code>Dispose</code> -- per test</li>\n<li><code>[ClassCleanup]</code> -- once per class</li>\n<li><code>[AssemblyCleanup]</code> -- once per assembly</li>\n</ol>\n<h3>Step 6: Apply cancellation and timeout patterns</h3>\n<p>Use <code>TestContext.CancellationToken</code> with <code>[Timeout]</code> only when the installed\nMSTest version exposes it. On older versions, use a test-owned\n<code>CancellationTokenSource</code> where cancellation itself is under test.</p>\n<pre><code>[TestMethod]\n[Timeout(5000)]\npublic async Task FetchData_ReturnsWithinTimeout()\n{\n    var result = await _client.GetDataAsync(_testContext.CancellationToken);\n    Assert.IsNotNull(result);\n}\n</code></pre>\n<h3>Step 7: Use advanced features where appropriate</h3>\n<h4>Retry flaky tests (MSTest 3.8+)</h4>\n<p>Use only for genuinely flaky external dependencies (network, file system), not to paper over race conditions or shared state issues.</p>\n<pre><code>[TestMethod]\n[Retry(3)]\npublic void ExternalService_EventuallyResponds() { }\n</code></pre>\n<h4>Conditional execution</h4>\n<p><code>OSCondition</code> requires MSTest 3.8+; <code>CICondition</code> requires MSTest 3.10+.</p>\n<pre><code>[TestMethod]\n[OSCondition(OperatingSystems.Windows)]\npublic void WindowsRegistry_ReadsValue() { }\n\n[TestMethod]\n[CICondition(ConditionMode.Exclude)]\npublic void LocalOnly_InteractiveTest() { }\n</code></pre>\n<h4>Parallelization</h4>\n<pre><code>[assembly: Parallelize(Workers = 4, Scope = ExecutionScope.MethodLevel)]\n\n[TestClass]\n[DoNotParallelize]  // Opt out specific classes\npublic sealed class DatabaseIntegrationTests { }\n</code></pre>\n<h3>Step 8: Fix MSTest analyzer diagnostics (MSTESTxxxx)</h3>\n<p>The <code>MSTest.Analyzers</code> package reports <code>MSTESTxxxx</code> diagnostics during build and in the IDE. The analyzers come in automatically with the modern <code>MSTest</code> metapackage and <code>MSTest.Sdk</code> (and are bundled with <code>MSTest.TestFramework</code> 3.7+); for other setups, reference <code>MSTest.Analyzers</code> 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.</p>\n<p>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: <a href=\"https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/overview\">https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/overview</a>.</p>\n<h4>Common diagnostics and their fixes</h4>\n<table>\n<thead>\n<tr>\n<th>Rule</th>\n<th>Problem</th>\n<th>Fix</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>MSTEST0006</td>\n<td><code>[ExpectedException]</code> used</td>\n<td>On 3.8+, replace with <code>Assert.Throws&lt;T&gt;</code> / <code>Assert.ThrowsExactly&lt;T&gt;</code>; otherwise use <code>Assert.ThrowsException&lt;T&gt;</code></td>\n</tr>\n<tr>\n<td>MSTEST0017</td>\n<td><code>Assert.AreEqual</code> args swapped</td>\n<td>Put <code>expected</code> first, <code>actual</code> second</td>\n</tr>\n<tr>\n<td>MSTEST0023</td>\n<td>Negated boolean assertion (<code>Assert.IsTrue(!x)</code>)</td>\n<td>Use <code>Assert.IsFalse(x)</code></td>\n</tr>\n<tr>\n<td>MSTEST0025</td>\n<td>Always-false condition asserted</td>\n<td>Use <code>Assert.Fail(\"reason\")</code></td>\n</tr>\n<tr>\n<td>MSTEST0032</td>\n<td>Always-true assert condition</td>\n<td>Remove or correct the assertion</td>\n</tr>\n<tr>\n<td>MSTEST0037</td>\n<td>Sub-optimal assert (<code>IsTrue(x == null)</code>)</td>\n<td>Use the specific assert (<code>Assert.IsNull</code>, <code>HasCount</code>, etc.) (Step 3)</td>\n</tr>\n<tr>\n<td>MSTEST0038</td>\n<td><code>Assert.AreSame</code> on value types</td>\n<td>Use <code>Assert.AreEqual</code> (value types box to distinct references)</td>\n</tr>\n<tr>\n<td>MSTEST0039</td>\n<td>Legacy <code>Assert.ThrowsException</code></td>\n<td>On 3.8+, use <code>Assert.Throws</code> / <code>Assert.ThrowsExactly</code> (+ <code>Async</code> variants)</td>\n</tr>\n<tr>\n<td>MSTEST0044</td>\n<td><code>[DataTestMethod]</code> used</td>\n<td>Replace with <code>[TestMethod]</code> only on a version where it supports data rows</td>\n</tr>\n<tr>\n<td>MSTEST0046</td>\n<td><code>StringAssert</code> used</td>\n<td>On 3.10+, use the equivalent <code>Assert</code> method (<code>Assert.Contains</code>, <code>StartsWith</code>, ...)</td>\n</tr>\n<tr>\n<td>MSTEST0052</td>\n<td>Explicit <code>DynamicDataSourceType</code></td>\n<td>Drop it — the source type is inferred</td>\n</tr>\n<tr>\n<td>MSTEST0042 / MSTEST0060</td>\n<td>Duplicate <code>[DataRow]</code> / <code>[TestMethod]</code></td>\n<td>Remove the duplicate attribute</td>\n</tr>\n<tr>\n<td>MSTEST0024</td>\n<td>Static <code>TestContext</code> field</td>\n<td>Make it an instance member (Step 5)</td>\n</tr>\n<tr>\n<td>MSTEST0045 / MSTEST0049 / MSTEST0054</td>\n<td>Timeout/token not cooperative</td>\n<td>Flow <code>TestContext.CancellationToken</code> into the awaited call (Step 6)</td>\n</tr>\n<tr>\n<td>MSTEST0036</td>\n<td>Member shadows a base test member</td>\n<td>Rename or use <code>override</code> instead of <code>new</code></td>\n</tr>\n<tr>\n<td>MSTEST0061</td>\n<td>Runtime OS check inside a test</td>\n<td>Use <code>[OSCondition(...)]</code> (Step 7)</td>\n</tr>\n<tr>\n<td>MSTEST0002 / MSTEST0003 / MSTEST0005 / MSTEST0007–0014</td>\n<td>Invalid test class / method / fixture / <code>TestContext</code> / data-source layout</td>\n<td>Correct the signature named by the rule (e.g. make it public, fix the return type and parameters, add <code>static</code> where required)</td>\n</tr>\n</tbody>\n</table>\n<h4>Tuning which rules are enforced</h4>\n<p>Use the <code>MSTestAnalysisMode</code> MSBuild property (MSTest 3.8+) to control the rule set globally:</p>\n<pre><code>&lt;PropertyGroup&gt;\n  &lt;!-- None | Default | Recommended | All --&gt;\n  &lt;MSTestAnalysisMode&gt;Recommended&lt;/MSTestAnalysisMode&gt;\n&lt;/PropertyGroup&gt;\n</code></pre>\n<ul>\n<li><code>Recommended</code> escalates info-level rules to warnings and is the mode most projects should adopt.</li>\n<li>A handful of rules are completely opt-in (e.g. MSTEST0015, MSTEST0019–0022); enable them per project via <code>.editorconfig</code> when you want their convention enforced.</li>\n<li>Prefer fixing the underlying code over suppressing a diagnostic. Suppress only with a documented justification.</li>\n</ul>\n","files":[{"path":"references/advanced-mstest-patterns.md","sizeBytes":4369,"isText":true},{"path":"SKILL.md","sizeBytes":19980,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-10-16T00:43:28.765074Z","sha256":"E586C3F5AF0F3880D897C734D747FEC76ABC1B3AFEE964CB1AE516EF5B6DF2DF","sizeBytes":9658},"review":null,"source":{"repositoryUrl":"https://github.com/dotnet/skills","path":"plugins/dotnet-test/skills/writing-mstest-tests","license":"MIT","commit":"4e03bfdade5d1f9b7d1c2e95f64e31d1cb7af5ab","subtreeSha":"F197265AE5F5325A07FAA160E49F7754B467874216BDCBC1E15EC89623467093","lastSyncedAt":"2026-11-19T19:30:03.195544Z"},"reviewedAt":"2026-10-16T00:47:23.30752Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/dotnet/skills/tree/main/plugins/dotnet-test/skills/writing-mstest-tests"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install dotnet-skills@llmmart"},{"target":"git","command":"git clone https://github.com/dotnet/skills.git"}]}