Automatically enforce code coverage in a Maven project with JaCoCo
#java #mavenPut this in your POM file
<properties>
<!-- 0.90 = 90% minimum coverage -->
<jacoco-maven-plugin.minimum-coverage>0.90</jacoco-maven-plugin.minimum-coverage>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>set-artifact-path-properties</id>
<goals>
<goal>properties</goal>
</goals>
<phase>initialize</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>@{argLine}
-javaagent:${settings.localRepository}/org/mockito/mockito-core/${mockito.version}/mockito-core-${mockito.version}.jar
-Xshare:off</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco-maven-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<goals>
<goal>report</goal>
</goals>
<phase>test</phase>
</execution>
<execution>
<id>jacoco-check</id>
<goals>
<goal>check</goal>
</goals>
<phase>test</phase>
<configuration>
<rules>
<rule>
<element>PACKAGE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>${jacoco-maven-plugin.minimum-coverage}</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
The maven-dependency-plugin
& maven-surefire-plugin
bits aren't strictly related to adding code coverage, but it shows how to update the argLine
properly. In my example, I'm adding some extra config to ensure Mockito work with later versions of Java in addition to the code coverage config. You need to include @{argLine}
at the beginning to preserve whatever was added when the jacoco-maven-plugin:prepare-agent
goal runs.