sonarqube支持多种代码覆盖率的报告展示,最常用的当属jacoco报告,那么jacoco的报告怎么同步到我们的sonarqube中呢?
我们先看看jacoco的offline模式(单元测试)报告生成的流程
根据上图我们需要生成单测报告,有两个关键点:
为了实现上述功能,我们首先需要对我们工程进行改造
<plugin>
<groupId>org.jacocogroupId>
<artifactId>jacoco-maven-pluginartifactId>
<version>0.8.7version>
<configuration>
<destFile>target/coverage-reports/jacoco-unit.execdestFile>
<dataFile>target/coverage-reports/jacoco-unit.execdataFile>
<includes>
<include>com/dr/jacoco/services/**include>
includes>
<excludes>
<exclude>META-INF/**exclude>
excludes>
configuration>
<executions>
<execution>
<id>jacoco-initializeid>
<goals>
<goal>prepare-agentgoal>
goals>
<phase>test-compilephase>
execution>
<execution>
<id>jacoco-siteid>
<phase>verifyphase>
<goals>
<goal>reportgoal>
goals>
execution>
executions>
plugin>
这里我们看看配置的两个关键点,当生命周期test-compile,即单测编译时触发jacoco的初始化,当生命周期verify时就对jacoco报告进行生成
mvn clean verify sonar:sonar \
-Dsonar.host.url=http://*******.com \
-Dsonar.login=********** \
-Dsonar.projectKey=jacoco-demo \
-Dsonar.projectName=jacoco-demo \
-Dsonar.java.source=1.8 \
-Dsonar.branch.name=master \
-Dsonar.java.coveragePlugin=jacoco \
-Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
此命令会触发单测,verify命令会触发报告,然后通过
-Dsonar.java.coveragePlugin=jacoco
-Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
指定报告类型和报告的本地路径就可以轻松上传报告到jacoco
使用上就是这么简单,当然在集成上也会有一些坑,比如springboot运行junit5会出现无法触发的问题等
,据说是版本不兼容的问题,我们只需通过pom指定版本就可解决
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-surefire-pluginartifactId>
<version>2.19.1version>
<configuration>
<skipTests>falseskipTests>
configuration>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefiregroupId>
<artifactId>surefire-junit47artifactId>
<version>2.19.1version>
dependency>
<dependency>
<groupId>org.junit.platformgroupId>
<artifactId>junit-platform-surefire-providerartifactId>
<version>1.1.0version>
dependency>
<dependency>
<groupId>org.junit.jupitergroupId>
<artifactId>junit-jupiter-engineartifactId>
<version>5.1.0version>
dependency>
dependencies>
plugin>