本文將從以下幾個方面介紹如何在 Spring Boot 中集成 Jacoco:1、Jacoco 概述;2、Spring Boot 集成 Jacoco 的配置;3、生成 Jacoco 報告。
一、Jacoco 概述
Jacoco 是一個開源的覆蓋率測試工具,它可以幫助開發人員在開發過程中對代碼的覆蓋率進行測試和監控。Jacoco 可以生成三種類型的報告:HTML、XML 和 CSV,其中 HTML 報告是最常見的。
Jacoco 的工作原理是通過在編譯時在代碼中插入一個 Java Agent,當應用程序運行時,該 Agent 會在內存中動態生成一個代理類,該類會檢測代碼被執行的情況,並將覆蓋率信息收集到一個文件中。
二、Spring Boot 集成 Jacoco 的配置
1、添加依賴
在 pom.xml 文件中添加 Jacoco 依賴:
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.5</version>
</dependency>
2、配置插件
在 pom.xml 文件中添加 Jacoco 插件的配置:
<build>
<plugins>
<!-- Jacoco -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.5</version>
<executions>
<execution>
<id>jacoco-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-report</id>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>jacoco-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>CLASS</element>
<excludes>
<exclude>*</exclude>
</excludes>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.80</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
這裡定義了 3 個 Jacoco 的插件執行項:
- jacoco-prepare-agent:這個任務會執行 prepare-agent 目標,它會在編譯時將 Jacoco 的 Jar 包指定到 Java Agent 中,同時指定一個存放報告的文件。
- jacoco-report:這個任務會執行 report 目標,它會生成一個 HTML 報告,並將其保存到指定的目錄中。
- jacoco-check:這個任務會執行 check 目標,它會檢查代碼覆蓋率是否達到指定的要求。
3、設置 Jacoco 配置文件
在 src/main/resources 目錄下添加一個 jacoco-agent.properties 文件,設置 Jacoco 相關的配置:
destfile=target/jacoco.exec output=file
這個配置文件指定了報告文件存放的位置和格式。
4、修改測試任務
在 pom.xml 文件中修改測試任務配置,添加 Jacoco 插件:
<build>
<plugins>
<!-- Maven Surefire Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<systemProperties>
<property>
<name>jacoco-agent.destfile</name>
<value>${project.build.directory}/jacoco.exec</value>
</property>
<property>
<name>jacoco-agent.output</name>
<value>file</value>
</property>
</systemProperties>
</configuration>
<dependencies>
<dependency>
<groupId>org.jacoco.agent</groupId>
<artifactId>jacoco-agent-runtime</artifactId>
<version>0.8.5</version>
<scope>test</scope>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
這個配置將 Jacoco Agent 的參數傳遞給 Maven 的 Surefire 插件,以便在測試時收集覆蓋率信息。
三、生成 Jacoco 報告
在項目的根目錄下執行以下命令:
mvn clean verify
執行結束後,在 target/site 目錄下就能找到 Jacoco 的 HTML 報告了。在瀏覽器中打開 index.html 即可查看報告。
四、總結
本文介紹了如何在 Spring Boot 中集成 Jacoco 來檢測代碼的覆蓋率,並生成 Jacoco 報告。通過閱讀本文,我們學習了 Jacoco 的概念以及如何在 Maven 項目中配置 Jacoco 插件。
原創文章,作者:CZCKG,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/375531.html
微信掃一掃
支付寶掃一掃