Java持续集成(三)-- 为maven配置测试代码覆盖率并上传到sonar

Step1:在pom.xml配置新的profile来支持Jacoco插件

<!-- BEGIN: Specific to mapping unit tests and covered code -->

<profiles>

<profile>

<id>coverage-per-test</id>

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<!-- Minimal supported version is 2.4 -->

<version>2.13</version>

<configuration>

<properties>

<property>

<name>listener</name>

<value>org.sonar.java.jacoco.JUnitListener</value>

</property>

</properties>

</configuration>

</plugin>

</plugins>

</build>

<dependencies>

<dependency>

<groupId>org.sonarsource.java</groupId>

<artifactId>sonar-jacoco-listeners</artifactId>

<version>3.8</version>

<scope>test</scope>

</dependency>

</dependencies>

</profile>

</profiles>

<!-- END: Specific to mapping unit tests and covered code -->

Step2:在pom.xml配置sonar服务器链接

<properties> 
    <sonar.host.url>http://localhost:9000</sonar.host.url>
</properties>

Step3:运行单元测试及覆盖率分析

如果仅仅运行单元测试,不分析覆盖率:

mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install

如果运行单元测试的同时分析覆盖率:

mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install -Pcoverage-per-test

Step4:执行代码扫描,并上传覆盖率到sonar上

mvn sonar:sonar

正常情况下在sonar上面就能看到代码覆盖率和测试通过率了,如图:

演示

如果没有看到测试结果检查maven有没有一下输出:

 T E S T S

 Results :
 
 Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

如果没有的话,请pom.xml搜索<skipTest>true</skipTest>,然后删除掉。

Step5:提交代码提交单元测试及分析结果,更新Jenkins的配置

需要在Jenkins job里面添加相应的maven命令,这样子Jenkins才能自动分析代码覆盖率并上传到sonar.

猜你喜欢

转载自my.oschina.net/zhengweishan/blog/1797399