在 java 单元测试中统计代码覆盖率,核心做法是配置 jacoco maven 插件并在测试执行时注入代理。具体操作是在 pom.xml 的 build/plugins 中添加 jacoco-maven-plugin,然后运行 mvn test jacoco:report 命令即可生成报告。jacoco 通过字节码插桩技术记录执行路径,无需修改业务代码,直接输出 html 和 xml 格式的覆盖率数据。

JaCoCo 插件如何集成到 Maven 构建流程
JaCoCo 插件集成到 Maven 流程主要依赖 pre-unit-test 和 post-unit-test 两个生命周期阶段。在 pre-unit-test 阶段,插件启动 JVM 代理并指定 destfile 用于存储执行数据;在 post-unit-test 阶段,插件读取该数据文件并生成最终报告。这种机制确保了测试运行时产生的覆盖率数据能被准确捕获并持久化。

<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<executions>
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<destFile>${project.build.directory}/jacoco.exec</destFile>
</configuration>
</execution>
<execution>
<id>post-unit-test</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${project.build.directory}/jacoco.exec</dataFile>
<outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
JaCoCo 如何处理多模块项目的覆盖率聚合
在多模块项目中,JaCoCo 处理覆盖率聚合需要启用 setProperties 目标来收集各子模块的执行数据。父模块通过 check 或 report-aggregate 目标汇总所有子模块的 .exec 文件。这种方式避免了重复计算,确保整体项目的覆盖率统计准确反映所有子模块的代码执行情况。
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。
立即学习“Java免费学习笔记(深入)”;

<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<executions>
<execution>
<id>collect-data</id>
<phase>verify</phase>
<goals>
<goal>set-properties</goal>
</goals>
</execution>
<execution>
<id>aggregate-report</id>
<phase>verify</phase>
<goals>
<goal>report-aggregate</goal>
</goals>
</execution>
</executions>
</plugin>
JaCoCo 报告中 Branch Coverage 的具体判定逻辑是什么
JaCoCo 报告中 Branch Coverage 的判定逻辑基于控制流图中的每个分支节点。对于 if、switch 等语句,JaCoCo 会检查每个可能的出口是否被至少一次执行覆盖。如果某个分支(如 true 或 false)从未被执行,则该分支被视为未覆盖。判定结果仅依赖于运行时实际触发的路径,与静态分析无关。

















