Cobertura is another popular Java tool that calculates the percentage of code accessed by tests. It is based on jcoverage. There are many ways to use Cobertura, including standalone, through Ant script, and Maven. Let us use the Maven Cobertura plugin.
Use the following steps to analyze the code coverage with the Maven Cobertura plugin:
project-with-tests
).mvn cobertura:cobertura
[INFO] <<< cobertura-maven-plugin:2.6:cobertura (default-cli) < [cobertura]test@ project-with-tests <<< [INFO] [INFO] --- cobertura-maven-plugin:2.6:cobertura (default-cli) @ project-with-tests --- [INFO] Cobertura 2.0.3 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file Report time: 165ms [ERROR] Nov 15, 2014 5:06:25 PM net.sourceforge.cobertura.coveragedata.CoverageDataFileHandler loadCoverageData INFO: Cobertura: Loaded information on 1 classes.
JaCoCo instruments the code online when the tests are running and hence,it needs to have the agent running. On the other hand, Cobertura instruments the bytecode during compilation offline. The cobertura
goal of the Cobertura Maven plugin instruments the project, runs the tests, and generates the report.
There are separate goals to instrument
and check
results, if required.
What if we want to fail the build if the code coverage is below a threshold level? We can set up Cobertura to do this:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.6</version> <configuration> <check> <branchRate>85</branchRate> <lineRate>85</lineRate> <haltOnFailure>true</haltOnFailure> </check> </configuration> <executions> <execution> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin>
mvn cobertura:check
The build has failed because, in the pom file, we specified that the build should be halted if the coverage is less than 85%.
3.144.39.133