Let’s assume a few think before we begin.
- SonarQube is installed somewhere and works.
- The task « Invoke Standalone Sonar Analysis » is available in Jenkins.
- Your project is using Maven so it has a pom.xml.
To begin, we’ll add configuration in our pom.xml.
<properties> <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin> <sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath> <sonar.language>java</sonar.language> </properties>
We’re using JUnit to run tests.
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies>
Now, we configure our plugins.
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.2.201409121644</version> <configuration> <append>true</append> </configuration> <executions> <execution> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>post-unit-test</id> <phase>test</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
Everything should be good regarding Maven configuration, so we’ll switch to Jenkins configuration. In your job, you should add the task « Invoke Standalone Sonar Analysis ». The interesting part is the « project properties » field.
# Metadata sonar.projectName=${JOB_NAME} sonar.projectVersion=1.0.0 # Source information sonar.sources=src/main sonar.sourceEncoding=UTF-8 sonar.language=java # Tests sonar.tests=src/test sonar.junit.reportsPath=target/surefire-reports sonar.surefire.reportsPath=target/surefire-reports sonar.jacoco.reportPath=target/jacoco.exec sonar.binaries=target/classes sonar.java.coveragePlugin=jacoco # Debug sonar.verbose=true
Don’t forget sonar.binaries, otherwise, you might get something like « Project coverage is set to 0% since there is no directories with classes. » in your logs.
In addition, if I’m doing a mvn clean test, I get the following files in directory target (among others):
- classes/
- surefire-reports/
- jacoco.exec
Using this setup, I manage to display information regarding test coverage and test execution. Besides, there might be some duplicate as for sonar.surefire.reportsPath and sonar.junit.reportsPath in sonar properties.