SuperAPI AI 工具集

mstest-skill

测试与质量

查看项目

更新于 10-15 14:49

技能介绍

用途

MSTest 是微软为 .NET 提供的内置测试框架。本技能用于在 C# 中生成 MSTest 测试代码,适用于用户提及 "MSTest"、"[TestMethod]"、"[TestClass]" 等场景。

主要能力

基础测试

使用 [TestClass] 标记测试类,[TestMethod] 标记测试方法,[TestInitialize] 在每个测试前执行初始化。示例:

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class CalculatorTests
{
    private Calculator _calc;

    [TestInitialize]
    public void SetUp() => _calc = new Calculator();

    [TestMethod]
    public void Add_TwoNumbers_ReturnsSum()
    {
        Assert.AreEqual(5, _calc.Add(2, 3));
    }

    [TestMethod]
    [ExpectedException(typeof(DivideByZeroException))]
    public void Divide_ByZero_Throws()
    {
        _calc.Divide(10, 0);
    }
}

数据驱动测试

使用 [DataTestMethod] 配合 [DataRow] 或 [DynamicData] 实现参数化测试:

[DataTestMethod]
[DataRow(2, 3, 5)]
[DataRow(-1, 1, 0)]
[DataRow(0, 0, 0)]
public void Add_Parameterized(int a, int b, int expected)
{
    Assert.AreEqual(expected, _calc.Add(a, b));
}

[DataTestMethod]
[DynamicData(nameof(GetTestData), DynamicDataSourceType.Method)]
public void Add_DynamicData(int a, int b, int expected)
{
    Assert.AreEqual(expected, _calc.Add(a, b));
}

private static IEnumerable<object[]> GetTestData()
{
    yield return new object[] { 1, 2, 3 };
    yield return new object[] { 10, -5, 5 };
}

断言

提供多种断言方法:

Assert.AreEqual(expected, actual);
Assert.AreNotEqual(unexpected, actual);
Assert.IsTrue(condition);
Assert.IsFalse(condition);
Assert.IsNull(obj);
Assert.IsNotNull(obj);
Assert.IsInstanceOfType(obj, typeof(MyClass));
Assert.ThrowsException<ArgumentException>(() => Method());
CollectionAssert.Contains(list, item);
CollectionAssert.AreEquivalent(expected, actual);
StringAssert.Contains(str, "substring");
StringAssert.StartsWith(str, "prefix");
StringAssert.Matches(str, new Regex(@"\d+"));

生命周期

测试生命周期钩子按以下顺序执行:

  • [AssemblyInitialize] → 每个程序集一次(静态)
  • [ClassInitialize] → 每个类一次(静态)
  • [TestInitialize] → 每个测试前
  • [TestMethod] → 测试
  • [TestCleanup] → 每个测试后
  • [ClassCleanup] → 类结束后一次(静态)
  • [AssemblyCleanup] → 程序集结束后一次(静态)

分类与标记

[TestMethod, TestCategory("Smoke")]
public void QuickTest() { }

[TestMethod, Ignore("Bug #456")]
public void SkippedTest() { }

[TestMethod, Timeout(5000)]
public void TimedTest() { }

使用方式

安装依赖:

dotnet add package MSTest.TestFramework MSTest.TestAdapter Microsoft.NET.Test.Sdk

运行测试:

dotnet test

按分类筛选运行:

dotnet test --filter "TestCategory=Smoke"

深入模式

参考 reference/playbook.md 获取生产级模式,包含以下章节:

  • §1 项目设置:.csproj 依赖、带并行与覆盖率配置的 .runsettings
  • §2 测试模式:TestMethod、DataTestMethod、DynamicData、异常测试
  • §3 FluentAssertions:AssertionScope、异步异常、集合断言
  • §4 类与程序集初始化:Testcontainers、共享昂贵设置、全局配置
  • §5 WebApplicationFactory:使用内存数据库的 API 集成测试
  • §6 Bogus 测试数据:用于生成真实数据的 Faker 模式
  • §7 TestContext 与日志:诊断输出、分类、超时
  • §8 CI/CD 集成:带覆盖率报告与阈值的 GitHub Actions
  • §9 调试表:12 个常见问题及其原因与修复
  • §10 最佳实践:14 项生产检查清单

适用场景

适用于 .NET 项目中的单元测试、参数化测试、集成测试编写,以及测试项目配置、CI/CD 集成和测试调试。

限制

资料未提供关于收费、价格、平台支持范围或具体效果的信息。