【本文前提是了解maven项目及其Pom.xml机制,不熟悉可以看该博客的0.Pre部分Auto-Unit-Test-Case-Generator -- java项目自动测试生成-CSDN博客】
JaCoCo(Java Code Coverage)是一个开源的代码覆盖率工具,专门用于测量 Java 应用程序的代码覆盖率。
注意,测试覆盖率自然是在src/test目录下的某个包/类:
myproject/
├── .gitignore
├── pom.xml
├── README.md
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── MyMainClass.java
│ │ ├── resources/
│ │ │ ├── application.properties
│ │ │ └── log4j.properties
│ │ └── webapp/
│ │ ├── WEB-INF/
│ │ │ └── classes/
│ │ └── index.html
│ └── test/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── MyMainClassTest.java
│ └── resources/
│ └── test-application.properties
└── target/├── classes/│ ├── com/│ │ └── example/│ │ └── MyMainClass.class│ ├── application.properties│ └── log4j.properties├── generated-sources/├── maven-archiver/│ └── pom.properties├── maven-status/├── test-classes/├── test/│ └── com/│ └── example/│ └── MyMainClassTest.class├── surefire-reports/└── classes/
Step1:准备工作-修改pom.xml:
1.1 添加插件1--maven-surefire-plugin:
【注意{argLine}】
插件添加位置:如前文的项目树状图,我要测试myproject,那就在同级的pom.xml内添加即可,下同;
通过使用
${argLine}
,你可以在其他地方(如父 POM 或其他插件配置)定义的argLine
值被继承下来。这使得你可以集中管理 JVM 参数,而不是在每个插件配置中重复定义。
<build><plugins> <!-- 以下是需要复制的内容,以上是方便查找复制的位置--> <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>2.22.2</version><configuration><argLine> ${argLine} </argLine><forkCount>4</forkCount><reuseForks>true</reuseForks> </configuration></plugin>
1.2 添加插件2--Jacoco:
<build><plugins> <!-- 以下是需要复制的内容,以上是方便查找复制的位置-->
<plugin><groupId>org.jacoco</groupId><artifactId>jacoco-maven-plugin</artifactId><version>0.8.7</version><executions><execution><id>pre-test</id><goals><goal>prepare-agent</goal></goals></execution><execution><id>post-test</id><phase>test</phase><goals><goal>report</goal></goals></execution></executions>
</plugin>
Step2:运行如下命令:
执行路径在: src/test下的某级目录;如下图,我是在子模块目录下执行的;
mvn test jacoco:report
2.1 运行结果:
[INFO] --- jacoco-maven-plugin:0.8.7:report (post-test) @ aa-bb-xx ---
[INFO] Loading execution data file /home/xx/target/jacoco.exec
[INFO] Analyzed bundle 'aa :: bb :: xx' with 133 classes
[INFO] BUILD SUCCESS
2.1.2如果 报错如下,那就是没有加{argLine}的原因:
[INFO] --- jacoco-maven-plugin:0.8.7:report (report) @ aa-bb-xx ---
[INFO] Skipping JaCoCo execution due to missing execution data file.
报错解释:
意味着 JaCoCo 插件在尝试生成覆盖率报告时没有找到必要的执行数据文件。通常,JaCoCo 会在运行测试时生成一个或多个执行数据文件(通常是
.exec
文件),这些文件包含了覆盖率信息。如果这些文件不存在或找不到,JaCoCo 插件就无法生成覆盖率报告。
Step3:覆盖率报告文件位置:
生成/target/site/jacoco/; 其中的index.html打开即可看到覆盖率报告;
附:dependency vs plugin:
- 依赖项[通过
<dependencies>
标签配置],项目运行/构建过程中需要的库.e.g.函数需要的库- 构建插件[通过
<plugins>
标签配置] ,执行特定任务的工具.e.g.生成测试覆盖率报告