[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76SF2T2YTRA5GZH3SHG7Y7F":3,"skill-same:01M76SF2T2YTRA5GZH3SHG7Y7F":46},{"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":25,"commitSha":26,"skillDirectory":27,"forksCount":14,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M76SF2T2YTRA5GZH3SHG7Y7F","writing-mstest-tests",null,"Write new MSTest unit tests and implement concrete fixes in existing MSTest code using MSTest 3.x\u002F4.x modern APIs and best practices. USE FOR: write unit tests for a class, write MSTest tests, create test class, fix test assertions, MSTest assertion APIs (StartsWith, EndsWith, MatchesRegex, IsGreaterThan, IsInRange, HasCount, IsNull), something seems off with my tests, review tests and fix issues, fix swapped Assert.AreEqual arguments, replace ExpectedException with Assert.Throws, modernize test patterns, convert DynamicData to ValueTuples, data-driven tests, test lifecycle setup, sealed test classes, async test patterns, cancellation token testing, test parallelization, Parallelize, DoNotParallelize, MSTest.Sdk project setup. DO NOT USE FOR: broad test quality audits or test smell detection (use test-anti-patterns), running tests (use run-tests), MSTest version migration (use migrate-mstest-v1v2-to-v3 or migrate-mstest-v3-to-v4).","weiflycc-cmd\u002Fskills","weiflycc-cmd","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F250846518?v=4","01M756C4PFGZJWKK04WFB9S5XF","威飛工作室","01M756C4QJJ66QDXN2RN6SXY87",0,"MIT","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-test\u002Fskills\u002Fwriting-mstest-tests\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: writing-mstest-tests\ndescription: >\n  Write new MSTest unit tests and implement concrete fixes in existing MSTest code using\n  MSTest 3.x\u002F4.x modern APIs and best practices.\n  USE FOR: write unit tests for a class, write MSTest tests, create test class,\n  fix test assertions, MSTest assertion APIs (StartsWith, EndsWith, MatchesRegex,\n  IsGreaterThan, IsInRange, HasCount, IsNull), something seems off with my tests,\n  review tests and fix issues,\n  fix swapped Assert.AreEqual arguments, replace ExpectedException with Assert.Throws, modernize\n  test patterns, convert DynamicData to ValueTuples, data-driven tests, test lifecycle setup,\n  sealed test classes, async test patterns, cancellation token testing,\n  test parallelization, Parallelize, DoNotParallelize, MSTest.Sdk project setup.\n  DO NOT USE FOR: broad test quality audits or test smell detection (use test-anti-patterns),\n  running tests (use run-tests), MSTest version migration (use migrate-mstest-v1v2-to-v3 or\n  migrate-mstest-v3-to-v4).\nlicense: MIT\n---\n\n# Writing MSTest Tests\n\nHelp users write effective, modern unit tests with MSTest 3.x\u002F4.x using current APIs and best practices.\n\n## When to Use\n\n- User wants to write new MSTest unit tests\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\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- **Write new tests from scratch**: Follow the full workflow.\n- **Review and fix existing tests**: Fix only the issues present. Do not add unrelated improvements.\n\n## Workflow\n\n### Step 1: Determine project setup\n\nCheck the test project for MSTest version and configuration:\n\n- If using `MSTest.Sdk` (`\u003CSdk Name=\"MSTest.Sdk\">`): modern setup, all features available\n- If using `MSTest` metapackage: modern setup (MSTest 3.x+)\n- If using `MSTest.TestFramework` + `MSTest.TestAdapter`: check version for feature availability\n\nRecommend MSTest.Sdk or the MSTest metapackage for 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:\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 modern assertion APIs\n\nPick the most specific assertion for each test scenario. More specific assertions produce better failure messages and make the test's intent clear:\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)` |\n| Collection is not empty | `Assert.IsNotEmpty(collection)` |\n| Collection has exactly N items | `Assert.HasCount(N, collection)` |\n| Collection contains an item | `Assert.Contains(item, collection)` |\n| Collection does not contain an item | `Assert.DoesNotContain(item, collection)` |\n| Object is a specific type | `Assert.IsInstanceOfType\u003CT>(value)` |\n| Code throws an exception | `Assert.ThrowsExactly\u003CT>(() => ...)` |\n\nPrefer `Assert` class methods over `StringAssert` or `CollectionAssert` where both exist.\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 -- use `Assert.Throws` instead of `[ExpectedException]`\n\n```csharp\n\u002F\u002F Synchronous\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\n#### Collection assertions\n\n```csharp\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\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\nAssert.Contains(\"expected\", actualString);\nAssert.StartsWith(\"prefix\", actualString);\nAssert.EndsWith(\"suffix\", actualString);\nAssert.MatchesRegex(@\"\\d{3}-\\d{4}\", phoneNumber);\n```\n\n#### Type assertions\n\n```csharp\n\u002F\u002F MSTest 3.x -- out parameter\nAssert.IsInstanceOfType\u003CMyHandler>(result, out var typed);\ntyped.Handle();\n\n\u002F\u002F MSTest 4.x -- returns 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(actual, low, high);\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\nPrefer `ValueTuple` return types over `IEnumerable\u003Cobject[]>` for type safety:\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, 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- **Always initialize in the constructor** -- this enables `readonly` fields and works correctly with nullability analyzers (fields are guaranteed non-null after construction)\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 (MSTest 3.6+)\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\nAlways use `TestContext.CancellationToken` with `[Timeout]`:\n\n```csharp\n[TestMethod]\n[Timeout(5000)]\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.9+)\n\nUse only for genuinely flaky external dependencies (network, file system), not to paper over race conditions or shared state issues.\n\n```csharp\n[TestMethod]\n[Retry(3)]\npublic void ExternalService_EventuallyResponds() { }\n```\n\n#### Conditional execution (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\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","# Writing MSTest Tests\n\nHelp users write effective, modern unit tests with MSTest 3.x\u002F4.x using current APIs and best practices.\n\n## When to Use\n\n- User wants to write new MSTest unit tests\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\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- **Write new tests from scratch**: Follow the full workflow.\n- **Review and fix existing tests**: Fix only the issues present. Do not add unrelated improvements.\n\n## Workflow\n\n### Step 1: Determine project setup\n\nCheck the test project for MSTest version and configuration:\n\n- If using `MSTest.Sdk` (`\u003CSdk Name=\"MSTest.Sdk\">`): modern setup, all features available\n- If using `MSTest` metapackage: modern setup (MSTest 3.x+)\n- If using `MSTest.TestFramework` + `MSTest.TestAdapter`: check version for feature availability\n\nRecommend MSTest.Sdk or the MSTest metapackage for 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:\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 modern assertion APIs\n\nPick the most specific assertion for each test scenario. More specific assertions produce better failure messages and make the test's intent clear:\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)` |\n| Collection is not empty | `Assert.IsNotEmpty(collection)` |\n| Collection has exactly N items | `Assert.HasCount(N, collection)` |\n| Collection contains an item | `Assert.Contains(item, collection)` |\n| Collection does not contain an item | `Assert.DoesNotContain(item, collection)` |\n| Object is a specific type | `Assert.IsInstanceOfType\u003CT>(value)` |\n| Code throws an exception | `Assert.ThrowsExactly\u003CT>(() => ...)` |\n\nPrefer `Assert` class methods over `StringAssert` or `CollectionAssert` where both exist.\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 -- use `Assert.Throws` instead of `[ExpectedException]`\n\n```csharp\n\u002F\u002F Synchronous\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\n#### Collection assertions\n\n```csharp\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\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\nAssert.Contains(\"expected\", actualString);\nAssert.StartsWith(\"prefix\", actualString);\nAssert.EndsWith(\"suffix\", actualString);\nAssert.MatchesRegex(@\"\\d{3}-\\d{4}\", phoneNumber);\n```\n\n#### Type assertions\n\n```csharp\n\u002F\u002F MSTest 3.x -- out parameter\nAssert.IsInstanceOfType\u003CMyHandler>(result, out var typed);\ntyped.Handle();\n\n\u002F\u002F MSTest 4.x -- returns 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(actual, low, high);\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\nPrefer `ValueTuple` return types over `IEnumerable\u003Cobject[]>` for type safety:\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, 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- **Always initialize in the constructor** -- this enables `readonly` fields and works correctly with nullability analyzers (fields are guaranteed non-null after construction)\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 (MSTest 3.6+)\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\nAlways use `TestContext.CancellationToken` with `[Timeout]`:\n\n```csharp\n[TestMethod]\n[Timeout(5000)]\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.9+)\n\nUse only for genuinely flaky external dependencies (network, file system), not to paper over race conditions or shared state issues.\n\n```csharp\n[TestMethod]\n[Retry(3)]\npublic void ExternalService_EventuallyResponds() { }\n```\n\n#### Conditional execution (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\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",{"name":5,"license":15,"description":24},"Write new MSTest unit tests and implement concrete fixes in existing MSTest code using MSTest 3.x\u002F4.x modern APIs and best practices. USE FOR: write unit tests for a class, write MSTest tests, create test class, fix test assertions, MSTest assertion APIs (StartsWith, EndsWith, MatchesRegex, IsGreaterThan, IsInRange, HasCount, IsNull), something seems off with my tests, review tests and fix issues, fix swapped Assert.AreEqual arguments, replace ExpectedException with Assert.Throws, modernize test patterns, convert DynamicData to ValueTuples, data-driven tests, test lifecycle setup, sealed test classes, async test patterns, cancellation token testing, test parallelization, Parallelize, DoNotParallelize, MSTest.Sdk project setup. DO NOT USE FOR: broad test quality audits or test smell detection (use test-anti-patterns), running tests (use run-tests), MSTest version migration (use migrate-mstest-v1v2-to-v3 or migrate-mstest-v3-to-v4).\n","main","5810d492c9b301d8227f932bf87b5c954c4fa4d6","plugins\u002Fdotnet-test\u002Fskills\u002Fwriting-mstest-tests","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd","weiflycc.com","2026-11-10 03:26:55",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add weiflycc-cmd\u002Fskills --skill writing-mstest-tests",{"tool":38,"command":39},"bunx","bunx skills add weiflycc-cmd\u002Fskills --skill writing-mstest-tests",{"tool":41,"command":42},"pnpm","pnpm dlx skills add weiflycc-cmd\u002Fskills --skill writing-mstest-tests","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-test\u002Fskills\u002Fwriting-mstest-tests\u002FSKILL.md",true,[],[47,54,61,68,75,82],{"skillNo":48,"name":49,"nameZh":6,"description":50,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":51,"categories":52,"keywords":53,"publishedAt":19},"01M76SGT4WG5682JQJ0V3NSK6X","system-text-json-net11","Provides guidance on new System.Text.Json APIs introduced in .NET 11. It covers typed JsonTypeInfo access via GetTypeInfo\u003CT> and TryGetTypeInfo\u003CT> on JsonSerializerOptions, and the new JsonNamingPolicy.PascalCase static property. Use when serializing or deserializing JSON in .NET 11 applications and needing typed metadata access or PascalCase property naming.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet11\u002Fskills\u002Fsystem-text-json-net11\u002FSKILL.md",[],[],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M76SGPNZYYV9BCZJW7BF7J8A","nuget-trusted-publishing","Set up NuGet trusted publishing (OIDC) on a GitHub Actions repo — replaces long-lived API keys with short-lived tokens. USE FOR: trusted publishing, NuGet OIDC, keyless NuGet publish, migrate from NuGet API key, NuGet\u002Flogin, secure NuGet publishing. DO NOT USE FOR: publishing to private feeds or Azure Artifacts (OIDC is nuget.org only). INVOKES: shell (powershell or bash), edit, create, ask_user for guided repo setup.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fnuget-trusted-publishing\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M76SGHVNBNVM1DMVDYTMAE5G","dotnet-pinvoke","Correctly call native (C\u002FC++) libraries from .NET using P\u002FInvoke and LibraryImport. Covers function signatures, string marshalling, memory lifetime, SafeHandle, and cross-platform patterns. USE FOR: writing new P\u002FInvoke or LibraryImport declarations, reviewing or debugging existing native interop code, wrapping a C or C++ library for use in .NET, diagnosing crashes, memory leaks, or corruption at the managed\u002Fnative boundary. DO NOT USE FOR: COM interop, C++\u002FCLI mixed-mode assemblies, or pure managed code with no native dependencies.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fdotnet-pinvoke\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M76SGDB9Z3GSB1CFW314NC84","csharp-scripts","Run file-based C# apps with the .NET CLI when the user explicitly wants C#\u002F.NET code without creating a project. Use for C# language\u002FAPI experiments, one-file C# apps, small multi-file C# apps composed with `#:include`\u002F`#:exclude`, or C# file-based apps linked with `#:ref`. Do not use for language-agnostic throwaway scripts, generic computations, Python\u002FPowerShell-style automation, full projects, or existing app integration.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fcsharp-scripts\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M76SG805T8W764WAKB1NP3CJ","thread-abort-migration","Guides migration of .NET Framework Thread.Abort usage to cooperative cancellation in modern .NET. USE FOR: modernizing code that calls Thread.Abort, catching ThreadAbortException, replacing Thread.ResetAbort, replacing Thread.Interrupt for thread termination, resolving PlatformNotSupportedException or SYSLIB0006 after retargeting to .NET 6+, migrating ASP.NET Response.End or Response.Redirect(url, true) which internally call Thread.Abort. DO NOT USE FOR: code that only uses Thread.Join, Thread.Sleep, or Thread.Start without any abort, interrupt, or ThreadAbortException usage — these APIs work identically in modern .NET and need no migration. Also not for projects staying on .NET Framework, or Thread.Abort usage inside third-party libraries you do not control.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-upgrade\u002Fskills\u002Fthread-abort-migration\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M76SG2588ZJBE5C51HYJJSKV","migrate-nullable-references","Enable nullable reference types in a C# project and systematically resolve all warnings. USE FOR: adopting NRTs in existing codebases, file-by-file or project-wide migration, fixing CS8602\u002FCS8618\u002FCS86xx warnings, annotating APIs for nullability, cleaning up null-forgiving operators, upgrading dependencies with new nullable annotations. DO NOT USE FOR: projects already fully migrated with zero warnings (unless auditing suppressions), fixing a handful of nullable warnings in code that already has NRTs enabled, suppressing warnings without fixing them, C# 7.3 or earlier projects. INVOKES: Get-NullableReadiness.ps1 scanner script.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-upgrade\u002Fskills\u002Fmigrate-nullable-references\u002FSKILL.md",[],[]]