mcpField
C
csharp-mstest

csharp-mstest

github.com/github测试与质量40.5k8.9k 次安装今天更新
代码仓库

关于 csharp-mstest

面向 C# 开发者的现代 MSTest 3.x/4.x 单元测试实践指南,涵盖测试结构、断言、生命周期、数据驱动测试和执行选项。

主要功能

  1. 01MSTest 类与方法规范
  2. 02Arrange-Act-Assert 测试组织
  3. 03现代断言与异常 API
  4. 04生命周期和 TestContext 指引
  5. 05数据驱动、重试与并行测试

适用场景

  1. 01搭建独立的 MSTest 测试项目
  2. 02编写同步与异步代码的测试
  3. 03检查异常和集合结果
  4. 04组织 CI 与可追溯性测试

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/github/awesome-copilot --skill csharp-mstest

安装后在 Claude Code 中输入/csharp-mstest确认已加载。

详细介绍

MSTest 最佳实践(MSTest 3.x/4.x)

你的目标是帮助我使用现代 MSTest 编写有效的单元测试,采用当前的 API 和最佳实践。

项目设置

  • 使用单独的测试项目,命名约定为 [ProjectName].Tests
  • 引用 MSTest 3.x+ NuGet 包(包含分析器)
  • 考虑使用 MSTest.Sdk 以简化项目设置
  • 使用 dotnet test 运行测试

测试类结构

  • 对测试类使用 [TestClass] 特性
  • 默认将测试类密封(seal),以提升性能并明确设计意图
  • 对测试方法使用 [TestMethod](优先于 [DataTestMethod])
  • 遵循 Arrange-Act-Assert(AAA)模式
  • 使用 MethodName_Scenario_ExpectedBehavior 模式命名测试
[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);
    }
}

测试生命周期

  • 优先使用构造函数而非 [TestInitialize]——这样可以启用 readonly 字段,并遵循标准 C# 模式
  • 对于即使测试失败也必须运行的清理操作,使用 [TestCleanup]
  • 当需要异步设置时,将构造函数与异步 [TestInitialize] 结合使用
[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();
}
执行顺序
  1. 程序集初始化——[AssemblyInitialize](每个测试程序集一次)
  2. 类初始化——[ClassInitialize](每个测试类一次)
  3. 测试初始化(针对每个测试方法):
    1. 构造函数
    2. 设置 TestContext 属性
    3. [TestInitialize]
  4. 测试执行——测试方法运行
  5. 测试清理(针对每个测试方法):
    1. [TestCleanup]
    2. DisposeAsync(如果已实现)
    3. Dispose(如果已实现)
  6. 类清理——[ClassCleanup](每个测试类一次)
  7. 程序集清理——[AssemblyCleanup](每个测试程序集一次)

现代断言 API

MSTest 提供三个断言类:Assert、StringAssert 和 CollectionAssert。

Assert 类——核心断言
// 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...");
异常测试(优先于 [ExpectedException])
// 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());
集合断言(Assert 类)
Assert.Contains(expectedItem, collection);
Assert.DoesNotContain(unexpectedItem, collection);
Assert.ContainsSingle(collection);  // exactly one element
Assert.HasCount(5, collection);
Assert.IsEmpty(collection);
Assert.IsNotEmpty(collection);
字符串断言(Assert 类)
Assert.Contains("expected", actualString);
Assert.StartsWith("prefix", actualString);
Assert.EndsWith("suffix", actualString);
Assert.DoesNotStartWith("prefix", actualString);
Assert.DoesNotEndWith("suffix", actualString);
Assert.MatchesRegex(@"\d{3}-\d{4}", phoneNumber);
Assert.DoesNotMatchRegex(@"\d+", textOnly);
比较断言
Assert.IsGreaterThan(lowerBound, actual);
Assert.IsGreaterThanOrEqualTo(lowerBound, actual);
Assert.IsLessThan(upperBound, actual);
Assert.IsLessThanOrEqualTo(upperBound, actual);
Assert.IsInRange(actual, low, high);
Assert.IsPositive(number);
Assert.IsNegative(number);
类型断言
// MSTest 3.x - uses out parameter
Assert.IsInstanceOfType<MyClass>(obj, out var typed);
typed.DoSomething();

// MSTest 4.x - returns typed result directly
var typed = Assert.IsInstanceOfType<MyClass>(obj);
typed.DoSomething();

Assert.IsNotInstanceOfType<WrongType>(obj);
Assert.That(MSTest 4.0+)
Assert.That(result.Count > 0);  // Auto-captures expression in failure message
StringAssert 类

注意: 在可用时优先使用 Assert 类的等效方法(例如,用 Assert.Contains("expected", actual) 代替 StringAssert.Contains(actual, "expected"))。

StringAssert.Contains(actualString, "expected");
StringAssert.StartsWith(actualString, "prefix");
StringAssert.EndsWith(actualString, "suffix");
StringAssert.Matches(actualString, new Regex(@"\d{3}-\d{4}"));
StringAssert.DoesNotMatch(actualString, new Regex(@"\d+"));
CollectionAssert 类

注意: 在可用时优先使用 Assert 类的等效方法(例如,Assert.Contains)。

// Containment
CollectionAssert.Contains(collection, expectedItem);
CollectionAssert.DoesNotContain(collection, unexpectedItem);

// Equality (same elements, same order)
CollectionAssert.AreEqual(expectedCollection, actualCollection);
CollectionAssert.AreNotEqual(unexpectedCollection, actualCollection);

// Equivalence (same elements, any order)
CollectionAssert.AreEquivalent(expectedCollection, actualCollection);
CollectionAssert.AreNotEquivalent(unexpectedCollection, actualCollection);

// Subset checks
CollectionAssert.IsSubsetOf(subset, superset);
CollectionAssert.IsNotSubsetOf(notSubset, collection);

// Element validation
CollectionAssert.AllItemsAreInstancesOfType(collection, typeof(MyClass));
CollectionAssert.AllItemsAreNotNull(collection);
CollectionAssert.AllItemsAreUnique(collection);

数据驱动测试

DataRow
[TestMethod]
[DataRow(1, 2, 3)]
[DataRow(0, 0, 0, DisplayName = "Zeros")]
[DataRow(-1, 1, 0, IgnoreMessage = "Known issue #123")]  // MSTest 3.8+
public void Add_ReturnsSum(int a, int b, int expected)
{
    Assert.AreEqual(expected, Calculator.Add(a, b));
}
DynamicData

数据源可以返回以下任意类型:

  • IEnumerable<(T1, T2, ...)>(ValueTuple)——首选,提供类型安全(MSTest 3.7+)
  • IEnumerable<Tuple<T1, T2, ...>>——提供类型安全
  • IEnumerable<TestDataRow>——提供类型安全,并可控制测试元数据(显示名称、类别)
  • IEnumerable<object[]>——最不推荐,没有类型安全

注意: 创建新的测试数据方法时,优先使用 ValueTuple 或 TestDataRow,而不是 IEnumerable<object[]>。object[] 方式不提供编译时类型检查,可能会因类型不匹配导致运行时错误。

[TestMethod]
[DynamicData(nameof(TestData))]
public void DynamicTest(int a, int b, int expected)
{
    Assert.AreEqual(expected, Calculator.Add(a, b));
}

// ValueTuple - preferred (MSTest 3.7+)
public static IEnumerable<(int a, int b, int expected)> TestData =>
[
    (1, 2, 3),
    (0, 0, 0),
];

// TestDataRow - when you need custom display names or metadata
public static IEnumerable<TestDataRow<(int a, int b, int expected)>> TestDataWithMetadata =>
[
    new((1, 2, 3)) { DisplayName = "Positive numbers" },
    new((0, 0, 0)) { DisplayName = "Zeros" },
    new((-1, 1, 0)) { DisplayName = "Mixed signs", IgnoreMessage = "Known issue #123" },
];

// IEnumerable<object[]> - avoid for new code (no type safety)
public static IEnumerable<object[]> LegacyTestData =>
[
    [1, 2, 3],
    [0, 0, 0],
];

TestContext

TestContext 类提供测试运行信息、取消支持以及输出方法。 完整参考请参阅 TestContext 文档。

访问 TestContext
// Property (MSTest suppresses CS8618 - don't use nullable or = null!)
public TestContext TestContext { get; set; }

// Constructor injection (MSTest 3.6+) - preferred for immutability
[TestClass]
public sealed class MyTests
{
    private readonly TestContext _testContext;

    public MyTests(TestContext testContext)
    {
        _testContext = testContext;
    }
}

// Static methods receive it as parameter
[ClassInitialize]
public static void ClassInit(TestContext context) { }

// Optional for cleanup methods (MSTest 3.6+)
[ClassCleanup]
public static void ClassCleanup(TestContext context) { }

[AssemblyCleanup]
public static void AssemblyCleanup(TestContext context) { }
取消令牌

始终使用 TestContext.CancellationToken 配合 [Timeout] 实现协作式取消:

[TestMethod]
[Timeout(5000)]
public async Task LongRunningTest()
{
    await _httpClient.GetAsync(url, TestContext.CancellationToken);
}
测试运行属性
TestContext.TestName              // Current test method name
TestContext.TestDisplayName       // Display name (3.7+)
TestContext.CurrentTestOutcome    // Pass/Fail/InProgress
TestContext.TestData              // Parameterized test data (3.7+, in TestInitialize/Cleanup)
TestContext.TestException         // Exception if test failed (3.7+, in TestCleanup)
TestContext.DeploymentDirectory   // Directory with deployment items
输出和结果文件
// Write to test output (useful for debugging)
TestContext.WriteLine("Processing item {0}", itemId);

// Attach files to test results (logs, screenshots)
TestContext.AddResultFile(screenshotPath);

// Store/retrieve data across test methods
TestContext.Properties["SharedKey"] = computedValue;

高级功能

针对不稳定测试的重试(MSTest 3.9+)
[TestMethod]
[Retry(3)]
public void FlakyTest() { }
条件执行(MSTest 3.10+)

根据操作系统或 CI 环境跳过或运行测试:

// OS-specific tests
[TestMethod]
[OSCondition(OperatingSystems.Windows)]
public void WindowsOnlyTest() { }

[TestMethod]
[OSCondition(OperatingSystems.Linux | OperatingSystems.MacOS)]
public void UnixOnlyTest() { }

[TestMethod]
[OSCondition(ConditionMode.Exclude, OperatingSystems.Windows)]
public void SkipOnWindowsTest() { }

// CI environment tests
[TestMethod]
[CICondition]  // Runs only in CI (default: ConditionMode.Include)
public void CIOnlyTest() { }

[TestMethod]
[CICondition(ConditionMode.Exclude)]  // Skips in CI, runs locally
public void LocalOnlyTest() { }
并行化
// Assembly level
[assembly: Parallelize(Workers = 4, Scope = ExecutionScope.MethodLevel)]

// Disable for specific class
[TestClass]
[DoNotParallelize]
public sealed class SequentialTests { }
工作项可追溯性(MSTest 3.8+)

将测试链接到工作项,以便在测试报告中实现可追溯性:

// Azure DevOps work items
[TestMethod]
[WorkItem(12345)]  // Links to work item #12345
public void Feature_Scenario_ExpectedBehavior() { }

// Multiple work items
[TestMethod]
[WorkItem(12345)]
[WorkItem(67890)]
public void Feature_CoversMultipleRequirements() { }

// GitHub issues (MSTest 3.8+)
[TestMethod]
[GitHubWorkItem("https://github.com/owner/repo/issues/42")]
public void BugFix_Issue42_IsResolved() { }

工作项关联会出现在测试结果中,可用于:

  • 将测试覆盖范围追溯到需求
  • 将缺陷修复链接到回归测试
  • 在 CI/CD 管道中生成可追溯性报告

应避免的常见错误

// ❌ Wrong argument order
Assert.AreEqual(actual, expected);
// ✅ Correct
Assert.AreEqual(expected, actual);

// ❌ Using ExpectedException (obsolete)
[ExpectedException(typeof(ArgumentException))]
// ✅ Use Assert.Throws
Assert.Throws<ArgumentException>(() => Method());

// ❌ Using LINQ Single() - unclear exception
var item = items.Single();
// ✅ Use ContainsSingle - better failure message
var item = Assert.ContainsSingle(items);

// ❌ Hard cast - unclear exception
var handler = (MyHandler)result;
// ✅ Type assertion - shows actual type on failure
var handler = Assert.IsInstanceOfType<MyHandler>(result);

// ❌ Ignoring cancellation token
await client.GetAsync(url, CancellationToken.None);
// ✅ Flow test cancellation
await client.GetAsync(url, TestContext.CancellationToken);

// ❌ Making TestContext nullable - leads to unnecessary null checks
public TestContext? TestContext { get; set; }
// ❌ Using null! - MSTest already suppresses CS8618 for this property
public TestContext TestContext { get; set; } = null!;
// ✅ Declare without nullable or initializer - MSTest handles the warning
public TestContext TestContext { get; set; }

测试组织

  • 按功能或组件对测试进行分组
  • 使用 [TestCategory("Category")] 进行筛选
  • 使用 [TestProperty("Name", "Value")] 添加自定义元数据(例如 [TestProperty("Bug", "12345")])
  • 使用 [Priority(1)] 标记关键测试
  • 启用相关的 MSTest 分析器(MSTEST0020 用于构造函数偏好)

Mock 与隔离

  • 使用 Moq 或 NSubstitute 来 Mock 依赖项
  • 使用接口以便于 Mock
  • Mock 依赖项以隔离被测单元

评论

支持 Markdown