java-coverage

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Java Coverage

Java代码覆盖率

JaCoCo code coverage configuration for Java/Gradle projects.
适用于Java/Gradle项目的JaCoCo代码覆盖率配置。

When to use this skill

何时使用本技能

  • Setting up code coverage reporting
  • Configuring coverage thresholds
  • Aggregating coverage across modules
  • Integrating with SonarQube
  • Troubleshooting coverage reports
  • When asked to "improve test coverage"
  • 搭建代码覆盖率报告体系
  • 配置覆盖率阈值
  • 聚合多模块覆盖率数据
  • 与SonarQube集成
  • 排查覆盖率报告相关问题
  • 收到「提升测试覆盖率」需求时

Skill Contents

技能内容

Sections

章节

Available Resources

可用资源

references/ - Detailed documentation
  • coverage targets
  • coverage via mcp
  • exclusion patterns
  • improvement workflow
  • multi module
  • prioritization

references/ - 详细文档
  • 覆盖率目标
  • 通过MCP查询覆盖率
  • 排除模式
  • 优化工作流
  • 多模块配置
  • 优先级排序

Quick Start

快速入门

1. Apply JaCoCo Plugin

1. 应用JaCoCo插件

groovy
plugins {
    id 'jacoco'
}

jacoco {
    toolVersion = "0.8.14"
}
groovy
plugins {
    id 'jacoco'
}

jacoco {
    toolVersion = "0.8.14"
}

2. Configure Report Task

2. 配置报告任务

groovy
jacocoTestReport {
    dependsOn test

    reports {
        xml.required = true  // For SonarQube
        html.required = true // For local viewing
    }
}

test {
    finalizedBy jacocoTestReport
}
groovy
jacocoTestReport {
    dependsOn test

    reports {
        xml.required = true  // For SonarQube
        html.required = true // For local viewing
    }
}

test {
    finalizedBy jacocoTestReport
}

3. Run Coverage

3. 执行覆盖率检测

bash
./gradlew test jacocoTestReport
bash
./gradlew test jacocoTestReport

Report at: build/reports/jacoco/test/html/index.html

Report at: build/reports/jacoco/test/html/index.html

undefined
undefined

Coverage Thresholds

覆盖率阈值

groovy
jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = 0.80  // 80% minimum coverage
            }
        }

        rule {
            element = 'CLASS'
            excludes = ['*.generated.*', '*.config.*']
            limit {
                counter = 'LINE'
                minimum = 0.70
            }
        }
    }
}

check.dependsOn jacocoTestCoverageVerification
groovy
jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = 0.80  // 80% minimum coverage
            }
        }

        rule {
            element = 'CLASS'
            excludes = ['*.generated.*', '*.config.*']
            limit {
                counter = 'LINE'
                minimum = 0.70
            }
        }
    }
}

check.dependsOn jacocoTestCoverageVerification

Exclusions

排除规则

Common patterns to exclude from coverage:
groovy
jacocoTestReport {
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: [
                '**/generated/**',
                '**/config/**',
                '**/*Config.class',
                '**/*Properties.class',
                '**/Application.class'
            ])
        }))
    }
}
常见的覆盖率排除模式:
groovy
jacocoTestReport {
    afterEvaluate {
        classDirectories.setFrom(files(classDirectories.files.collect {
            fileTree(dir: it, exclude: [
                '**/generated/**',
                '**/config/**',
                '**/*Config.class',
                '**/*Properties.class',
                '**/Application.class'
            ])
        }))
    }
}

Multi-Module Aggregation

多模块聚合

For aggregated reports across modules, use the modern
jacoco-report-aggregation
plugin (Gradle 7.4+):
groovy
// In root build.gradle
plugins {
    id 'base'
    id 'jacoco-report-aggregation'
}

// Ensure subprojects are evaluated first
subprojects.each { evaluationDependsOn(it.path) }

dependencies {
    subprojects.each { jacocoAggregation it }
}

reporting {
    reports {
        testCodeCoverageReport(JacocoCoverageReport) {
            testType = TestSuiteType.UNIT_TEST
        }
    }
}
For older Gradle versions, use a manual task with defensive filtering:
groovy
// In root build.gradle (Gradle < 7.4)
task jacocoRootReport(type: JacocoReport) {
    dependsOn subprojects*.test

    // Use defensive filtering to avoid missing-directory errors
    def srcDirs = files(subprojects*.sourceSets*.main*.allSource*.srcDirs).filter { it.exists() }
    def classDirs = files(subprojects*.sourceSets*.main*.output).filter { it.exists() }
    def execData = files(subprojects*.jacocoTestReport*.executionData).filter { it.exists() }

    additionalSourceDirs.from(srcDirs)
    sourceDirectories.from(srcDirs)
    classDirectories.from(classDirs)
    executionData.from(execData)

    reports {
        xml.required = true
        html.required = true
    }
}
如需生成跨模块的聚合报告,请使用新版
jacoco-report-aggregation
插件(适用于Gradle 7.4及以上版本):
groovy
// In root build.gradle
plugins {
    id 'base'
    id 'jacoco-report-aggregation'
}

// Ensure subprojects are evaluated first
subprojects.each { evaluationDependsOn(it.path) }

dependencies {
    subprojects.each { jacocoAggregation it }
}

reporting {
    reports {
        testCodeCoverageReport(JacocoCoverageReport) {
            testType = TestSuiteType.UNIT_TEST
        }
    }
}
针对旧版本Gradle,可使用带防御性过滤的手动任务:
groovy
// In root build.gradle (Gradle < 7.4)
task jacocoRootReport(type: JacocoReport) {
    dependsOn subprojects*.test

    // Use defensive filtering to avoid missing-directory errors
    def srcDirs = files(subprojects*.sourceSets*.main*.allSource*.srcDirs).filter { it.exists() }
    def classDirs = files(subprojects*.sourceSets*.main*.output).filter { it.exists() }
    def execData = files(subprojects*.jacocoTestReport*.executionData).filter { it.exists() }

    additionalSourceDirs.from(srcDirs)
    sourceDirectories.from(srcDirs)
    classDirectories.from(classDirs)
    executionData.from(execData)

    reports {
        xml.required = true
        html.required = true
    }
}

SonarQube Integration

SonarQube集成

groovy
sonar {
    properties {
        property 'sonar.coverage.jacoco.xmlReportPaths',
            "${projectDir}/build/reports/jacoco/test/jacocoTestReport.xml"
    }
}
groovy
sonar {
    properties {
        property 'sonar.coverage.jacoco.xmlReportPaths',
            "${projectDir}/build/reports/jacoco/test/jacocoTestReport.xml"
    }
}

Checking Coverage via SonarQube MCP

通过SonarQube MCP查询覆盖率

Instead of running local JaCoCo builds to check current coverage state, use SonarQube MCP tools for faster feedback:
ToolPurpose
search_files_by_coverage
Find files with lowest coverage
get_file_coverage_details
Line-by-line coverage for a specific file
get_component_measures
Project/module-level coverage metric
get_project_quality_gate_status
Check if coverage gate passes
text
undefined
无需在本地运行JaCoCo构建即可查询当前覆盖率状态,使用SonarQube MCP工具可以更快获得反馈:
工具用途
search_files_by_coverage
查找覆盖率最低的文件
get_file_coverage_details
查询指定文件的行级覆盖率详情
get_component_measures
查询项目/模块级的覆盖率指标
get_project_quality_gate_status
检查覆盖率门禁是否通过
text
undefined

Find low-coverage files

Find low-coverage files

search_files_by_coverage: projectKey: "my-service"
search_files_by_coverage: projectKey: "my-service"

Check specific file coverage

Check specific file coverage

get_file_coverage_details: key: "my-service:src/main/java/com/bitso/Service.java"
get_file_coverage_details: key: "my-service:src/main/java/com/bitso/Service.java"

Check overall coverage

Check overall coverage

get_component_measures: component: "my-service", metricKeys: ["coverage"]

MCP reflects the last CI analysis. Use JaCoCo locally to generate new coverage after writing tests.

See [fix-sonarqube coverage reference](.claude/skills/fix-sonarqube/references/coverage-via-mcp.md) for the full MCP coverage workflow.
get_component_measures: component: "my-service", metricKeys: ["coverage"]

MCP展示的是最近一次CI分析的结果,编写测试后请在本地运行JaCoCo生成最新的覆盖率报告。

查看[fix-sonarqube覆盖率参考](.claude/skills/fix-sonarqube/references/coverage-via-mcp.md)获取完整的MCP覆盖率查询工作流。

References

参考资料

ReferenceDescription
references/exclusion-patterns.mdCommon exclusion patterns
references/multi-module.mdMulti-module aggregation
参考资料描述
references/exclusion-patterns.md常用排除模式
references/multi-module.md多模块聚合配置

Related Rules

相关规则

  • java-jacoco-coverage - Full JaCoCo reference
  • java-jacoco-coverage - 完整JaCoCo参考文档

Related Skills

相关技能

SkillPurpose
java-testingTest configuration
fix-sonarqubeSonarQube setup
gradle-standardsGradle configuration
<!-- AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY --> <!-- Source: bitsoex/ai-code-instructions → java/skills/java-coverage/SKILL.md --> <!-- To modify, edit the source file and run the distribution workflow -->
技能用途
java-testing测试配置
fix-sonarqubeSonarQube搭建
gradle-standardsGradle配置规范
<!-- AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY --> <!-- Source: bitsoex/ai-code-instructions → java/skills/java-coverage/SKILL.md --> <!-- To modify, edit the source file and run the distribution workflow -->