> Write new MSTest unit tests and fix existing MSTest code using MSTest 3.x/4.x modern APIs and best practices. better MSTest assertion than Assert.IsTrue, replace hard cast with MSTest type assertion, MSTest assertion APIs (IsInstanceOfType, Contains, ContainsSingle, HasCount, IsEmpty, IsNotEmpty, DoesNotContain, StartsWith, EndsWith, MatchesRegex, IsGreaterThan, IsInRange, IsNull), fix swapped Assert.AreEqual arguments, replace ExpectedException with Assert.Throws, data-driven tests (DataRow, DynamicData, ValueTuples), test lifecycle (sealed classes, TestInitialize, TestCleanup), async tests and cancellation tokens, test parallelization (Parallelize / DoNotParallelize), MSTest.Sdk project setup. running tests (use run-tests), MSTest version migration (use migrate-mstest-v1v2-to-v3 or migrate-mstest-v3-to-v4), xUnit/NUnit/TUnit, or non-.NET languages.
npx skills add https://github.com/microsoft/testfx --skill writing-mstest-tests
Help users write effective, modern unit tests with MSTest 3.x/4.x using current APIs and best practices.
Assert.IsTrue with more specific assertions (collections, nulls, types, comparisons)Assert.AreEqual argument order (expected first, actual second)DynamicData from IEnumerable<object[]> to ValueTuple-based datatest-anti-patterns)run-tests skill)migrate-mstest-v1v2-to-v3)migrate-mstest-v3-to-v4)| Input | Required | Description |
|-------|----------|-------------|
| Code under test | No | The production code to be tested |
| Existing test code | No | Current tests to fix, update, or modernize |
| Test scenario description | No | What behavior the user wants to test |
Check the test project for MSTest version and configuration:
MSTest.Sdk (<Sdk Name="MSTest.Sdk">): modern setup, all features availableMSTest metapackage: modern setup (MSTest 3.x+)MSTest.TestFramework + MSTest.TestAdapter: check version for feature availabilityRecommend MSTest.Sdk or the MSTest metapackage for new projects:
<!-- Option 1: MSTest SDK (simplest, recommended for new projects) -->
<Project Sdk="MSTest.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
</Project>
When using MSTest.Sdk, put the version in global.json instead of the project file so all test projects get bumped together:
{
"msbuild-sdks": {
"MSTest.Sdk": "3.8.2"
}
}
<!-- Option 2: MSTest metapackage -->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MSTest" Version="3.8.2" />
</ItemGroup>
</Project>
Apply these structural conventions:
sealed for performance and design clarity[TestClass] on the class and [TestMethod] on test methodsMethodName_Scenario_ExpectedBehavior[ProjectName].Tests[TestClass]
public sealed class OrderServiceTests
{
[TestMethod]
public void CalculateTotal_WithDiscount_ReturnsReducedPrice()
{
// Arrange
var service = new OrderService();
var order = new Order { Price = 100m, DiscountPercent = 10 };
// Act
var total = service.CalculateTotal(order);
// Assert
Assert.AreEqual(90m, total);
}
}
Pick the most specific assertion for each test scenario. More specific assertions produce better failure messages and make the test's intent clear:
| What you are testing | Assertion |
|---|---|
| Two values are equal | Assert.AreEqual(expected, actual) |
| Same object instance (reference identity) | Assert.AreSame(expected, actual) |
| Value is null | Assert.IsNull(value) |
| Value is not null | Assert.IsNotNull(value) |
| Collection is empty | Assert.IsEmpty(collection) |
| Collection is not empty | Assert.IsNotEmpty(collection) |
| Collection has exactly N items | Assert.HasCount(N, collection) |
| Collection contains an item | Assert.Contains(item, collection) |
| Collection does not contain an item | Assert.DoesNotContain(item, collection) |
| Object is a specific type | Assert.IsInstanceOfType<T>(value) |
| Code throws an exception | Assert.ThrowsExactly<T>(() => ...) |
Prefer Assert class methods over StringAssert or CollectionAssert where both exist.
Assert.AreEqual(expected, actual); // Value equality
Assert.AreSame(expected, actual); // Reference equality -- same object instance
Assert.IsNull(value);
Assert.IsNotNull(value);
Assert.Throws instead of [ExpectedException]// Synchronous
var ex = Assert.ThrowsExactly<ArgumentNullException>(() => service.Process(null));
Assert.AreEqual("input", ex.ParamName);
// Async
var ex = await Assert.ThrowsExactlyAsync<InvalidOperationException>(
async () => await service.ProcessAsync(null));
Assert.Throws<T> matches T or any derived typeAssert.ThrowsExactly<T> matches only the exact type TAssert.Contains(expectedItem, collection);
Assert.DoesNotContain(unexpectedItem, collection);
var single = Assert.ContainsSingle(collection); // Returns the single element
Assert.HasCount(3, collection);
Assert.IsEmpty(collection);
Assert.IsNotEmpty(collection);
Replace generic Assert.IsTrue with specialized assertions -- they give better failure messages:
| Instead of | Use |
|---|---|
| Assert.IsTrue(list.Count > 0) | Assert.IsNotEmpty(list) |
| Assert.IsTrue(list.Count == 0) | Assert.IsEmpty(list) |
| Assert.IsTrue(list.Count() == 3) | Assert.HasCount(3, list) |
| Assert.IsTrue(x != null) | Assert.IsNotNull(x) |
| Assert.IsTrue(x == null) | Assert.IsNull(x) |
| Assert.AreEqual(a, b) for same instance | Assert.AreSame(a, b) -- reference identity |
| Assert.IsTrue(!list.Contains(item)) | Assert.DoesNotContain(item, list) |
| list.Single(predicate) + Assert.IsNotNull | Assert.ContainsSingle(list) |
| Assert.IsTrue(list.Contains(item)) | Assert.Contains(item, list) |
Assert.Contains("expected", actualString);
Assert.StartsWith("prefix", actualString);
Assert.EndsWith("suffix", actualString);
Assert.MatchesRegex(@"\d{3}-\d{4}", phoneNumber);
// MSTest 3.x -- out parameter
Assert.IsInstanceOfType<MyHandler>(result, out var typed);
typed.Handle();
// MSTest 4.x -- returns directly
var typed = Assert.IsInstanceOfType<MyHandler>(result);
Assert.IsGreaterThan(lowerBound, actual);
Assert.IsLessThan(upperBound, actual);
Assert.IsInRange(actual, low, high);
[TestMethod]
[DataRow(1, 2, 3)]
[DataRow(0, 0, 0, DisplayName = "Zeros")]
[DataRow(-1, 1, 0)]
public void Add_ReturnsExpectedSum(int a, int b, int expected)
{
Assert.AreEqual(expected, Calculator.Add(a, b));
}
Prefer ValueTuple return types over IEnumerable<object[]> for type safety:
[TestMethod]
[DynamicData(nameof(DiscountTestData))]
public void ApplyDiscount_ReturnsExpectedPrice(decimal price, int percent, decimal expected)
{
var result = PriceCalculator.ApplyDiscount(price, percent);
Assert.AreEqual(expected, result);
}
// ValueTuple -- preferred (MSTest 3.7+)
public static IEnumerable<(decimal price, int percent, decimal expected)> DiscountTestData =>
[
(100m, 10, 90m),
(200m, 25, 150m),
(50m, 0, 50m),
];
When you need metadata per test case, use TestDataRow<T>:
public static IEnumerable<TestDataRow<(decimal price, int percent, decimal expected)>> DiscountTestDataWithMetadata =>
[
new((100m, 10, 90m)) { DisplayName = "10% discount" },
new((200m, 25, 150m)) { DisplayName = "25% discount" },
new((50m, 0, 50m)) { DisplayName = "No discount" },
];
readonly fields and works correctly with nullability analyzers (fields are guaranteed non-null after construction)[TestInitialize] only for async initialization, combined with the constructor for sync parts[TestCleanup] for cleanup that must run even on failureTestContext via constructor (MSTest 3.6+)[TestClass]
public sealed class RepositoryTests
{
private readonly TestContext _testContext;
private readonly FakeDatabase _db; // readonly -- guaranteed by constructor
public RepositoryTests(TestContext testContext)
{
_testContext = testContext;
_db = new FakeDatabase(); // sync init in ctor
}
[TestInitialize]
public async Task InitAsync()
{
// Use TestInitialize ONLY for async setup
await _db.SeedAsync();
}
[TestCleanup]
public void Cleanup() => _db.Reset();
}
[AssemblyInitialize] -- once per assembly[ClassInitialize] -- once per classTestContext property injection: Constructor -> set TestContext property -> [TestInitialize]TestContext: Constructor (receives TestContext) -> [TestInitialize][TestCleanup] -> DisposeAsync -> Dispose -- per test[ClassCleanup] -- once per class[AssemblyCleanup] -- once per assemblyAlways use TestContext.CancellationToken with [Timeout]:
[TestMethod]
[Timeout(5000)]
public async Task FetchData_ReturnsWithinTimeout()
{
var result = await _client.GetDataAsync(_testContext.CancellationToken);
Assert.IsNotNull(result);
}
Use only for genuinely flaky external dependencies (network, file system), not to paper over race conditions or shared state issues.
[TestMethod]
[Retry(3)]
public void ExternalService_EventuallyResponds() { }
[TestMethod]
[OSCondition(OperatingSystems.Windows)]
public void WindowsRegistry_ReadsValue() { }
[TestMethod]
[CICondition(ConditionMode.Exclude)]
public void LocalOnly_InteractiveTest() { }
[assembly: Parallelize(Workers = 4, Scope = ExecutionScope.MethodLevel)]
[TestClass]
[DoNotParallelize] // Opt out specific classes
public sealed class DatabaseIntegrationTests { }
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
Use when implementation is complete, all tests pass, and you need to decide how to integrate the work - guides completion of development work by presenting structured options for merge, PR, or cleanup
Use when implementing any feature or bugfix, before writing implementation code
Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always
Expert guidance for systematic backtesting of trading strategies. Use when developing, testing, stress-testing, or validating quantitative trading strategies. Covers "beating ideas to death" methodology, parameter robustness testing, slippage modeling, bias prevention, and interpreting backtest results. Applicable when user asks about backtesting, strategy validation, robustness testing, avoiding overfitting, or systematic trading development.
Cloud laboratory platform for automated protein testing and validation. Use when designing proteins and needing experimental validation including binding assays, expression testing, thermostability measurements, enzyme activity assays, or protein sequence optimization. Also use for submitting experiments via API, tracking experiment status, downloading results, optimizing protein sequences for better expression using computational tools (NetSolP, SoluProt, SolubleMPNN, ESM), or managing protein design workflows with wet-lab validation.
This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.
Take microsoft/writing-mstest-tests from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.