CRAP 分数分析
何时使用此技能
在以下场景使用此技能:
- 在修改代码前评估代码质量和测试覆盖率
- 识别需要进行重构或测试的高风险代码
- 为 .NET 项目设置覆盖率收集
- 根据风险优先级确定要测试的代码
- 为 CI/CD 管道建立覆盖率阈值
什么是 CRAP?
CRAP 分数 = 复杂度 x (1 - 覆盖率)^2
CRAP(Change Risk Anti-Patterns,变更风险反模式)分数结合圈复杂度和测试覆盖率来识别有风险的代码。
| CRAP 分数 | 风险等级 | 需要采取的措施 |
|---|---|---|
| < 5 | 低 | 测试良好、可维护的代码 |
| 5-30 | 中 | 可接受,但需关注复杂度 |
| > 30 | 高 | 需要测试或重构 |
为什么 CRAP 很重要
- 高复杂度 + 低覆盖率 = 危险:难以理解且未经测试的代码修改起来风险很高
- 仅看复杂度是不够的:一个 100% 覆盖率的复杂方法比一个 0% 覆盖率的简单方法更安全
- 聚焦精力:优先测试复杂代码,而不是简单的 getter/setter
CRAP 分数示例
| 方法 | 复杂度 | 覆盖率 | 计算 | CRAP |
|---|---|---|---|---|
GetUserId() | 1 | 0% | 1 x (1 - 0)^2 | 1 |
ParseToken() | 54 | 52% | 54 x (1 - 0.52)^2 | 12.4 |
ValidateForm() | 20 | 0% | 20 x (1 - 0)^2 | 20 |
ProcessOrder() | 45 | 20% | 45 x (1 - 0.20)^2 | 28.8 |
ImportData() | 80 | 10% | 80 x (1 - 0.10)^2 | 64.8 |
覆盖率收集设置
coverage.runsettings
在仓库根目录创建 coverage.runsettings 文件。CRAP 分数计算必须使用 OpenCover 格式,因为它包含圈复杂度指标。
<?xml version="1.0" encoding="utf-8" ?>
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="XPlat code coverage">
<Configuration>
<!-- OpenCover 格式包含用于 CRAP 分数的圈复杂度 -->
<Format>cobertura,opencover</Format>
<!-- 排除测试和基准测试程序集 -->
<Exclude>[*.Tests]*,[*.Benchmark]*,[*.Migrations]*</Exclude>
<!-- 排除生成的代码、废弃成员和显式排除项 -->
<ExcludeByAttribute>Obsolete,GeneratedCodeAttribute,CompilerGeneratedAttribute,ExcludeFromCodeCoverageAttribute</ExcludeByAttribute>
<!-- 排除源生成的文件、Blazor 生成代码和迁移 -->
<ExcludeByFile>**/obj/**/*,**/*.g.cs,**/*.designer.cs,**/*.razor.g.cs,**/*.razor.css.g.cs,**/Migrations/**/*</ExcludeByFile>
<!-- 排除测试程序集 -->
<IncludeTestAssembly>false</IncludeTestAssembly>
<!-- 优化标志 -->
<SingleHit>false</SingleHit>
<UseSourceLink>true</UseSourceLink>
<SkipAutoProps>true</SkipAutoProps>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>
关键配置选项
| 选项 | 目的 |
|---|---|
Format | 必须包含 opencover 以获取复杂度指标 |
Exclude | 按模式排除测试/基准测试程序集 |
ExcludeByAttribute | 跳过生成的、废弃的以及显式排除的代码(包含 ExcludeFromCodeCoverageAttribute) |
ExcludeByFile | 跳过源生成的文件、Blazor 组件和迁移 |
SkipAutoProps | 不将自动属性视为分支 |
ReportGenerator 安装
将 ReportGenerator 安装为本地工具,用于生成包含风险热点的 HTML 报告。
添加到 .config/dotnet-tools.json
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-reportgenerator-globaltool": {
"version": "5.4.5",
"commands": ["reportgenerator"],
"rollForward": false
}
}
}
然后恢复:
dotnet tool restore
或全局安装
dotnet tool install --global dotnet-reportgenerator-globaltool
收集覆盖率
运行带有覆盖率收集的测试
# 清理之前的测试结果
rm -rf coverage/ TestResults/
# 运行单元测试并进行覆盖率收集
dotnet test tests/MyApp.Tests.Unit \
--settings coverage.runsettings \
--collect:"XPlat Code Coverage" \
--results-directory ./TestResults
# 运行集成测试(可选,增加覆盖率)
dotnet test tests/MyApp.Tests.Integration \
--settings coverage.runsettings \
--collect:"XPlat Code Coverage" \
--results-directory ./TestResults
生成 HTML 报告
dotnet reportgenerator \
-reports:"TestResults/**/coverage.opencover.xml" \
-targetdir:"coverage" \
-reporttypes:"Html;TextSummary;MarkdownSummaryGithub"
报告类型
| 类型 | 描述 | 输出 |
|---|---|---|
Html | 完整交互式报告 | coverage/index.html |
TextSummary | 纯文本摘要 | coverage/Summary.txt |
MarkdownSummaryGithub | 兼容 GitHub 的 Markdown | coverage/SummaryGithub.md |
Badges | 用于 README 的 SVG 徽章 | coverage/badge_*.svg |
Cobertura | 合并后的 Cobertura XML | coverage/Cobertura.xml |
阅读报告
风险热点部分
HTML 报告包含一个 风险热点(Risk Hotspots)部分,按复杂度排序显示方法:
- 圈复杂度:代码中独立路径的数量(if/else、switch case、循环)
- NPath 复杂度:非循环执行路径的数量(随嵌套呈指数增长)
- CRAP 分数:根据复杂度和覆盖率计算得出
解读结果
风险热点
─────────────
方法 复杂度 覆盖率 CRAP 分数
──────────────────────────────────────────────────────────────────
DataImporter.ParseRecord() 54 52% 12.4
AuthService.ValidateToken() 32 0% 32.0 ← 高风险
OrderProcessor.Calculate() 28 85% 1.3
UserService.CreateUser() 15 100% 0.0
待办事项:
ValidateToken()的 CRAP 分数 > 30 且覆盖率为 0% - 立即测试或重构ParseRecord()复杂度高但覆盖率尚可 - 可接受CreateUser()和Calculate()测试良好 - 修改安全
覆盖率阈值
推荐标准
| 覆盖率类型 | 目标 | 措施 |
|---|---|---|
| 行覆盖率 | > 80% | 对大多数项目良好 |
| 分支覆盖率 | > 60% | 捕捉条件逻辑 |
| CRAP 分数 | < 30 | 新代码的最大值 |
配置阈值
在仓库中创建 coverage.props:
<Project>
<PropertyGroup>
<!-- CI 强制执行的覆盖率阈值 -->
<CoverageThresholdLine>80</CoverageThresholdLine>
<CoverageThresholdBranch>60</CoverageThresholdBranch>
</PropertyGroup>
</Project>
CI/CD 集成
GitHub Actions
name: Coverage
on:
pull_request:
branches: [main, dev]
jobs:
coverage:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '9.0.x'
- name: Restore tools
run: dotnet tool restore
- name: Run tests with coverage
run: |
dotnet test \
--settings coverage.runsettings \
--collect:"XPlat Code Coverage" \
--results-directory ./TestResults
- name: Generate report
run: |
dotnet reportgenerator \
-reports:"TestResults/**/coverage.opencover.xml" \
-targetdir:"coverage" \
-reporttypes:"Html;MarkdownSummaryGithub;Cobertura"
- name: Upload coverage report
uses: actions/upload-artifact@v4
with:
name: coverage-report
path: coverage/
- name: Add coverage to PR
uses: marocchino/sticky-pull-request-comment@v2
with:
path: coverage/SummaryGithub.md
Azure Pipelines
- task: DotNetCoreCLI@2
displayName: '使用覆盖率运行测试'
inputs:
command: 'test'
arguments: '--settings coverage.runsettings --collect:"XPlat Code Coverage" --results-directory $(Build.SourcesDirectory)/TestResults'
- task: DotNetCoreCLI@2
displayName: '生成覆盖率报告'
inputs:
command: 'custom'
custom: 'reportgenerator'
arguments: '-reports:"$(Build.SourcesDirectory)/TestResults/**/coverage.opencover.xml" -targetdir:"$(Build.SourcesDirectory)/coverage" -reporttypes:"HtmlInline_AzurePipelines;Cobertura"'
- task: PublishCodeCoverageResults@2
displayName: '发布覆盖率'
inputs:
codeCoverageTool: 'Cobertura'
summaryFileLocation: '$(Build.SourcesDirectory)/coverage/Cobertura.xml'
快速参考
单行命令
# 完整分析工作流
rm -rf coverage/ TestResults/ && \
dotnet test --settings coverage.runsettings \
--collect:"XPlat Code Coverage" \
--results-directory ./TestResults && \
dotnet reportgenerator \
-reports:"TestResults/**/coverage.opencover.xml" \
-targetdir:"coverage" \
-reporttypes:"Html;TextSummary"
# 查看摘要
cat coverage/Summary.txt
# 在 Linux 上打开 HTML 报告
xdg-open coverage/index.html
# 在 macOS 上打开 HTML 报告
open coverage/index.html
# 在 Windows 上打开 HTML 报告
start coverage/index.html
项目标准
| 指标 | 新代码 | 遗留代码 |
|---|---|---|
| 行覆盖率 | 80%+ | 60%+(逐步改善) |
| 分支覆盖率 | 60%+ | 40%+(逐步改善) |
| 最大 CRAP 分数 | 30 | 记录例外情况 |
| 高风险方法 | 必须有测试 | 修改前添加测试 |
排除的内容
推荐的 coverage.runsettings 排除:
| 模式 | 原因 |
|---|---|
[*.Tests]* | 测试程序集不是生产代码 |
[*.Benchmark]* | 基准测试项目 |
[*.Migrations]* | 数据库迁移(生成的) |
GeneratedCodeAttribute | 源生成器 |
CompilerGeneratedAttribute | 编译器生成的代码 |
ExcludeFromCodeCoverageAttribute | 开发者显式选择退出 |
*.g.cs, *.designer.cs | 生成的文件 |
*.razor.g.cs | Blazor 组件生成的代码 |
*.razor.css.g.cs | Blazor CSS 隔离生成的代码 |
**/Migrations/**/* | EF Core 迁移(自动生成) |
SkipAutoProps | 自动属性(琐碎分支) |
何时更新阈值
临时降低阈值的情况:
- 正在现代化的遗留代码库(在 README 中记录)
- 无法修改的生成代码
- 第三方包装代码
永远不要降低阈值的情况:
- “测试太难了”——改为重构
- “我们稍后再添加测试”——现在添加
- 新功能——应该从一开始就满足标准
更多资源
- Coverlet 文档:https://github.com/coverlet-coverage/coverlet
- ReportGenerator:https://github.com/danielpalme/ReportGenerator
- CRAP 分数原始论文:http://www.artima.com/weblogs/viewpost.jsp?thread=215899