Pages

17/10/2019

[Maven] Code coverage during build

If you want to generate code coverage reports during your build, you can use an analyzer that will scan your code and your tests and give you a summary of the tested and untested lines of code.


For Java, you can use JaCoCo and its Maven plugin. Simply add this to your POM:

 <plugin>  
  <groupId>org.jacoco</groupId>  
  <artifactId>jacoco-maven-plugin</artifactId>  
  <version>0.8.4</version>  
  <executions>  
   <execution>  
    <id>default-prepare-agent</id>  
    <goals>  
     <goal>prepare-agent</goal>  
    </goals>  
   </execution>  
   <execution>  
    <id>ut-report</id>  
    <phase>prepare-package</phase>  
    <goals>  
     <goal>report</goal>  
    </goals>  
   </execution>  
   <execution>  
    <id>it-report</id>  
    <phase>post-integration-test</phase>  
    <goals>  
     <goal>report</goal>  
    </goals>  
   </execution>  
  </executions>  
 </plugin>  


which will bind the execution to the unit test (prepare-package) AND integration test phase (post-integration-test), generating the report at the end of both phases in folder target/site/jacoco. If you skip one of those phases, the report will be incomplete and you might see much lower coverage than expected.

In case you want to exclude a package or a class from the check, you can add this section to the plugin configuration:

  <configuration>  
   <excludes>  
    <exclude>PATH/TO/PACKAGE/**</exclude>  
    <exclude>PATH/TO/PACKAGE/CLASS.class</exclude>  
   </excludes>  
  </configuration>  


You can also fail the build if the coverage is below a certain threshold you define, but I suggest activating this only when you are confident your setup is stable and doesn't annoy too many people.

No comments:

Post a Comment

With great power comes great responsibility