Community编程与开发github.com

CRAP 分析

分析代码覆盖率和 CRAP(变更风险反模式)分数,识别高风险代码。使用 OpenCover 格式配合 ReportGenerator 生成风险热点图,展示圈复杂度和未测试代码路径。

CRAP 分析 是什么?

该技能提供了一套完整的 .NET 项目代码质量和风险分析方法,核心是 CRAP(Change Risk Anti-Patterns)分数——一种结合圈复杂度和测试覆盖率的指标。它帮助开发者快速定位高风险代码区域:高复杂度且低覆盖率的代码被视为变更风险极高,需要优先进行测试或重构。技能支持通过 `coverage.runsettings` 配置 OpenCover 格式的覆盖率收集(必备,因为 OpenCover 包含计算 CRAP 所需的复杂度数据),并使用 ReportGenerator 生成包含“风险热点”模块的 HTML 报告,按复杂度排序展示方法。此外,还提供了 CI/CD 集成范例(GitHub Actions、Azure Pipelines)、推荐阈值标准(行覆盖率 >80%、分支覆盖率 >60%、CRAP <30)以及排除生成代码和测试项目的配置模板。整个技能适用于 Cursor、Claude Code、Codex 等 AI Agent,能在开发工作流中自动执行覆盖率收集、报告生成和风险分析。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/crap-analysis

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

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()10%1 x (1 - 0)^21
ParseToken()5452%54 x (1 - 0.52)^212.4
ValidateForm()200%20 x (1 - 0)^220
ProcessOrder()4520%45 x (1 - 0.20)^228.8
ImportData()8010%80 x (1 - 0.10)^264.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 的 Markdowncoverage/SummaryGithub.md
Badges用于 README 的 SVG 徽章coverage/badge_*.svg
Cobertura合并后的 Cobertura XMLcoverage/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.csBlazor 组件生成的代码
*.razor.css.g.csBlazor CSS 隔离生成的代码
**/Migrations/**/*EF Core 迁移(自动生成)
SkipAutoProps自动属性(琐碎分支)

何时更新阈值

临时降低阈值的情况:

  • 正在现代化的遗留代码库(在 README 中记录)
  • 无法修改的生成代码
  • 第三方包装代码

永远不要降低阈值的情况:

  • “测试太难了”——改为重构
  • “我们稍后再添加测试”——现在添加
  • 新功能——应该从一开始就满足标准

更多资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

相关技能