JaCoCo code coverage

Code coverage can be a useful tool but how can you set it up to not be too much of a burden on your developers? Simple, follow the recipe below and let your CI do the heavy lifting!

Add the Jacoco plugin to your pluginManagement section.


  <pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.8.1</version>
      </plugin>
    </plugins>
  </pluginManagement>
        

Create a coverage profile and add it to your top level POM


  <profiles>
    <profile>
      <id>coverage</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <inherited>true</inherited>
            <executions>
              <execution>
                <id>default-prepare-agent</id>
                <goals>
                  <goal>prepare-agent</goal>
                </goals>
              </execution>
              <execution>
                <id>default-report</id>
                <phase>prepare-package</phase>
                <goals>
                  <goal>report</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
      <modules>
        <module>coverage</module>
      </modules>
    </profile>
  </profiles>
        

Create the coverage module with the coverage aggregate report and add the other modules as dependencies


  <build>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>default-report-aggegrate</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>report-aggregate</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>            
        

Execute your Maven build with -P coverage and you can find the aggregate coverage report in the coverage module.

Posted April 19th, 2018

Up