SuperAPI AI 工具集

csharp-tunit

数据与分析

查看项目

更新于 10-16 01:15

技能介绍

用途:帮助在 .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、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] 关闭,同类测试默认顺序执行。

从 xUnit 迁移:将 [Fact] 换为 [Test],[Theory]+[InlineData] 换为 [Test]+[Arguments],[MemberData] 换为 [MethodData],Assert.Equal/True/Throws 换为对应异步断言,构造函数/IDisposable 换为 [Before(Test)]/[After(Test)],IClassFixture<T> 换为 [Before(Class)]/[After(Class)]。

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