SuperAPI AI 工具集

csharp-tunit

测试与质量

查看项目

更新于 10-15 21:52

技能介绍

用途:帮助在 .NET 项目中用 TUnit 编写有效的单元测试,覆盖标准测试与数据驱动测试。

项目设置:使用独立测试项目,命名约定为 [ProjectName].Tests;引用 TUnit 与 TUnit.Assertions 包;测试类与被测类对应(如 CalculatorTests 对应 Calculator);用 dotnet test 运行;TUnit 要求 .NET 8.0 或更高版本。

测试结构:测试类无需类级特性;测试方法用 [Test](非 xUnit 的 [Fact]);遵循 Arrange-Act-Assert;命名采用 MethodName_Scenario_ExpectedBehavior;生命周期钩子包括 [Before(Test)]/[After(Test)]、[Before(Class)]/[After(Class)]、[Before(Assembly)]/[After(Assembly)],以及 [Before(TestSession)]/[After(TestSession)]。

标准测试:每个测试聚焦单一行为,保持独立、幂等、可任意顺序运行,必要时用 [DependsOn] 声明依赖。

数据驱动:用 [Arguments] 提供内联数据,[MethodData] 提供方法级数据,[ClassData] 提供类级数据,也可实现 ITestDataSource 自定义数据源;同一方法可叠加多个 [Arguments]。

断言:全部为异步,需 await。常用形式包括 await Assert.That(value).IsEqualTo(expected)、IsSameReferenceAs、IsTrue/IsFalse、Contains/DoesNotContain、Matches(pattern)、Throws<TException>()/ThrowsAsync<TException>();可用 .And、.Or 链式组合,用 .Within(tolerance) 做容差比较。

高级特性:[Repeat(n)]、[Retry(n)]、[ParallelLimit<T>]、[Skip("reason")]、[DependsOn(nameof(OtherTest))]、[Timeout(milliseconds)],并可扩展基类特性自定义属性。

组织与并行:按功能或组件分组,用 [Category] 分类、[DisplayName] 自定义名称,可用 TestContext 获取诊断信息;TUnit 默认并行执行,可用 [NotInParallel] 关闭,同类测试默认顺序执行。

迁移:将 [Fact] 换为 [Test],[Theory]+[InlineData] 换为 [Test]+[Arguments],[MemberData] 换为 [MethodData],Assert.Equal/True/Throws 换为对应的 await Assert.That 写法,构造函数/IDisposable 换为 [Before(Test)]/[After(Test)],IClassFixture<T> 换为 [Before(Class)]/[After(Class)]。

限制:资料未提供具体版本兼容细节、性能数据或收费信息。