Step1: Configure a new profile in pom.xml to support Jacoco plugin
<!-- 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: Configure the sonar server link in pom.xml
<properties>
<sonar.host.url>http://localhost:9000</sonar.host.url>
</properties>
Step3: Run unit tests and coverage analysis
If only running unit tests without analyzing coverage:
mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install
If you run unit tests while analyzing coverage:
mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install -Pcoverage-per-test
Step4: Perform code scanning and upload coverage to sonar
mvn sonar:sonar
Under normal circumstances, you can see the code coverage and test pass rate on sonar, as shown in the figure:
If you don't see the test results, check if maven has the following output:
T E S T S
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
If not, please search <skipTest>true</skipTest> in pom.xml and delete it.
Step5: Submit code Submit unit test and analysis results, update Jenkins configuration
You need to add the corresponding maven command in the Jenkins job, so that Jenkins can automatically analyze the code coverage and upload it to sonar.