Code Coverage with Cobertura in Maven 3
Code Coverage
Code coverage is a metric used to determine how much of your code is executed by your automated test suite. It is typically only applied to unit & integration tests, but it can be applied to all automated tests. There are several different code coverage tools on the market. The two most well known for Java are Cobertura and EclEmma/JaCoCo.
Cobertura
Cobertura is a free Java tool that calculates the percentage of code accessed by tests. It can be used to identify which parts of your Java program are lacking test coverage. Cobertura is generally a stand-alone application, however it can also be executed from Ant tasks, IDE Plugins, or Maven Plugins. When Cobertura is executed, it will generate a series of reports that show each line of code, and how many times it was executed. It will also show things like line coverage, branch coverage, & package coverage.
Configuring Maven 3
The following code will configure Maven 3 to execute the Cobertura plugin during the package phase of the build lifecycle. If the code has line rate of less that 85%, or any single file has a line rate of less than 75%, then the build will fail.
Along with lineRate and totalLineRate properties, there are four other that you can set as well, they are:
- branchRate - Specify the minimum acceptable branch coverage rate needed by each class
- totalBranchRate - Specify the minimum acceptable average branch coverage rate needed by the project as a whole
- packageBranchRate - Specify the minimum acceptable average branch coverage rate needed by each package
- packageLineRate - Specify the minimum acceptable average line coverage rate needed by each package