sonarqube支持多种代码覆盖率的报告展示,最常用的当属jacoco报告,那么jacoco的报告怎么同步到我们的sonarqube中呢?
我们先看看jacoco的offline模式(单元测试)报告生成的流程
根据上图我们需要生成单测报告,有两个关键点:
- 触发单测
- 触发jacoco生成报告
为了实现上述功能,我们首先需要对我们工程进行改造
- 引入jacoco插件(只需引入插件即可)
<plugin><groupId>org.jacoco</groupId><artifactId>jacoco-maven-plugin</artifactId><version>0.8.7</version><configuration><!--指定生成.exec文件的存放位置--><destFile>target/coverage-reports/jacoco-unit.exec</destFile><!--Jacoco是根据.exec文件生成最终的报告,所以需指定.exec的存放路径--><dataFile>target/coverage-reports/jacoco-unit.exec</dataFile><includes><include>com/dr/jacoco/services/**</include></includes><excludes><exclude>META-INF/**</exclude></excludes></configuration><executions><execution><id>jacoco-initialize</id><goals><goal>prepare-agent</goal></goals><phase>test-compile</phase></execution><execution><id>jacoco-site</id><phase>verify</phase><goals><goal>report</goal></goals></execution></executions></plugin>
这里我们看看配置的两个关键点,当生命周期test-compile,即单测编译时触发jacoco的初始化,当生命周期verify时就对jacoco报告进行生成
- 执行sonar命令
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.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>2.19.1</version><configuration><skipTests>false</skipTests></configuration><dependencies><dependency><groupId>org.apache.maven.surefire</groupId><artifactId>surefire-junit47</artifactId><version>2.19.1</version></dependency><dependency><groupId>org.junit.platform</groupId><artifactId>junit-platform-surefire-provider</artifactId><version>1.1.0</version></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>5.1.0</version></dependency></dependencies></plugin>
版权归原作者 dray_ 所有, 如有侵权,请联系我们删除。