使用jacoco实现单元测试覆盖率检测

it2024-03-16  58

1、pom文件配置

1.1 maven中添加依赖项

<dependency> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.2</version> </dependency>

1.2 maven中添加插件

<plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.2</version> <configuration> <destFile>target/coverage-reports/jacoco-unit.exec</destFile> <dataFile>target/coverage-reports/jacoco-unit.exec</dataFile> <includes> <include>**/service/**</include> <include>**/controller/**</include> <!--<include>**/service/impl/*.class</include>--> </includes> <!-- rules里面指定覆盖规则 --> <rules> <rule implementation="org.jacoco.maven.RuleConfiguration"> <element>BUNDLE</element> <!--<limits>  --> <!--&lt;!&ndash; 指定方法覆盖到50% &ndash;&gt;--> <!--<limit implementation="org.jacoco.report.check.Limit">--> <!--<counter>METHOD</counter>--> <!--<value>COVEREDRATIO</value>--> <!--<minimum>0.50</minimum>--> <!--</limit>--> <!--&lt;!&ndash; 指定分支覆盖到50% &ndash;&gt;--> <!--<limit implementation="org.jacoco.report.check.Limit">--> <!--<counter>BRANCH</counter>--> <!--<value>COVEREDRATIO</value>--> <!--<minimum>0.50</minimum>--> <!--</limit>--> <!--&lt;!&ndash; 指定类覆盖到100%,不能遗失任何类 &ndash;&gt;--> <!--<limit implementation="org.jacoco.report.check.Limit">--> <!--<counter>CLASS</counter>--> <!--<value>MISSEDCOUNT</value>--> <!--<maximum>0</maximum>--> <!--</limit>--> <!--</limits>--> </rule> </rules> </configuration> <executions> <execution> <id>jacoco-initialize</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <!--这个check:对代码进行检测,控制项目构建成功还是失败--> <execution> <id>check</id> <goals> <goal>check</goal> </goals> </execution> <!--这个report:对代码进行检测,然后生成index.html在 target/site/index.html中可以查看检测的详细结果--> <execution> <id>jacoco-site</id> <phase>package</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin>

2、生成单元测试覆盖率报告

可以直接使用mvn install 命令执行并生成报告。

mvn install

 也可以在idea编辑环境中选择install命令使用:

3、报告示例

报告生成位置为target目录下的/site/jacoco文件夹中,在浏览器中打开文件index.html即可查看报告内容。

可以查看各个文件类的覆盖率,及各个方法函数的覆盖率

也可以查询具体文件的代码单元测试覆盖情况 ,绿色标记的为测试用例覆盖到的代码,红色为未覆盖到的代码。

4、未生成报告问题处理

如果使用mvn install 命令未生成报告,可能需要添加 maven-surefire-plugin 插件

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.19.1</version> <configuration> <reuseForks>false</reuseForks> <forkCount>1</forkCount> </configuration> </plugin>

 

最新回复(0)