MR
Mayur Rathi
@github
⭐ 34.1k GitHub stars

Csharp-Mstest

Csharp-Mstest是一款code方向的AI技能,核心价值是Get best practices for MSTest 3,可用于解决开发者在code领域的实际问题,帮助用户提升效率、自动化重复任务或优化工作流。

Get best practices for MSTest 3.x/4.x unit testing, including modern assertion APIs and data-driven tests

Last verified on: 2026-05-30
mkdir -p ./skills/csharp-mstest && curl -sfL https://raw.githubusercontent.com/github/awesome-copilot/main/skills/csharp-mstest/SKILL.md -o ./skills/csharp-mstest/SKILL.md

Run in terminal / PowerShell. Requires curl (Unix) or PowerShell 5+ (Windows).

Skill Content

# MSTest Best Practices (MSTest 3.x/4.x)


Your goal is to help me write effective unit tests with modern MSTest, using current APIs and best practices.


Project Setup


- Use a separate test project with naming convention `[ProjectName].Tests`

- Reference MSTest 3.x+ NuGet packages (includes analyzers)

- Consider using MSTest.Sdk for simplified project setup

- Run tests with `dotnet test`


Test Class Structure


- Use `[TestClass]` attribute for test classes

- **Seal test classes by default** for performance and design clarity

- Use `[TestMethod]` for test methods (prefer over `[DataTestMethod]`)

- Follow Arrange-Act-Assert (AAA) pattern

- Name tests using pattern `MethodName_Scenario_ExpectedBehavior`


csharp
[TestClass]
public sealed class CalculatorTests
{
    [TestMethod]
    public void Add_TwoPositiveNumbers_ReturnsSum()
    {
        // Arrange
        var calculator = new Calculator();

        // Act
        var result = calculator.Add(2, 3);

        // Assert
        Assert.AreEqual(5, result);
    }
}

Test Lifecycle


- **Prefer constructors over `[TestInitialize]`** - enables `readonly` fields and follows standard C# patterns

- Use `[TestCleanup]` for cleanup that must run even if test fails

- Combine constructor with async `[TestInitialize]` when async setup is needed


csharp
[TestClass]
public sealed class ServiceTests
{
    private readonly MyService _service;  // readonly enabled by constructor

    public ServiceTests()
    {
        _service = new MyService();
    }

    [TestInitialize]
    public async Task InitAsync()
    {
        // Use for async initialization only
        await _service.WarmupAsync();
    }

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

Execution Order


1. **Assembly Initialization** - `[AssemblyInitialize]` (once per test assembly)

2. **Class Initialization** - `[ClassInitialize]` (once per test class)

3. **Test Initialization** (for every test method):

1. Constructor

2. Set `TestContext` property

3. `[TestInitialize]`

4. **Test Execution** - test method runs

5. **Test Cleanup** (for every test method):

1. `[TestCleanup]`

2. `DisposeAsync` (if implemented)

3. `Dispose` (if implemented)

6. **Class Cleanup** - `[ClassCleanup]` (once per test class)

7. **Assembly Cleanup** - `[AssemblyCleanup]` (once per test assembly)


Modern Assertion APIs


MSTest provides three assertion classes: `Assert`, `StringAssert`, and `CollectionAssert`.


Assert Class - Core Assertions


csharp
// Equality
Assert.AreEqual(expected, actual);
Assert.AreNotEqual(notExpected, actual);
Assert.AreSame(expectedObject, actualObject);      // Reference equality
Assert.AreNotSame(notExpectedObject, actualObject);

// Null checks
Assert.IsNull(value);
Assert.IsNotNull(value);

// Boolean
Assert.IsTrue(condition);
Assert.IsFalse(condition);

// Fail/Inconclusive
Assert.Fail("Test failed due to...");
Assert.Inconclusive("Test cannot be completed because...");

Exception Testing (Prefer over `[ExpectedException]`)


csharp
// Assert.Throws - matches TException or derived types
var ex = Assert.Throws<ArgumentException>(() => Method(null));
Assert.AreEqual("Value cannot be null.", ex.Message);

// Assert.ThrowsExactly - matches exact type only
var ex = Assert.ThrowsExactly<InvalidOperationException>(() => Method());

// Async versions
var ex = await Assert.ThrowsAsync<HttpRequestException>(async () => await client.GetAsync(url));
var ex = await Assert.ThrowsExactlyAsync<InvalidOperationException>(async () => await Method());

Collection Assertions (Assert class)


csharp
Assert.Contains(expectedItem, collection);
Assert.DoesNotContain(unexpectedItem, collection);
Assert.ContainsSingle(collection);  // exactly one element
Assert.HasCount(5, collection);
Assert.IsEmpty(collection);
Assert.IsNotEmpty(collection);

String Assertions (Assert class)


csharp
Assert.Contains("expected", actualString);
Assert.StartsWith("prefix", 

🎯 Best For

  • QA engineers
  • Developers writing unit tests
  • Claude users
  • GitHub Copilot users
  • Software engineers

💡 Use Cases

  • Generating test cases for edge conditions
  • Writing integration test suites
  • Code quality improvement
  • Best practice enforcement

📖 How to Use This Skill

  1. 1

    Install the Skill

    Copy the install command from the Terminal tab and run it. The SKILL.md file downloads to your local skills directory.

  2. 2

    Load into Your AI Assistant

    Open Claude or GitHub Copilot and reference the skill. Paste the SKILL.md content or use the system prompt tab.

  3. 3

    Apply Csharp-Mstest to Your Work

    Open your project in the AI assistant and ask it to apply the skill. Start with a small module to verify the output quality.

  4. 4

    Review and Refine

    Review AI suggestions before committing. Run tests, check for regressions, and iterate on the skill output.

❓ Frequently Asked Questions

Does this generate test mocks?

Many testing skills include mock generation. Check the install command and skill content for details.

Is Csharp-Mstest compatible with Cursor and VS Code?

Yes — this skill works with any AI coding assistant including Cursor, VS Code with Copilot, and JetBrains IDEs.

Do I need specific dependencies for Csharp-Mstest?

Check the install command and Works With section. Most code skills only require the AI assistant and your codebase.

How do I install Csharp-Mstest?

Copy the install command from the Terminal tab and run it. The skill downloads to ./skills/csharp-mstest/SKILL.md, ready to use.

Can I customize this skill for my team?

Absolutely. Edit the SKILL.md file to add team-specific instructions, examples, or workflows.

⚠️ Common Mistakes to Avoid

Not testing edge cases

AI tends to generate happy-path tests. Manually review for boundary conditions.

Skipping validation

Always test AI-generated code changes, even for simple refactors.

Missing dependency updates

Check if the skill requires updated dependencies or new packages.

🔗 Related Skills