答案是使用 Coverlet 可轻松收集 .NET 测试覆盖率。通过安装 coverlet.collector 包并运行 dotnet test –collect:”XPlat Code Coverage”,可生成默认 coverage.json 报告;结合 coverlet.runsettings 文件可自定义输出格式(如 json、cobertura、lcov)、排除测试项及指定输出目录;生成的报告支持本地可视化分析或集成到 CI/CD 工具中,便于全面掌握代码覆盖情况。
使用 Coverlet 收集 .NET 测试的代码覆盖率
Coverlet 是一个开源工具,用于收集 .NET 项目的单元测试代码覆盖率。它支持 MSTest、xUnit 和 NUnit 等主流测试框架,并能生成多种格式的覆盖率报告(如 JSON、Cobertura、lcov)。以下是具体使用方法。
安装 Coverlet
在项目中启用 Coverlet 最简单的方式是通过 NuGet 安装其 MSBuild 集成包:
- 在测试项目目录下运行以下命令:
dotnet add package coverlet.collector
- 该包会自动集成到 dotnet test 命令中,无需额外配置运行时依赖。
运行测试并生成覆盖率数据
执行测试的同时启用 Coverlet 收集覆盖率:
dotnet test –collect:”XPlat Code Coverage”
- –collect:”XPlat Code Coverage” 触发 Coverlet 收集器。
- 测试完成后,Coverlet 默认在 TestResults 目录下生成一个 coverage.json 文件。
自定义输出格式和路径
你可以指定覆盖率报告的格式和保存位置:
dotnet test –collect:”XPlat Code Coverage” –settings coverlet.runsettings
- 创建名为 coverlet.runsettings 的文件,内容如下:
<?xml version="1.0" encoding="utf-8"?> <RunSettings> <DataCollectionRunSettings> <DataCollectors> <DataCollector friendlyName="XPlat Code Coverage"> <Configuration> <Format>json,cobertura,lcov</Format> <Exclude>[*Tests*]*</Exclude> <IncludeTestAssembly>false</IncludeTestAssembly> <OutputDirectory>./coverage/</OutputDirectory> </Configuration> </DataCollector> </DataCollectors> </DataCollectionRunSettings> </RunSettings>
- Format:支持 json、cobertura、lcov、opencover、teamcity 等。
- Exclude:排除测试类或特定命名空间。
- OutputDirectory:指定输出目录。
查看和分析报告
生成的报告可用于本地分析或 CI 集成:
- 使用 lcov 格式配合 genhtml 生成可视化 HTML 报告。
- 将 cobertura.xml 导入 CI 工具如 Azure DevOps、Jenkins 或 GitHub Actions。
- 使用 VS Code 插件(如 “Coverage Gutters”)结合 lcov 文件高亮显示未覆盖代码。
基本上就这些。只要测试项目引用了 coverlet.collector,再配合 –collect 参数,就能轻松获得覆盖率数据。关键在于合理配置 runsettings 文件以满足项目需求。
html js git json github 工具 jenkins vs code .net json html 命名空间 format xml github jenkins devops azure