关于 dotnet-add-testing
为现有 .NET 项目添加测试基础设施的 Skill,可搭建 xUnit 测试项目、coverlet 覆盖率配置和常规目录结构;深入测试模式由相关 Skill 负责。
主要功能
- 01创建 xUnit 测试项目
- 02配置 coverlet 代码覆盖率
- 03设置测试专用构建属性
- 04通过 CPM 注册测试包
- 05添加起始测试与命名规范
适用场景
- 01为现有解决方案搭建单元测试
- 02为 dotnet test 添加覆盖率收集
- 03创建集成测试项目结构
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ wshaddix/ dotnet-skills --skill dotnet-add-testing安装后在 Claude Code 中输入/dotnet-add-testing确认已加载。
详细介绍
dotnet-add-testing
为现有 .NET 项目添加测试基础架构脚手架。创建使用 xUnit 的测试项目,使用 coverlet 配置代码覆盖率,并设置惯用的目录结构。
范围边界:此技能仅提供测试项目脚手架。关于深入的测试模式——xUnit v3 功能、使用 WebApplicationFactory 进行集成测试、UI 测试、快照测试、测试质量指标和测试策略指导——请参阅 [skill:dotnet-testing-strategy] 和相关测试技能。
**前置条件:**先运行 [skill:dotnet-version-detection] 以确定 SDK 版本和 TFM。运行 [skill:dotnet-project-analysis] 以了解现有解决方案结构。
交叉引用:[skill:dotnet-project-structure] 介绍整体解决方案布局约定;[skill:dotnet-scaffold-project] 会在新项目中包含测试脚手架;[skill:dotnet-add-analyzers] 介绍测试专用分析器的抑制配置。
测试项目结构
遵循在 tests/ 下镜像 src/ 项目名称的约定:
MyApp/
├── src/
│ ├── MyApp.Core/
│ ├── MyApp.Api/
│ └── MyApp.Infrastructure/
└── tests/
├── MyApp.Core.UnitTests/
├── MyApp.Api.UnitTests/
├── MyApp.Api.IntegrationTests/
└── Directory.Build.props # Test-specific build settings
命名约定:
*.UnitTests—— 不依赖外部资源的独立测试*.IntegrationTests—— 使用真实基础设施(数据库、HTTP、文件系统)的测试*.FunctionalTests—— 通过完整应用程序堆栈进行端到端测试
步骤 1:创建测试项目
# Create xUnit test project
dotnet new xunit -n MyApp.Core.UnitTests -o tests/MyApp.Core.UnitTests
# Add to solution
dotnet sln add tests/MyApp.Core.UnitTests/MyApp.Core.UnitTests.csproj
# Add reference to the project under test
dotnet add tests/MyApp.Core.UnitTests/MyApp.Core.UnitTests.csproj \
reference src/MyApp.Core/MyApp.Core.csproj
清理生成的项目
移除已在 Directory.Build.props 中定义的属性:
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="coverlet.collector" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\MyApp.Core\MyApp.Core.csproj" />
</ItemGroup>
</Project>
使用 CPM 时,Version 属性由 Directory.Packages.props 管理。请从生成的 .csproj 中移除这些属性。
步骤 2:添加测试专用生成属性
创建 tests/Directory.Build.props,以自定义所有测试项目的设置:
<Project>
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
</PropertyGroup>
</Project>
此文件会导入根目录的 Directory.Build.props(用于共享设置,如 Nullable、ImplicitUsings、LangVersion),并覆盖测试专用属性。
步骤 3:在 CPM 中注册测试包
将测试包版本添加到 Directory.Packages.props:
<ItemGroup>
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageVersion Include="xunit.v3" Version="3.2.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
<PackageVersion Include="coverlet.collector" Version="8.0.0" />
</ItemGroup>
可选:模拟库
如果项目需要测试替身,请添加模拟库:
<PackageVersion Include="NSubstitute" Version="5.3.0" />
或者使用断言库:
<PackageVersion Include="FluentAssertions" Version="8.0.1" />
步骤 4:配置代码覆盖率
Coverlet(Collector 模式)
coverlet.collector 包通过数据收集器与 dotnet test 集成。基本覆盖率无需额外配置。
生成覆盖率报告:
# Collect coverage (Cobertura format by default)
dotnet test --collect:"XPlat Code Coverage"
# Results appear in TestResults/*/coverage.cobertura.xml
覆盖率阈值
如需在 CI 中强制执行阈值,请使用 coverlet.msbuild 进行阈值检查:
<PackageReference Include="coverlet.msbuild" />
# Enforce minimum coverage threshold
dotnet test /p:CollectCoverage=true \
/p:CoverageOutputFormat=cobertura \
/p:Threshold=80 \
/p:ThresholdType=line
生成覆盖率报告
使用 reportgenerator 生成易于阅读的 HTML 报告:
# Install globally
dotnet tool install -g dotnet-reportgenerator-globaltool
# Generate HTML report
reportgenerator \
-reports:"tests/**/coverage.cobertura.xml" \
-targetdir:coverage-report \
-reporttypes:Html
步骤 5:添加测试专用 EditorConfig 覆盖设置
在根目录的 .editorconfig 中添加测试专用的宽松规则:
[tests/**.cs]
# Allow underscores in test method names (Given_When_Then or Should_Behavior)
dotnet_diagnostic.CA1707.severity = none
# Test parameters are validated by the framework
dotnet_diagnostic.CA1062.severity = none
# ConfigureAwait not relevant in test context
dotnet_diagnostic.CA2007.severity = none
# Tests often have intentionally unused variables for assertions
dotnet_diagnostic.IDE0059.severity = suggestion
步骤 6:编写入门测试
将模板生成的 UnitTest1.cs 替换为结构规范的测试:
namespace MyApp.Core.UnitTests;
public class SampleServiceTests
{
[Fact]
public void Method_Condition_ExpectedResult()
{
// Arrange
var sut = new SampleService();
// Act
var result = sut.DoWork();
// Assert
Assert.NotNull(result);
}
[Theory]
[InlineData(1, 2, 3)]
[InlineData(0, 0, 0)]
[InlineData(-1, 1, 0)]
public void Add_TwoNumbers_ReturnsSum(int a, int b, int expected)
{
var result = Calculator.Add(a, b);
Assert.Equal(expected, result);
}
}
测试命名约定
使用 Method_Condition_ExpectedResult 模式:
CreateUser_WithValidInput_ReturnsUserGetById_WhenNotFound_ReturnsNullDelete_WithoutPermission_ThrowsUnauthorized
验证
添加测试基础架构后,验证一切是否正常:
# Restore (regenerate lock files if using CPM)
dotnet restore
# Build (verifies project references and analyzer config)
dotnet build --no-restore
# Run tests
dotnet test --no-build
# Run with coverage
dotnet test --collect:"XPlat Code Coverage"
添加集成测试项目
对于需要 WebApplicationFactory 或数据库访问的集成测试:
dotnet new xunit -n MyApp.Api.IntegrationTests -o tests/MyApp.Api.IntegrationTests
dotnet sln add tests/MyApp.Api.IntegrationTests/MyApp.Api.IntegrationTests.csproj
dotnet add tests/MyApp.Api.IntegrationTests/MyApp.Api.IntegrationTests.csproj \
reference src/MyApp.Api/MyApp.Api.csproj
将集成测试包添加到 CPM(让 Microsoft.AspNetCore.Mvc.Testing 的主版本与目标框架匹配——例如,net8.0 对应 8.x,net9.0 对应 9.x,net10.0 对应 10.x):
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0" />
<PackageVersion Include="Testcontainers" Version="4.3.0" />
有关集成测试深度内容(WebApplicationFactory 模式、测试容器、数据库夹具),请参阅 [skill:dotnet-integration-testing]。
后续内容
本技能介绍了测试项目搭建。有关更深入的测试指导:
- xUnit v3 功能和模式 -- [技能:dotnet-xunit]
- 使用 WebApplicationFactory 进行集成测试 -- [技能:dotnet-integration-testing]
- UI 测试(Blazor、MAUI、Uno) -- [技能:dotnet-blazor-testing]、[技能:dotnet-maui-testing]、[技能:dotnet-uno-testing]
- 快照测试 -- [技能:dotnet-snapshot-testing]
- 测试质量和覆盖率强制检查 -- [技能:dotnet-test-quality]
- CI 测试报告 -- 入门请参阅 [技能:dotnet-add-ci],进阶请参阅 [技能:dotnet-gha-build-test] 和 [技能:dotnet-ado-build-test]