Java continuous integration (3) - configure test code coverage for maven and upload to sonar

Step 1: configure a new profile in pom.xml to support the Jacobo plug-in

<!-- 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 -->

Step 2: configure the sonar server link in pom.xml

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

Step 3: run unit test and coverage analysis

If you only run unit tests, do not analyze coverage:

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

If you run unit tests and analyze coverage at the same time:

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

Step 4: perform code scanning and upload coverage to sonar

mvn sonar:sonar

Under normal circumstances, code coverage and test pass rate can be seen on the sonar, as shown in the figure below:

If you don't see the test results, check whether maven has the following output:

 T E S T S

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

If not, search pom.xml for < skiptest > true < / skiptest > and delete it.

Step 5: submit code submission unit test and analysis results, and update Jenkins configuration

You need to add corresponding maven command in Jenkins job, so that sub Jenkins can automatically analyze code coverage and upload it to sonar

Keywords: Maven xml jenkins Java

Added by ShaunO on Fri, 03 Apr 2020 18:02:45 +0300