在 Spring Boot 多模块项目中配置 JaCoCo(Java Code Coverage)可以实现对代码覆盖率的统计和分析。以下是一个完整的配置指南,帮助你在多模块项目中正确配置 JaCoCo。
假设你的 Spring Boot 多模块项目结构如下:
my-springboot-project
├── parent (父模块)
├── module-a (模块 A)
├── module-b (模块 B)
└── module-c (模块 C)
其中:
parent
是父模块,定义了所有子模块的依赖管理和插件配置。module-a
、module-b
和 module-c
是具体的业务模块。parent
中配置 JaCoCo 插件在父模块的 pom.xml
文件中,定义 JaCoCo 插件的全局配置。这样可以确保所有子模块都能继承该配置。
<project>
<modelVersion>4.0.0modelVersion>
<groupId>com.examplegroupId>
<artifactId>parentartifactId>
<version>1.0.0-SNAPSHOTversion>
<packaging>pompackaging>
<properties>
<jacoco.version>0.8.10jacoco.version>
properties>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.jacocogroupId>
<artifactId>jacoco-maven-pluginartifactId>
<version>${jacoco.version}version>
<executions>
<execution>
<id>prepare-agentid>
<goals>
<goal>prepare-agentgoal>
goals>
execution>
<execution>
<id>reportid>
<phase>testphase>
<goals>
<goal>reportgoal>
goals>
execution>
executions>
plugin>
plugins>
pluginManagement>
build>
project>
在每个需要统计代码覆盖率的子模块(如 module-a
、module-b
和 module-c
)中,引入 JaCoCo 插件并启用它。
以 module-a
的 pom.xml
为例:
<project>
<parent>
<groupId>com.examplegroupId>
<artifactId>parentartifactId>
<version>1.0.0-SNAPSHOTversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>module-aartifactId>
<build>
<plugins>
<plugin>
<groupId>org.jacocogroupId>
<artifactId>jacoco-maven-pluginartifactId>
plugin>
plugins>
build>
project>
重复上述步骤,在其他子模块(如 module-b
和 module-c
)中也进行类似的配置。
如果你希望生成整个项目的汇总代码覆盖率报告,可以在父模块或一个专门的聚合模块中添加额外的 JaCoCo 配置。
例如,在父模块的 pom.xml
中添加以下内容:
<build>
<plugins>
<plugin>
<groupId>org.jacocogroupId>
<artifactId>jacoco-maven-pluginartifactId>
<executions>
<execution>
<id>merge-resultsid>
<phase>verifyphase>
<goals>
<goal>mergegoal>
goals>
<configuration>
<fileSets>
<fileSet>
<directory>module-a/targetdirectory>
<includes>
<include>*.execinclude>
includes>
fileSet>
<fileSet>
<directory>module-b/targetdirectory>
<includes>
<include>*.execinclude>
includes>
fileSet>
<fileSet>
<directory>module-c/targetdirectory>
<includes>
<include>*.execinclude>
includes>
fileSet>
fileSets>
configuration>
execution>
<execution>
<id>generate-reportid>
<phase>verifyphase>
<goals>
<goal>reportgoal>
goals>
execution>
executions>
plugin>
plugins>
build>
在某个子模块下运行以下命令,生成该模块的代码覆盖率报告:
mvn clean test
生成的报告会存储在 target/site/jacoco/index.html
文件中。
在父模块下运行以下命令,生成整个项目的代码覆盖率报告:
mvn clean verify
如果配置了合并功能,最终的汇总报告会存储在父模块的 target/site/jacoco/index.html
文件中。
JaCoCo 自动生成的 HTML 报告位于目标目录中,例如:
module-a/target/site/jacoco/index.html
parent/target/site/jacoco/index.html
打开 index.html
文件即可查看详细的代码覆盖率统计信息。
原因:可能是测试用例未覆盖任何代码,或者测试未正确运行。
解决方法:检查测试用例是否正常执行,并确保测试用例覆盖了目标代码。
原因:可能是因为 .exec
文件未正确生成或未被正确合并。
解决方法:检查子模块的 target
目录中是否存在 .exec
文件,并确保合并配置正确。
原因:不同模块可能使用了不同版本的 JaCoCo 插件。
解决方法:统一在父模块中定义 JaCoCo 插件版本,避免版本冲突。
通过以上步骤,你可以在 Spring Boot 多模块项目中成功配置 JaCoCo,生成详细的代码覆盖率报告。
【Java知识】使用jacoco实现代码覆盖率测试