Sonar Unit and Integration Test Coverage with Maven

Lots of posts on the web about this, few seem to work. Here is my config, which works.

First, configuration of the maven sonar plugin:

<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>  <!-- Ensure you run mvn install before sonar:sonar -->
<sonar.java.codeCoveragePlugin>jacoco</sonar.java.codeCoveragePlugin>
<sonar.surefire.reportsPath>/target/surefire-reports</sonar.surefire.reportsPath>
<sonar.jacoco.reportPath>target/jacoco.exec</sonar.jacoco.reportPath>    <!-- This is the default, put here to be explicit -->
<sonar.jacoco.itReportPath>target/jacoco-it.exec</sonar.jacoco.itReportPath>

Next, the Jacoco plugin. Here we use the default output file for unit tests, and a separate output file for integration tests:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.6.2.201302030002</version>
    <executions>
        <execution>
            <id>pre-unit-test</id>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
        </execution>
        <execution>
            <id>post-unit-test</id>
            <phase>test</phase>
            <goals>
                <goal>report</goal>
            </goals>
        </execution>
        <execution>
            <id>pre-integration-test</id>
            <phase>pre-integration-test</phase>
            <goals>
                <goal>prepare-agent</goal>
            </goals>
            <configuration>
                <destFile>target/jacoco-it.exec</destFile>
                <propertyName>failsafe.argLine</propertyName>
            </configuration>
        </execution>
        <execution>
            <id>post-integration-test</id>
            <phase>post-integration-test</phase>
            <goals>
                <goal>report</goal>
            </goals>
            <configuration>
                <dataFile>target/jacoco-it.exec</dataFile>
            </configuration>
        </execution>
    </executions>
</plugin>

Finally, the failsafe plugin. This ensures tests will be instrumented during the integration test phase, and the results collected during the verify phase. The reference to argLine is critical, because this causes failsafe to write to the correct Jacoco output file.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.14</version>
    <configuration>
        <argLine>${failsafe.argLine}</argLine>
    </configuration>
    <executions>
        <execution>
            <id>integration-test</id>
            <goals>
                <goal>integration-test</goal>
            </goals>
        </execution>
        <execution>
            <id>verify</id>
            <goals>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>
Advertisements