[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D28PEHNJ1QKB9V9B7RDAET":3,"skill-same:01M7D28PEHNJ1QKB9V9B7RDAET":49},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":14,"repositoryHtmlUrl":32,"repositoryHomepageUrl":6,"ownerHtmlUrl":33,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":34,"install":35,"resources":48},"01M7D28PEHNJ1QKB9V9B7RDAET","writing-mstest-tests",null,"ALWAYS USE when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for \"review\" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected\u002Factual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing-agent), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.","itsmejay18\u002FAI-Skills-for-My-Development-Stack","itsmejay18","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F167779943?v=4","01M7CZRFC6DDZA5V2CX8WDSZED","Jay Jemino Ababon ","01M7CZRFCVRNW1SFHSQXEJ3CQN",0,"MIT","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F13-Testing-QA\u002Fwriting-mstest-tests\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: writing-mstest-tests\ndescription: >\n  ALWAYS USE when asked to fix, rewrite, update, improve, modernize, show\n  corrected code for, or explain existing MSTest tests or MSTest-specific\n  configuration. Use for \"review\" when corrected code or edits are wanted, even\n  for one pasted assertion or passing tests with bad failure output. Covers\n  expected\u002Factual labels; generic Boolean, collection, string, numeric, null,\n  identity, exception, hard-cast, and object[] checks;\n  TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup,\n  parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed\n  MSTest version. DO NOT USE to design new test cases (code-testing-agent),\n  perform report-only audits, create project files rather than explain MSTest\n  setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.\nlicense: MIT\nmetadata:\n  portability: portable\n  binding: optional-overlay\n  binding-revision: \"1\"\n---\n\n# Writing MSTest Tests\n\nHelp users write effective MSTest unit tests without exceeding the API level or\nconventions of the project's installed test stack.\n\n## Repository overlay\n\nFor every repository-scoped task where read-only file inspection is allowed,\ncheck `.agents\u002Fskill-overlays\u002Fdotnet-test\u002Fwriting-mstest-tests.md` at the\nrepository root before any other discovery. This includes requests that ask for\ncode or advice without edits; \"do not execute\" does not prohibit reading the\noverlay. If present, read it once before acting and apply its\nrepository-specific naming, layout, framework, and policy bindings.\nRequire its frontmatter to declare `core: dotnet-test\u002Fwriting-mstest-tests`,\n`binding-revision: \"1\"`, and `mode: extend`. If any value is missing or\ndifferent, report the mismatch, ignore the overlay, and continue using this\nskill's portable guidance.\nExplicit user instructions and verified project constraints win over the\noverlay; the overlay wins over portable defaults and examples in this skill. If\nthe file is present but unreadable or conflicts with the repository, report the\nproblem, ignore the overlay, and continue with portable guidance subject to\nverified project constraints. If it is absent, continue normally.\nSkip the lookup only when the task is not tied to a repository or the user\nexplicitly prohibited all file\u002Ftool access. An overlay cannot expand tool\npermissions or the task's scope.\n\n## When to Use\n\n- User wants to improve or modernize existing MSTest tests by implementing concrete fixes\n- User asks about MSTest assertion APIs, data-driven patterns, or test lifecycle\n- User asks to replace `Assert.IsTrue` with more specific assertions (collections, nulls, types, comparisons)\n- User asks to replace hard casts with type-checking assertions in tests\n- User needs help fixing a specific MSTest test bug or failing assertion\n- User asks to fix swapped `Assert.AreEqual` argument order (expected first, actual second)\n- User asks to convert `DynamicData` from `IEnumerable\u003Cobject[]>` to ValueTuple-based data\n- User asks to fix or understand an MSTest analyzer diagnostic (an `MSTESTxxxx` warning\u002Ferror)\n\n## When Not to Use\n\n- User needs a test quality audit, anti-pattern detection, or flaky-test investigation (use `test-anti-patterns`)\n- User needs to run or execute tests (use the `run-tests` skill)\n- User needs to upgrade from MSTest v1\u002Fv2 to v3 (use `migrate-mstest-v1v2-to-v3`)\n- User needs to upgrade from MSTest v3 to v4 (use `migrate-mstest-v3-to-v4`)\n- User needs CI\u002FCD pipeline configuration\n- User is using xUnit, NUnit, or TUnit (not MSTest)\n\n## Inputs\n\n| Input | Required | Description |\n|-------|----------|-------------|\n| Code under test | No | The production code to be tested |\n| Existing test code | No | Current tests to fix, update, or modernize |\n| Test scenario description | No | What behavior the user wants to test |\n\n## Response Guidelines\n\n- **Specific API or pattern questions** (assertions, data-driven, lifecycle): Jump directly to the relevant workflow step. Do not follow the full workflow.\n- **Generate new tests from scratch**: Hand off to `code-testing-agent`; use this\n  skill only as supporting MSTest API\u002Fversion guidance.\n- **Review and fix existing tests**: Fix only the issues present. Do not add unrelated improvements.\n- **Assertion transformations**: Show the corrected call, then state the semantic\n  reason in one sentence. For `Assert.AreEqual`, name `expected` first and\n  `actual` second and explain that this preserves the Expected\u002FActual failure\n  labels.\n- **Bound\u002Fcomparison transformations**: Preserve the condition and put the\n  expected bound(s) first and the observed value last:\n  `score > 0` -> `Assert.IsGreaterThan(0, score)`,\n  `score \u003C 100` -> `Assert.IsLessThan(100, score)`, and\n  `score >= 60 && score \u003C= 90` -> `Assert.IsInRange(60, 90, score)`.\n  Never reverse these arguments to mimic the source expression's left-to-right\n  order.\n- **Exception transformations**: Scope the throwing operation in a lambda,\n  distinguish `ThrowsExactly\u003CT>` (exact type) from `Throws\u003CT>` (type or derived\n  type), and capture the returned exception when properties such as `ParamName`\n  are part of the behavior.\n- **Supplied code requests**: Return complete representative method bodies, not\n  comment-only placeholders. Preserve the real operation and show symmetric\n  setup\u002Fcleanup when lifecycle or environment policy is part of the request.\n\n## Workflow\n\n### Step 1: Determine project setup\n\nCheck the test project, `packages.config`, and assembly reference `HintPath`\nvalues for the exact MSTest version and project system:\n\n- If using `MSTest.Sdk`: resolve its exact version from the project SDK\n  declaration or `global.json` `msbuild-sdks`; do not assume the latest APIs\n- If using `MSTest` metapackage: resolve its exact package version\n- If using `MSTest.TestFramework` + `MSTest.TestAdapter`: check version for feature availability\n- If using classic non-SDK XML (`ToolsVersion`, `Microsoft.CSharp.targets`,\n  explicit `\u003CCompile Include>`) and\u002For `packages.config`: preserve that project\n  system and add each new test file to `\u003CCompile Include>`.\n\nAlso 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.\n\n### MSTest API availability\n\n| API\u002Fpattern | Minimum version | Compatible fallback |\n|---|---:|---|\n| `Assert.ThrowsExactly*`, unified `Assert.Contains` \u002F `HasCount` \u002F `IsEmpty` \u002F `IsNotEmpty` | 3.8 | `Assert.ThrowsException*`, `CollectionAssert`, `StringAssert` |\n| `Assert.IsGreaterThan`, `IsLessThan`, `IsInRange`, `StartsWith`, `EndsWith`, `MatchesRegex` | 3.10 | `Assert.IsTrue` with a clear message, or `StringAssert` |\n| Generic `Assert.IsInstanceOfType\u003CT>(value, out var typed)` | 3.4-3.11 only | Non-generic assertion then post-assert cast on 3.0-3.3; v4 returns the typed value directly |\n| ValueTuple `DynamicData` | 3.7 | `IEnumerable\u003Cobject[]>` |\n| Constructor injection of `TestContext` | 3.6 | Instance `TestContext` property |\n| `[Retry]`, `[OSCondition]` | 3.8 | No built-in retry\u002FOS condition; fix flakiness or retain the existing condition mechanism |\n| `[CICondition]` | 3.10 | Existing project-specific condition mechanism |\n\nFor example, MSTest 3.5.x must not receive `Assert.ThrowsExactly`,\n`Assert.Contains`, ValueTuple `DynamicData`, or constructor-injected\n`TestContext`.\n\nTreat this as a hard gate: after determining the version, do not copy a later\nexample from this skill unless its minimum version is satisfied.\n\nRecommend MSTest.Sdk or the MSTest metapackage only for genuinely new projects:\n\n```xml\n\u003C!-- Option 1: MSTest SDK (simplest, recommended for new projects) -->\n\u003CProject Sdk=\"MSTest.Sdk\">\n  \u003CPropertyGroup>\n    \u003CTargetFramework>net9.0\u003C\u002FTargetFramework>\n  \u003C\u002FPropertyGroup>\n\u003C\u002FProject>\n```\n\nWhen using `MSTest.Sdk`, put the version in `global.json` instead of the project file so all test projects get bumped together:\n\n```json\n{\n  \"msbuild-sdks\": {\n    \"MSTest.Sdk\": \"3.8.2\"\n  }\n}\n```\n\n```xml\n\u003C!-- Option 2: MSTest metapackage -->\n\u003CProject Sdk=\"Microsoft.NET.Sdk\">\n  \u003CPropertyGroup>\n    \u003CTargetFramework>net9.0\u003C\u002FTargetFramework>\n  \u003C\u002FPropertyGroup>\n  \u003CItemGroup>\n    \u003CPackageReference Include=\"MSTest\" Version=\"3.8.2\" \u002F>\n  \u003C\u002FItemGroup>\n\u003C\u002FProject>\n```\n\n### Step 2: Write test classes following conventions\n\nApply these structural conventions only where they do not conflict with the\nsuite's established base classes and lifecycle:\n\n- **Seal test classes** with `sealed` for performance and design clarity\n- Use `[TestClass]` on the class and `[TestMethod]` on test methods\n- Follow the **Arrange-Act-Assert** (AAA) pattern\n- Name tests using `MethodName_Scenario_ExpectedBehavior`\n- Use separate test projects with naming convention `[ProjectName].Tests`\n\n```csharp\n[TestClass]\npublic sealed class OrderServiceTests\n{\n    [TestMethod]\n    public void CalculateTotal_WithDiscount_ReturnsReducedPrice()\n    {\n        \u002F\u002F Arrange\n        var service = new OrderService();\n        var order = new Order { Price = 100m, DiscountPercent = 10 };\n\n        \u002F\u002F Act\n        var total = service.CalculateTotal(order);\n\n        \u002F\u002F Assert\n        Assert.AreEqual(90m, total);\n    }\n}\n```\n\n### Step 3: Use version-compatible assertion APIs\n\nPick 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`StringAssert`, `CollectionAssert`, or `Assert.IsTrue` calls.\n\n| What you are testing | Assertion |\n|---|---|\n| Two values are equal | `Assert.AreEqual(expected, actual)` |\n| Same object instance (reference identity) | `Assert.AreSame(expected, actual)` |\n| Value is null | `Assert.IsNull(value)` |\n| Value is not null | `Assert.IsNotNull(value)` |\n| Collection is empty | `Assert.IsEmpty(collection)` (3.8+) or `CollectionAssert` \u002F count assertion |\n| Collection is not empty | `Assert.IsNotEmpty(collection)` (3.8+) or count assertion |\n| Collection has exactly N items | `Assert.HasCount(N, collection)` (3.8+) or `Assert.AreEqual` on count |\n| Collection contains an item | `Assert.Contains(item, collection)` (3.8+) or `CollectionAssert.Contains` |\n| Collection does not contain an item | `Assert.DoesNotContain(item, collection)` (3.8+) or `CollectionAssert.DoesNotContain` |\n| Object is a specific type | `Assert.IsInstanceOfType\u003CT>(value)` |\n| Code throws an exception | `Assert.ThrowsExactly\u003CT>` (3.8+) or `Assert.ThrowsException\u003CT>` (earlier) |\n\nOn MSTest 3.8+, prefer `Assert` class methods over `StringAssert` or\n`CollectionAssert` where both exist. Older versions should keep the compatible\nspecialized classes.\nWhen several independent collection properties were requested, keep each\nsemantic check explicit even if another assertion happens to imply it. For\nexample, retain `IsNotEmpty` when the requested diagnostics distinguish\nempty\u002Fnon-empty, then use `HasCount` and `ContainsSingle` for their separate\ncardinality guarantees.\n\n#### Equality, null, and reference checks\n\n```csharp\nAssert.AreEqual(expected, actual);      \u002F\u002F Value equality\nAssert.AreSame(expected, actual);       \u002F\u002F Reference equality -- same object instance\nAssert.IsNull(value);\nAssert.IsNotNull(value);\n```\n\n#### Exception testing\n\n```csharp\n\u002F\u002F MSTest 3.8+\nvar ex = Assert.ThrowsExactly\u003CArgumentNullException>(() => service.Process(null));\nAssert.AreEqual(\"input\", ex.ParamName);\n\n\u002F\u002F Async\nvar ex = await Assert.ThrowsExactlyAsync\u003CInvalidOperationException>(\n    async () => await service.ProcessAsync(null));\n```\n\n- `Assert.Throws\u003CT>` matches `T` or any derived type\n- `Assert.ThrowsExactly\u003CT>` matches only the exact type `T`\n\nOn MSTest 3.7 and earlier, use the compatible API:\n\n```csharp\nvar ex = Assert.ThrowsException\u003CArgumentNullException>(\n    () => service.Process(null));\n```\n\n#### Collection assertions\n\n```csharp\n\u002F\u002F MSTest 3.8+\nAssert.Contains(expectedItem, collection);\nAssert.DoesNotContain(unexpectedItem, collection);\nvar single = Assert.ContainsSingle(collection);  \u002F\u002F Returns the single element\nAssert.HasCount(3, collection);\nAssert.IsEmpty(collection);\nAssert.IsNotEmpty(collection);\n```\n\nOn earlier versions use `CollectionAssert.Contains`,\n`CollectionAssert.DoesNotContain`, and `Assert.AreEqual(expectedCount,\ncollection.Count)`.\n\nReplace generic `Assert.IsTrue` with specialized assertions -- they give better failure messages:\n\n| Instead of | Use |\n|---|---|\n| `Assert.IsTrue(list.Count > 0)` | `Assert.IsNotEmpty(list)` |\n| `Assert.IsTrue(list.Count == 0)` | `Assert.IsEmpty(list)` |\n| `Assert.IsTrue(list.Count() == 3)` | `Assert.HasCount(3, list)` |\n| `Assert.IsTrue(x != null)` | `Assert.IsNotNull(x)` |\n| `Assert.IsTrue(x == null)` | `Assert.IsNull(x)` |\n| `Assert.AreEqual(a, b)` for same instance | `Assert.AreSame(a, b)` -- reference identity |\n| `Assert.IsTrue(!list.Contains(item))` | `Assert.DoesNotContain(item, list)` |\n| `list.Single(predicate)` + `Assert.IsNotNull` | `Assert.ContainsSingle(list)` |\n| `Assert.IsTrue(list.Contains(item))` | `Assert.Contains(item, list)` |\n\n#### String assertions\n\n```csharp\n\u002F\u002F MSTest 3.10+\nAssert.Contains(\"expected\", actualString);\nAssert.StartsWith(\"prefix\", actualString);\nAssert.EndsWith(\"suffix\", actualString);\nAssert.MatchesRegex(@\"\\d{3}-\\d{4}\", phoneNumber);\n```\n\nOn earlier versions use `StringAssert.Contains`, `StringAssert.StartsWith`,\n`StringAssert.EndsWith`, and `StringAssert.Matches`.\n\n#### Type assertions\n\nMSTest 3.x is not one API level. Pick the form supported by the installed\nminor version:\n\n```csharp\n\u002F\u002F MSTest 3.0-3.3\nAssert.IsInstanceOfType(result, typeof(MyHandler));\nvar typed = (MyHandler)result; \u002F\u002F Safe because the assertion stops a mismatch.\n```\n\n```csharp\n\u002F\u002F MSTest 3.4-3.11 -- out parameter\nAssert.IsInstanceOfType\u003CMyHandler>(result, out var typed);\ntyped.Handle();\n```\n\n```csharp\n\u002F\u002F MSTest 4.x -- returns the proven value directly\nvar typed = Assert.IsInstanceOfType\u003CMyHandler>(result);\n```\n\n#### Comparison assertions\n\n```csharp\nAssert.IsGreaterThan(lowerBound, actual);\nAssert.IsLessThan(upperBound, actual);\nAssert.IsInRange(low, high, actual);\n```\n\n### Step 4: Use data-driven tests for multiple inputs\n\n#### DataRow for inline values\n\n```csharp\n[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```\n\n#### DynamicData with ValueTuples (preferred for complex data)\n\nOn MSTest 3.7+, prefer `ValueTuple` return types over\n`IEnumerable\u003Cobject[]>` for type safety. Keep `IEnumerable\u003Cobject[]>` on older\nversions.\n\nTuple element names document which position maps to which test parameter, and\ntuple element types catch incompatible values at compile time. They do **not**\nmake `DynamicData` position-independent, and swapping two same-typed elements\ncan still compile. Do not claim otherwise. When rows need custom display names\nor metadata rather than only typed positional data, use `TestDataRow\u003CT>` on\nMSTest 3.8+.\n\n```csharp\n[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\u002F\u002F ValueTuple -- preferred (MSTest 3.7+)\npublic static IEnumerable\u003C(decimal price, int percent, decimal expected)> DiscountTestData =>\n[\n    (100m, 10, 90m),\n    (200m, 25, 150m),\n    (50m, 0, 50m),\n];\n```\n\nWhen you need metadata per test case on MSTest 3.8+, use `TestDataRow\u003CT>`:\n\n```csharp\npublic static IEnumerable\u003CTestDataRow\u003C(decimal price, int percent, decimal expected)>> DiscountTestDataWithMetadata =>\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```\n\n### Step 5: Handle test lifecycle correctly\n\n- Prefer constructor initialization when the existing suite supports it; retain a shared `FixtureBase\u003CTSut>` or established `[TestInitialize]` lifecycle rather than rewriting the fixture architecture incidentally.\n- Use `[TestInitialize]` **only** for async initialization, combined with the constructor for sync parts\n- Use `[TestCleanup]` for cleanup that must run even on failure\n- Inject `TestContext` via constructor only on MSTest 3.6+; otherwise use the instance property.\n\n```csharp\n[TestClass]\npublic sealed class RepositoryTests\n{\n    private readonly TestContext _testContext;\n    private readonly FakeDatabase _db;  \u002F\u002F readonly -- guaranteed by constructor\n\n    public RepositoryTests(TestContext testContext)\n    {\n        _testContext = testContext;\n        _db = new FakeDatabase();  \u002F\u002F sync init in ctor\n    }\n\n    [TestInitialize]\n    public async Task InitAsync()\n    {\n        \u002F\u002F Use TestInitialize ONLY for async setup\n        await _db.SeedAsync();\n    }\n\n    [TestCleanup]\n    public void Cleanup() => _db.Reset();\n}\n```\n\n#### Execution order\n\n1. `[AssemblyInitialize]` -- once per assembly\n2. `[ClassInitialize]` -- once per class\n3. Per test:\n   - With `TestContext` property injection: Constructor -> set `TestContext` property -> `[TestInitialize]`\n   - With constructor injection of `TestContext`: Constructor (receives `TestContext`) -> `[TestInitialize]`\n4. Test method\n5. `[TestCleanup]` -> `DisposeAsync` -> `Dispose` -- per test\n6. `[ClassCleanup]` -- once per class\n7. `[AssemblyCleanup]` -- once per assembly\n\n### Step 6: Apply cancellation and timeout patterns\n\nUse `TestContext.CancellationToken` with\n`[Timeout(milliseconds, CooperativeCancellation = true)]` when the installed\nMSTest version exposes the token directly (3.11+). On MSTest 3.6.4-3.10, use\n`TestContext.CancellationTokenSource.Token` with cooperative cancellation\ninstead. A plain `[Timeout]` does not establish that the framework token will\nstop in-flight work. On older versions, use a test-owned\n`CancellationTokenSource` where cancellation itself is under test.\n\n```csharp\n\u002F\u002F MSTest 3.11+\n[TestMethod]\n[Timeout(5000, CooperativeCancellation = true)]\npublic async Task FetchData_ReturnsWithinTimeout()\n{\n    var result = await _client.GetDataAsync(_testContext.CancellationToken);\n    Assert.IsNotNull(result);\n}\n```\n\n### Step 7: Use advanced features where appropriate\n\n#### Retry flaky tests (MSTest 3.8+)\n\nUse only for genuinely flaky external dependencies (network, file system), not to paper over race conditions or shared state issues.\nFor an external service, use bounded attempts plus a nonzero delay\u002Fbackoff so\nthe retry policy does not immediately hammer the same dependency:\n\n```csharp\n[TestMethod]\n[Retry(\n    3,\n    MillisecondsDelayBetweenRetries = 1_000,\n    BackoffType = DelayBackoffType.Exponential)]\npublic async Task ExternalService_EventuallyResponds()\n{\n    var response = await WeatherClient.GetAsync();\n    Assert.IsNotNull(response);\n}\n```\n\n#### Conditional execution\n\n`OSCondition` requires MSTest 3.8+; `CICondition` requires MSTest 3.10+.\n\n```csharp\n[TestMethod]\n[OSCondition(OperatingSystems.Windows)]\npublic void WindowsRegistry_ReadsValue() { }\n\n[TestMethod]\n[CICondition(ConditionMode.Exclude)]\npublic void LocalOnly_InteractiveTest() { }\n```\n\nAttributes replace environment branches in test bodies; they do not replace\nthe operation being tested. When correcting supplied code, retain the real\nregistry\u002FGPU\u002Fservice operation and concrete resource cleanup rather than\nreturning empty methods or comment-only placeholders.\nShow cleanup state initialized safely and released symmetrically (including a\nnull guard when setup can fail). A policy-only sketch that omits the operation,\nassertion, or cleanup body is incomplete.\n\n#### Parallelization\n\n```csharp\n[assembly: Parallelize(Workers = 4, Scope = ExecutionScope.MethodLevel)]\n\n[TestClass]\n[DoNotParallelize]  \u002F\u002F Opt out specific classes\npublic sealed class DatabaseIntegrationTests { }\n```\n\n### Step 8: Fix MSTest analyzer diagnostics (MSTESTxxxx)\n\nThe `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.\n\nWhen 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: \u003Chttps:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Ftesting\u002Fmstest-analyzers\u002Foverview>.\n\n#### Common diagnostics and their fixes\n\n| Rule | Problem | Fix |\n|---|---|---|\n| MSTEST0006 | `[ExpectedException]` used | On 3.8+, replace with `Assert.Throws\u003CT>` \u002F `Assert.ThrowsExactly\u003CT>`; otherwise use `Assert.ThrowsException\u003CT>` |\n| MSTEST0017 | `Assert.AreEqual` args swapped | Put `expected` first, `actual` second |\n| MSTEST0023 | Negated boolean assertion (`Assert.IsTrue(!x)`) | Use `Assert.IsFalse(x)` |\n| MSTEST0025 | Always-false condition asserted | Use `Assert.Fail(\"reason\")` |\n| MSTEST0032 | Always-true assert condition | Remove or correct the assertion |\n| MSTEST0037 | Sub-optimal assert (`IsTrue(x == null)`) | Use the specific assert (`Assert.IsNull`, `HasCount`, etc.) (Step 3) |\n| MSTEST0038 | `Assert.AreSame` on value types | Use `Assert.AreEqual` (value types box to distinct references) |\n| MSTEST0039 | Legacy `Assert.ThrowsException` | On 3.8+, use `Assert.Throws` \u002F `Assert.ThrowsExactly` (+ `Async` variants) |\n| MSTEST0044 | `[DataTestMethod]` used | Replace with `[TestMethod]` only on a version where it supports data rows |\n| MSTEST0046 | `StringAssert` used | On 3.10+, use the equivalent `Assert` method (`Assert.Contains`, `StartsWith`, ...) |\n| MSTEST0052 | Explicit `DynamicDataSourceType` | Drop it — the source type is inferred |\n| MSTEST0042 \u002F MSTEST0060 | Duplicate `[DataRow]` \u002F `[TestMethod]` | Remove the duplicate attribute |\n| MSTEST0024 | Static `TestContext` field | Make it an instance member (Step 5) |\n| MSTEST0045 \u002F MSTEST0049 \u002F MSTEST0054 | Timeout\u002Ftoken not cooperative | Flow `TestContext.CancellationToken` into the awaited call (Step 6) |\n| MSTEST0036 | Member shadows a base test member | Rename or use `override` instead of `new` |\n| MSTEST0061 | Runtime OS check inside a test | Use `[OSCondition(...)]` (Step 7) |\n| MSTEST0002 \u002F MSTEST0003 \u002F MSTEST0005 \u002F MSTEST0007–0014 | Invalid test class \u002F method \u002F fixture \u002F `TestContext` \u002F data-source layout | Correct the signature named by the rule (e.g. make it public, fix the return type and parameters, add `static` where required) |\n\n#### Tuning which rules are enforced\n\nUse the `MSTestAnalysisMode` MSBuild property (MSTest 3.8+) to control the rule set globally:\n\n```xml\n\u003CPropertyGroup>\n  \u003C!-- None | Default | Recommended | All -->\n  \u003CMSTestAnalysisMode>Recommended\u003C\u002FMSTestAnalysisMode>\n\u003C\u002FPropertyGroup>\n```\n\n- `Recommended` escalates info-level rules to warnings and is the mode most projects should adopt.\n- 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.\n- Prefer fixing the underlying code over suppressing a diagnostic. Suppress only with a documented justification.\n\n### Step 9: Verify file-backed corrections\n\nWhen the user asked for repository edits and did not prohibit execution, run the\nnarrowest affected `dotnet test` command after editing. A successful process with\nno discovered-test count is not verification. Require the intended test cases to\nbe discovered and pass.\n\nIf compilation exposes a directly coupled source issue that prevents the\ncorrected existing suite from running (for example, a missing namespace import\nin the supplied production file), make only that minimum fix and rerun. Do not\nupgrade packages or broaden the modernization. Report the actual test count and\nthe fixes made; never present unrun or output-free tests as passing.\nIn the final handoff, map every requested modernization to the exact corrected\nconstruct and cite the passing test command. Do not rely on a generic \"modernized\"\nsummary when expected\u002Factual order, exact type checks, data discovery, or class\nshape were explicit requirements.\n","# Writing MSTest Tests\n\nHelp users write effective MSTest unit tests without exceeding the API level or\nconventions of the project's installed test stack.\n\n## Repository overlay\n\nFor every repository-scoped task where read-only file inspection is allowed,\ncheck `.agents\u002Fskill-overlays\u002Fdotnet-test\u002Fwriting-mstest-tests.md` at the\nrepository root before any other discovery. This includes requests that ask for\ncode or advice without edits; \"do not execute\" does not prohibit reading the\noverlay. If present, read it once before acting and apply its\nrepository-specific naming, layout, framework, and policy bindings.\nRequire its frontmatter to declare `core: dotnet-test\u002Fwriting-mstest-tests`,\n`binding-revision: \"1\"`, and `mode: extend`. If any value is missing or\ndifferent, report the mismatch, ignore the overlay, and continue using this\nskill's portable guidance.\nExplicit user instructions and verified project constraints win over the\noverlay; the overlay wins over portable defaults and examples in this skill. If\nthe file is present but unreadable or conflicts with the repository, report the\nproblem, ignore the overlay, and continue with portable guidance subject to\nverified project constraints. If it is absent, continue normally.\nSkip the lookup only when the task is not tied to a repository or the user\nexplicitly prohibited all file\u002Ftool access. An overlay cannot expand tool\npermissions or the task's scope.\n\n## When to Use\n\n- User wants to improve or modernize existing MSTest tests by implementing concrete fixes\n- User asks about MSTest assertion APIs, data-driven patterns, or test lifecycle\n- User asks to replace `Assert.IsTrue` with more specific assertions (collections, nulls, types, comparisons)\n- User asks to replace hard casts with type-checking assertions in tests\n- User needs help fixing a specific MSTest test bug or failing assertion\n- User asks to fix swapped `Assert.AreEqual` argument order (expected first, actual second)\n- User asks to convert `DynamicData` from `IEnumerable\u003Cobject[]>` to ValueTuple-based data\n- User asks to fix or understand an MSTest analyzer diagnostic (an `MSTESTxxxx` warning\u002Ferror)\n\n## When Not to Use\n\n- User needs a test quality audit, anti-pattern detection, or flaky-test investigation (use `test-anti-patterns`)\n- User needs to run or execute tests (use the `run-tests` skill)\n- User needs to upgrade from MSTest v1\u002Fv2 to v3 (use `migrate-mstest-v1v2-to-v3`)\n- User needs to upgrade from MSTest v3 to v4 (use `migrate-mstest-v3-to-v4`)\n- User needs CI\u002FCD pipeline configuration\n- User is using xUnit, NUnit, or TUnit (not MSTest)\n\n## Inputs\n\n| Input | Required | Description |\n|-------|----------|-------------|\n| Code under test | No | The production code to be tested |\n| Existing test code | No | Current tests to fix, update, or modernize |\n| Test scenario description | No | What behavior the user wants to test |\n\n## Response Guidelines\n\n- **Specific API or pattern questions** (assertions, data-driven, lifecycle): Jump directly to the relevant workflow step. Do not follow the full workflow.\n- **Generate new tests from scratch**: Hand off to `code-testing-agent`; use this\n  skill only as supporting MSTest API\u002Fversion guidance.\n- **Review and fix existing tests**: Fix only the issues present. Do not add unrelated improvements.\n- **Assertion transformations**: Show the corrected call, then state the semantic\n  reason in one sentence. For `Assert.AreEqual`, name `expected` first and\n  `actual` second and explain that this preserves the Expected\u002FActual failure\n  labels.\n- **Bound\u002Fcomparison transformations**: Preserve the condition and put the\n  expected bound(s) first and the observed value last:\n  `score > 0` -> `Assert.IsGreaterThan(0, score)`,\n  `score \u003C 100` -> `Assert.IsLessThan(100, score)`, and\n  `score >= 60 && score \u003C= 90` -> `Assert.IsInRange(60, 90, score)`.\n  Never reverse these arguments to mimic the source expression's left-to-right\n  order.\n- **Exception transformations**: Scope the throwing operation in a lambda,\n  distinguish `ThrowsExactly\u003CT>` (exact type) from `Throws\u003CT>` (type or derived\n  type), and capture the returned exception when properties such as `ParamName`\n  are part of the behavior.\n- **Supplied code requests**: Return complete representative method bodies, not\n  comment-only placeholders. Preserve the real operation and show symmetric\n  setup\u002Fcleanup when lifecycle or environment policy is part of the request.\n\n## Workflow\n\n### Step 1: Determine project setup\n\nCheck the test project, `packages.config`, and assembly reference `HintPath`\nvalues for the exact MSTest version and project system:\n\n- If using `MSTest.Sdk`: resolve its exact version from the project SDK\n  declaration or `global.json` `msbuild-sdks`; do not assume the latest APIs\n- If using `MSTest` metapackage: resolve its exact package version\n- If using `MSTest.TestFramework` + `MSTest.TestAdapter`: check version for feature availability\n- If using classic non-SDK XML (`ToolsVersion`, `Microsoft.CSharp.targets`,\n  explicit `\u003CCompile Include>`) and\u002For `packages.config`: preserve that project\n  system and add each new test file to `\u003CCompile Include>`.\n\nAlso 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.\n\n### MSTest API availability\n\n| API\u002Fpattern | Minimum version | Compatible fallback |\n|---|---:|---|\n| `Assert.ThrowsExactly*`, unified `Assert.Contains` \u002F `HasCount` \u002F `IsEmpty` \u002F `IsNotEmpty` | 3.8 | `Assert.ThrowsException*`, `CollectionAssert`, `StringAssert` |\n| `Assert.IsGreaterThan`, `IsLessThan`, `IsInRange`, `StartsWith`, `EndsWith`, `MatchesRegex` | 3.10 | `Assert.IsTrue` with a clear message, or `StringAssert` |\n| Generic `Assert.IsInstanceOfType\u003CT>(value, out var typed)` | 3.4-3.11 only | Non-generic assertion then post-assert cast on 3.0-3.3; v4 returns the typed value directly |\n| ValueTuple `DynamicData` | 3.7 | `IEnumerable\u003Cobject[]>` |\n| Constructor injection of `TestContext` | 3.6 | Instance `TestContext` property |\n| `[Retry]`, `[OSCondition]` | 3.8 | No built-in retry\u002FOS condition; fix flakiness or retain the existing condition mechanism |\n| `[CICondition]` | 3.10 | Existing project-specific condition mechanism |\n\nFor example, MSTest 3.5.x must not receive `Assert.ThrowsExactly`,\n`Assert.Contains`, ValueTuple `DynamicData`, or constructor-injected\n`TestContext`.\n\nTreat this as a hard gate: after determining the version, do not copy a later\nexample from this skill unless its minimum version is satisfied.\n\nRecommend MSTest.Sdk or the MSTest metapackage only for genuinely new projects:\n\n```xml\n\u003C!-- Option 1: MSTest SDK (simplest, recommended for new projects) -->\n\u003CProject Sdk=\"MSTest.Sdk\">\n  \u003CPropertyGroup>\n    \u003CTargetFramework>net9.0\u003C\u002FTargetFramework>\n  \u003C\u002FPropertyGroup>\n\u003C\u002FProject>\n```\n\nWhen using `MSTest.Sdk`, put the version in `global.json` instead of the project file so all test projects get bumped together:\n\n```json\n{\n  \"msbuild-sdks\": {\n    \"MSTest.Sdk\": \"3.8.2\"\n  }\n}\n```\n\n```xml\n\u003C!-- Option 2: MSTest metapackage -->\n\u003CProject Sdk=\"Microsoft.NET.Sdk\">\n  \u003CPropertyGroup>\n    \u003CTargetFramework>net9.0\u003C\u002FTargetFramework>\n  \u003C\u002FPropertyGroup>\n  \u003CItemGroup>\n    \u003CPackageReference Include=\"MSTest\" Version=\"3.8.2\" \u002F>\n  \u003C\u002FItemGroup>\n\u003C\u002FProject>\n```\n\n### Step 2: Write test classes following conventions\n\nApply these structural conventions only where they do not conflict with the\nsuite's established base classes and lifecycle:\n\n- **Seal test classes** with `sealed` for performance and design clarity\n- Use `[TestClass]` on the class and `[TestMethod]` on test methods\n- Follow the **Arrange-Act-Assert** (AAA) pattern\n- Name tests using `MethodName_Scenario_ExpectedBehavior`\n- Use separate test projects with naming convention `[ProjectName].Tests`\n\n```csharp\n[TestClass]\npublic sealed class OrderServiceTests\n{\n    [TestMethod]\n    public void CalculateTotal_WithDiscount_ReturnsReducedPrice()\n    {\n        \u002F\u002F Arrange\n        var service = new OrderService();\n        var order = new Order { Price = 100m, DiscountPercent = 10 };\n\n        \u002F\u002F Act\n        var total = service.CalculateTotal(order);\n\n        \u002F\u002F Assert\n        Assert.AreEqual(90m, total);\n    }\n}\n```\n\n### Step 3: Use version-compatible assertion APIs\n\nPick 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`StringAssert`, `CollectionAssert`, or `Assert.IsTrue` calls.\n\n| What you are testing | Assertion |\n|---|---|\n| Two values are equal | `Assert.AreEqual(expected, actual)` |\n| Same object instance (reference identity) | `Assert.AreSame(expected, actual)` |\n| Value is null | `Assert.IsNull(value)` |\n| Value is not null | `Assert.IsNotNull(value)` |\n| Collection is empty | `Assert.IsEmpty(collection)` (3.8+) or `CollectionAssert` \u002F count assertion |\n| Collection is not empty | `Assert.IsNotEmpty(collection)` (3.8+) or count assertion |\n| Collection has exactly N items | `Assert.HasCount(N, collection)` (3.8+) or `Assert.AreEqual` on count |\n| Collection contains an item | `Assert.Contains(item, collection)` (3.8+) or `CollectionAssert.Contains` |\n| Collection does not contain an item | `Assert.DoesNotContain(item, collection)` (3.8+) or `CollectionAssert.DoesNotContain` |\n| Object is a specific type | `Assert.IsInstanceOfType\u003CT>(value)` |\n| Code throws an exception | `Assert.ThrowsExactly\u003CT>` (3.8+) or `Assert.ThrowsException\u003CT>` (earlier) |\n\nOn MSTest 3.8+, prefer `Assert` class methods over `StringAssert` or\n`CollectionAssert` where both exist. Older versions should keep the compatible\nspecialized classes.\nWhen several independent collection properties were requested, keep each\nsemantic check explicit even if another assertion happens to imply it. For\nexample, retain `IsNotEmpty` when the requested diagnostics distinguish\nempty\u002Fnon-empty, then use `HasCount` and `ContainsSingle` for their separate\ncardinality guarantees.\n\n#### Equality, null, and reference checks\n\n```csharp\nAssert.AreEqual(expected, actual);      \u002F\u002F Value equality\nAssert.AreSame(expected, actual);       \u002F\u002F Reference equality -- same object instance\nAssert.IsNull(value);\nAssert.IsNotNull(value);\n```\n\n#### Exception testing\n\n```csharp\n\u002F\u002F MSTest 3.8+\nvar ex = Assert.ThrowsExactly\u003CArgumentNullException>(() => service.Process(null));\nAssert.AreEqual(\"input\", ex.ParamName);\n\n\u002F\u002F Async\nvar ex = await Assert.ThrowsExactlyAsync\u003CInvalidOperationException>(\n    async () => await service.ProcessAsync(null));\n```\n\n- `Assert.Throws\u003CT>` matches `T` or any derived type\n- `Assert.ThrowsExactly\u003CT>` matches only the exact type `T`\n\nOn MSTest 3.7 and earlier, use the compatible API:\n\n```csharp\nvar ex = Assert.ThrowsException\u003CArgumentNullException>(\n    () => service.Process(null));\n```\n\n#### Collection assertions\n\n```csharp\n\u002F\u002F MSTest 3.8+\nAssert.Contains(expectedItem, collection);\nAssert.DoesNotContain(unexpectedItem, collection);\nvar single = Assert.ContainsSingle(collection);  \u002F\u002F Returns the single element\nAssert.HasCount(3, collection);\nAssert.IsEmpty(collection);\nAssert.IsNotEmpty(collection);\n```\n\nOn earlier versions use `CollectionAssert.Contains`,\n`CollectionAssert.DoesNotContain`, and `Assert.AreEqual(expectedCount,\ncollection.Count)`.\n\nReplace generic `Assert.IsTrue` with specialized assertions -- they give better failure messages:\n\n| Instead of | Use |\n|---|---|\n| `Assert.IsTrue(list.Count > 0)` | `Assert.IsNotEmpty(list)` |\n| `Assert.IsTrue(list.Count == 0)` | `Assert.IsEmpty(list)` |\n| `Assert.IsTrue(list.Count() == 3)` | `Assert.HasCount(3, list)` |\n| `Assert.IsTrue(x != null)` | `Assert.IsNotNull(x)` |\n| `Assert.IsTrue(x == null)` | `Assert.IsNull(x)` |\n| `Assert.AreEqual(a, b)` for same instance | `Assert.AreSame(a, b)` -- reference identity |\n| `Assert.IsTrue(!list.Contains(item))` | `Assert.DoesNotContain(item, list)` |\n| `list.Single(predicate)` + `Assert.IsNotNull` | `Assert.ContainsSingle(list)` |\n| `Assert.IsTrue(list.Contains(item))` | `Assert.Contains(item, list)` |\n\n#### String assertions\n\n```csharp\n\u002F\u002F MSTest 3.10+\nAssert.Contains(\"expected\", actualString);\nAssert.StartsWith(\"prefix\", actualString);\nAssert.EndsWith(\"suffix\", actualString);\nAssert.MatchesRegex(@\"\\d{3}-\\d{4}\", phoneNumber);\n```\n\nOn earlier versions use `StringAssert.Contains`, `StringAssert.StartsWith`,\n`StringAssert.EndsWith`, and `StringAssert.Matches`.\n\n#### Type assertions\n\nMSTest 3.x is not one API level. Pick the form supported by the installed\nminor version:\n\n```csharp\n\u002F\u002F MSTest 3.0-3.3\nAssert.IsInstanceOfType(result, typeof(MyHandler));\nvar typed = (MyHandler)result; \u002F\u002F Safe because the assertion stops a mismatch.\n```\n\n```csharp\n\u002F\u002F MSTest 3.4-3.11 -- out parameter\nAssert.IsInstanceOfType\u003CMyHandler>(result, out var typed);\ntyped.Handle();\n```\n\n```csharp\n\u002F\u002F MSTest 4.x -- returns the proven value directly\nvar typed = Assert.IsInstanceOfType\u003CMyHandler>(result);\n```\n\n#### Comparison assertions\n\n```csharp\nAssert.IsGreaterThan(lowerBound, actual);\nAssert.IsLessThan(upperBound, actual);\nAssert.IsInRange(low, high, actual);\n```\n\n### Step 4: Use data-driven tests for multiple inputs\n\n#### DataRow for inline values\n\n```csharp\n[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```\n\n#### DynamicData with ValueTuples (preferred for complex data)\n\nOn MSTest 3.7+, prefer `ValueTuple` return types over\n`IEnumerable\u003Cobject[]>` for type safety. Keep `IEnumerable\u003Cobject[]>` on older\nversions.\n\nTuple element names document which position maps to which test parameter, and\ntuple element types catch incompatible values at compile time. They do **not**\nmake `DynamicData` position-independent, and swapping two same-typed elements\ncan still compile. Do not claim otherwise. When rows need custom display names\nor metadata rather than only typed positional data, use `TestDataRow\u003CT>` on\nMSTest 3.8+.\n\n```csharp\n[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\u002F\u002F ValueTuple -- preferred (MSTest 3.7+)\npublic static IEnumerable\u003C(decimal price, int percent, decimal expected)> DiscountTestData =>\n[\n    (100m, 10, 90m),\n    (200m, 25, 150m),\n    (50m, 0, 50m),\n];\n```\n\nWhen you need metadata per test case on MSTest 3.8+, use `TestDataRow\u003CT>`:\n\n```csharp\npublic static IEnumerable\u003CTestDataRow\u003C(decimal price, int percent, decimal expected)>> DiscountTestDataWithMetadata =>\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```\n\n### Step 5: Handle test lifecycle correctly\n\n- Prefer constructor initialization when the existing suite supports it; retain a shared `FixtureBase\u003CTSut>` or established `[TestInitialize]` lifecycle rather than rewriting the fixture architecture incidentally.\n- Use `[TestInitialize]` **only** for async initialization, combined with the constructor for sync parts\n- Use `[TestCleanup]` for cleanup that must run even on failure\n- Inject `TestContext` via constructor only on MSTest 3.6+; otherwise use the instance property.\n\n```csharp\n[TestClass]\npublic sealed class RepositoryTests\n{\n    private readonly TestContext _testContext;\n    private readonly FakeDatabase _db;  \u002F\u002F readonly -- guaranteed by constructor\n\n    public RepositoryTests(TestContext testContext)\n    {\n        _testContext = testContext;\n        _db = new FakeDatabase();  \u002F\u002F sync init in ctor\n    }\n\n    [TestInitialize]\n    public async Task InitAsync()\n    {\n        \u002F\u002F Use TestInitialize ONLY for async setup\n        await _db.SeedAsync();\n    }\n\n    [TestCleanup]\n    public void Cleanup() => _db.Reset();\n}\n```\n\n#### Execution order\n\n1. `[AssemblyInitialize]` -- once per assembly\n2. `[ClassInitialize]` -- once per class\n3. Per test:\n   - With `TestContext` property injection: Constructor -> set `TestContext` property -> `[TestInitialize]`\n   - With constructor injection of `TestContext`: Constructor (receives `TestContext`) -> `[TestInitialize]`\n4. Test method\n5. `[TestCleanup]` -> `DisposeAsync` -> `Dispose` -- per test\n6. `[ClassCleanup]` -- once per class\n7. `[AssemblyCleanup]` -- once per assembly\n\n### Step 6: Apply cancellation and timeout patterns\n\nUse `TestContext.CancellationToken` with\n`[Timeout(milliseconds, CooperativeCancellation = true)]` when the installed\nMSTest version exposes the token directly (3.11+). On MSTest 3.6.4-3.10, use\n`TestContext.CancellationTokenSource.Token` with cooperative cancellation\ninstead. A plain `[Timeout]` does not establish that the framework token will\nstop in-flight work. On older versions, use a test-owned\n`CancellationTokenSource` where cancellation itself is under test.\n\n```csharp\n\u002F\u002F MSTest 3.11+\n[TestMethod]\n[Timeout(5000, CooperativeCancellation = true)]\npublic async Task FetchData_ReturnsWithinTimeout()\n{\n    var result = await _client.GetDataAsync(_testContext.CancellationToken);\n    Assert.IsNotNull(result);\n}\n```\n\n### Step 7: Use advanced features where appropriate\n\n#### Retry flaky tests (MSTest 3.8+)\n\nUse only for genuinely flaky external dependencies (network, file system), not to paper over race conditions or shared state issues.\nFor an external service, use bounded attempts plus a nonzero delay\u002Fbackoff so\nthe retry policy does not immediately hammer the same dependency:\n\n```csharp\n[TestMethod]\n[Retry(\n    3,\n    MillisecondsDelayBetweenRetries = 1_000,\n    BackoffType = DelayBackoffType.Exponential)]\npublic async Task ExternalService_EventuallyResponds()\n{\n    var response = await WeatherClient.GetAsync();\n    Assert.IsNotNull(response);\n}\n```\n\n#### Conditional execution\n\n`OSCondition` requires MSTest 3.8+; `CICondition` requires MSTest 3.10+.\n\n```csharp\n[TestMethod]\n[OSCondition(OperatingSystems.Windows)]\npublic void WindowsRegistry_ReadsValue() { }\n\n[TestMethod]\n[CICondition(ConditionMode.Exclude)]\npublic void LocalOnly_InteractiveTest() { }\n```\n\nAttributes replace environment branches in test bodies; they do not replace\nthe operation being tested. When correcting supplied code, retain the real\nregistry\u002FGPU\u002Fservice operation and concrete resource cleanup rather than\nreturning empty methods or comment-only placeholders.\nShow cleanup state initialized safely and released symmetrically (including a\nnull guard when setup can fail). A policy-only sketch that omits the operation,\nassertion, or cleanup body is incomplete.\n\n#### Parallelization\n\n```csharp\n[assembly: Parallelize(Workers = 4, Scope = ExecutionScope.MethodLevel)]\n\n[TestClass]\n[DoNotParallelize]  \u002F\u002F Opt out specific classes\npublic sealed class DatabaseIntegrationTests { }\n```\n\n### Step 8: Fix MSTest analyzer diagnostics (MSTESTxxxx)\n\nThe `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.\n\nWhen 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: \u003Chttps:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Ftesting\u002Fmstest-analyzers\u002Foverview>.\n\n#### Common diagnostics and their fixes\n\n| Rule | Problem | Fix |\n|---|---|---|\n| MSTEST0006 | `[ExpectedException]` used | On 3.8+, replace with `Assert.Throws\u003CT>` \u002F `Assert.ThrowsExactly\u003CT>`; otherwise use `Assert.ThrowsException\u003CT>` |\n| MSTEST0017 | `Assert.AreEqual` args swapped | Put `expected` first, `actual` second |\n| MSTEST0023 | Negated boolean assertion (`Assert.IsTrue(!x)`) | Use `Assert.IsFalse(x)` |\n| MSTEST0025 | Always-false condition asserted | Use `Assert.Fail(\"reason\")` |\n| MSTEST0032 | Always-true assert condition | Remove or correct the assertion |\n| MSTEST0037 | Sub-optimal assert (`IsTrue(x == null)`) | Use the specific assert (`Assert.IsNull`, `HasCount`, etc.) (Step 3) |\n| MSTEST0038 | `Assert.AreSame` on value types | Use `Assert.AreEqual` (value types box to distinct references) |\n| MSTEST0039 | Legacy `Assert.ThrowsException` | On 3.8+, use `Assert.Throws` \u002F `Assert.ThrowsExactly` (+ `Async` variants) |\n| MSTEST0044 | `[DataTestMethod]` used | Replace with `[TestMethod]` only on a version where it supports data rows |\n| MSTEST0046 | `StringAssert` used | On 3.10+, use the equivalent `Assert` method (`Assert.Contains`, `StartsWith`, ...) |\n| MSTEST0052 | Explicit `DynamicDataSourceType` | Drop it — the source type is inferred |\n| MSTEST0042 \u002F MSTEST0060 | Duplicate `[DataRow]` \u002F `[TestMethod]` | Remove the duplicate attribute |\n| MSTEST0024 | Static `TestContext` field | Make it an instance member (Step 5) |\n| MSTEST0045 \u002F MSTEST0049 \u002F MSTEST0054 | Timeout\u002Ftoken not cooperative | Flow `TestContext.CancellationToken` into the awaited call (Step 6) |\n| MSTEST0036 | Member shadows a base test member | Rename or use `override` instead of `new` |\n| MSTEST0061 | Runtime OS check inside a test | Use `[OSCondition(...)]` (Step 7) |\n| MSTEST0002 \u002F MSTEST0003 \u002F MSTEST0005 \u002F MSTEST0007–0014 | Invalid test class \u002F method \u002F fixture \u002F `TestContext` \u002F data-source layout | Correct the signature named by the rule (e.g. make it public, fix the return type and parameters, add `static` where required) |\n\n#### Tuning which rules are enforced\n\nUse the `MSTestAnalysisMode` MSBuild property (MSTest 3.8+) to control the rule set globally:\n\n```xml\n\u003CPropertyGroup>\n  \u003C!-- None | Default | Recommended | All -->\n  \u003CMSTestAnalysisMode>Recommended\u003C\u002FMSTestAnalysisMode>\n\u003C\u002FPropertyGroup>\n```\n\n- `Recommended` escalates info-level rules to warnings and is the mode most projects should adopt.\n- 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.\n- Prefer fixing the underlying code over suppressing a diagnostic. Suppress only with a documented justification.\n\n### Step 9: Verify file-backed corrections\n\nWhen the user asked for repository edits and did not prohibit execution, run the\nnarrowest affected `dotnet test` command after editing. A successful process with\nno discovered-test count is not verification. Require the intended test cases to\nbe discovered and pass.\n\nIf compilation exposes a directly coupled source issue that prevents the\ncorrected existing suite from running (for example, a missing namespace import\nin the supplied production file), make only that minimum fix and rerun. Do not\nupgrade packages or broaden the modernization. Report the actual test count and\nthe fixes made; never present unrun or output-free tests as passing.\nIn the final handoff, map every requested modernization to the exact corrected\nconstruct and cite the passing test command. Do not rely on a generic \"modernized\"\nsummary when expected\u002Factual order, exact type checks, data discovery, or class\nshape were explicit requirements.\n",{"name":5,"license":15,"metadata":24,"description":28},{"binding":25,"portability":26,"binding-revision":27},"optional-overlay","portable","1","ALWAYS USE when asked to fix, rewrite, update, improve, modernize, show corrected code for, or explain existing MSTest tests or MSTest-specific configuration. Use for \"review\" when corrected code or edits are wanted, even for one pasted assertion or passing tests with bad failure output. Covers expected\u002Factual labels; generic Boolean, collection, string, numeric, null, identity, exception, hard-cast, and object[] checks; TestContext\u002Flifecycle; timeout\u002Fcancellation; OS\u002FCI conditions, retry, cleanup, parallelization, MSTest.Sdk project setup, and MSTESTxxxx. Honor the installed MSTest version. DO NOT USE to design new test cases (code-testing-agent), perform report-only audits, create project files rather than explain MSTest setup, run tests, migrate frameworks, or handle non-MSTest\u002Fnon-.NET code.\n","main","30954af1dcd1a74b63f05deb2e2c41e5ecae4a82","13-Testing-QA\u002Fwriting-mstest-tests","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack","https:\u002F\u002Fgithub.com\u002Fitsmejay18","2026-09-18 16:06:36",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill writing-mstest-tests",{"tool":41,"command":42},"bunx","bunx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill writing-mstest-tests",{"tool":44,"command":45},"pnpm","pnpm dlx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill writing-mstest-tests","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F13-Testing-QA\u002Fwriting-mstest-tests\u002FSKILL.md",true,[],[50,57,64,71,78,85],{"skillNo":51,"name":52,"nameZh":6,"description":53,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":19},"01M7D2RKBHPZ3E1RNN5DWHT550","vectorization","Design, implement, optimize, and review SIMD code in .NET. USE FOR: vectorizing scalar loops with TensorPrimitives, Vector64\u002F128\u002F256\u002F512, or platform hardware intrinsics; reviewing existing SIMD code, including Vector\u003CT>, for contract equivalence, tail handling, memory safety, portability, fallbacks, and measured performance. DO NOT USE FOR: performance work unrelated to SIMD or vectorization.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fvectorization\u002FSKILL.md",[],[],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M7D2RDJ7RN3QK8GJR0QTER1D","resolve-project-references","Guide for interpreting ResolveProjectReferences time in MSBuild performance summaries. Activate when ResolveProjectReferences appears as the most expensive target and developers are trying to optimize it directly. Explains that the reported time includes wait time for dependent project builds and is misleading. Guides users to focus on task self-time instead. Do not activate for general build performance -- use build-perf-diagnostics instead.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fresolve-project-references\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7D2R1H2GTNZYHG9YRX3JDQW","optimizing-ef-core-queries","Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster. Use whenever an EF Core or DbContext query or data-access path is slow or should be made faster — whether or not EF Core owns the database schema. For EF Core, not Dapper or raw ADO.NET.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Foptimizing-ef-core-queries\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7D2QREG04W1YT0NEBHEW5C9","microbenchmarking","Activate this skill when BenchmarkDotNet (BDN) is involved in the task — creating, running, configuring, or reviewing BDN benchmarks. Also activate when microbenchmarking .NET code would be useful and BenchmarkDotNet is the likely tool. Consider activating when answering a .NET performance question requires measurement and BenchmarkDotNet may be needed. Covers microbenchmark design, BDN configuration and project setup, how to run BDN microbenchmarks efficiently and effectively, and using BDN for side-by-side performance comparisons. Do NOT use for profiling\u002Ftracing .NET code (dotnet-trace, PerfView), production telemetry, or load\u002Fstress testing (Crank, k6).","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fmicrobenchmarking\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M7D2QGE175XWPZVACVH2868Z","incremental-build","Guide for optimizing MSBuild incremental builds. USE FOR: builds slower than expected on subsequent runs, 'nothing changed but it rebuilds anyway', diagnosing why targets re-execute unnecessarily, fixing broken no-op builds. Covers 8 common causes: missing Inputs\u002FOutputs on custom targets, volatile properties in output paths (timestamps\u002FGUIDs), file writes outside tracked Outputs, missing FileWrites registration, glob changes, Visual Studio Fast Up-to-Date Check (FUTDC) issues. Key diagnostic: look for 'Building target completely' vs 'Skipping target' in binlog. DO NOT USE FOR: first-time build slowness (use build-perf-baseline), parallelism issues (use build-parallelism), evaluation-phase slowness (use eval-performance), non-MSBuild build systems.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fincremental-build\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M7D2Q1DQTC6K49R73WQTTPSB","eval-performance","Guide for diagnosing and improving MSBuild project evaluation performance. USE FOR: builds slow before any compilation starts, high evaluation time in binlog analysis, expensive glob patterns walking large directories (node_modules, .git, bin\u002Fobj), deep import chains (>20 levels), preprocessed output >10K lines indicating heavy evaluation, property functions with file I\u002FO ($([System.IO.File]::ReadAllText(...))), multiple evaluations per project. Covers the 5 MSBuild evaluation phases, glob optimization via DefaultItemExcludes, import chain analysis with \u002Fpp preprocessing. DO NOT USE FOR: compilation-time slowness (use build-perf-diagnostics), incremental build issues (use incremental-build), non-MSBuild build systems.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Feval-performance\u002FSKILL.md",[],[]]