CRAP 分數分析
使用時機
在以下情況使用此技能:
- 在進行變更前評估程式碼品質與測試涵蓋率
- 識別需要重構或測試的高風險程式碼
- 為 .NET 專案設定涵蓋率收集
- 根據風險優先排序需測試的程式碼
- 為 CI/CD 管道建立涵蓋率閾值
什麼是 CRAP?
CRAP 分數 = 複雜度 × (1 - 涵蓋率)²
CRAP(變更風險反模式)分數結合循環複雜度與測試涵蓋率,以識別有風險的程式碼。
| CRAP 分數 | 風險等級 | 需採取的行動 |
|---|---|---|
| < 5 | 低 | 測試良好、可維護的程式碼 |
| 5-30 | 中 | 可接受,但需留意複雜度 |
| > 30 | 高 | 需要測試或重構 |
為什麼 CRAP 很重要
- 高複雜度 + 低涵蓋率 = 危險:難以理解且未經測試的程式碼,修改起來很危險
- 僅靠複雜度不夠:一個 100% 涵蓋率的複雜方法,比一個 0% 涵蓋率的簡單方法更安全
- 聚焦努力:優先測試複雜的程式碼,而非簡單的 getter/setter
CRAP 分數範例
| 方法 | 複雜度 | 涵蓋率 | 計算 | CRAP |
|---|---|---|---|---|
GetUserId() | 1 | 0% | 1 x (1 - 0)² | 1 |
ParseToken() | 54 | 52% | 54 x (1 - 0.52)² | 12.4 |
ValidateForm() | 20 | 0% | 20 x (1 - 0)² | 20 |
ProcessOrder() | 45 | 20% | 45 x (1 - 0.20)² | 28.8 |
ImportData() | 80 | 10% | 80 x (1 - 0.10)² | 64.8 |
涵蓋率收集設定
coverage.runsettings
在儲存庫根目錄中建立 coverage.runsettings 檔案。必須使用 OpenCover 格式才能計算 CRAP 分數,因為它包含循環複雜度指標。
<?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 報表包含一個風險熱點區段,顯示依複雜度排序的方法:
- 循環複雜度:程式碼中獨立路徑的數量(if/else、switch 情況、迴圈)
- 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
# 開啟 HTML 報表(Linux)
xdg-open coverage/index.html
# 開啟 HTML 報表(macOS)
open coverage/index.html
# 開啟 HTML 報表(Windows)
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