The behavior and configuration of all of these tools is similar. In this section, we will look at Cobertura.
6.6.1. Measuring Code Coverage with Cobertura
Cobertura^1 is an open source code coverage tool for Java and Groovy that is easy to use and integrates
well with both Maven and Jenkins.
Like almost all of the Jenkins code quality metrics plugins,^2 the Cobertura plugin for Jenkins will not
run any test coverage metrics for you. It is left up to you to generate the raw code coverage data as part
of your automated build process. Jenkins, on the other hand, does an excellent job of reporting on the
code coverage metrics, including keeping track of code coverage over time, and providing aggregate
coverage across multiple application modules.
Code coverage can be a complicated business, and it helps to understand the basic process that Cobertura
follows, especially when you need to set it up in more low-level build scripting tools like Ant. Code
coverage analysis works in three steps. First, it modifies (or “instruments”) your application classes, to
make them keep a tally of the number of times each line of code has been executed.^3 They store all this
data in a special data file (Cobertura uses a file called cobertura.ser).
When the application code has been instrumented, you run your tests against this instrumented code.
At the end of the tests, Cobertura will have generated a data file containing the number of times each
line of code was executed during the tests.
Once this data file has been generated, Cobertura can use this data to generate a report in a more usable
format, such as XML or HTML.
6.6.1.1. Integrating Cobertura with Maven
Producing code coverage metrics with Cobertura in Maven is relatively straightforward. If all you are
interested in is producing code coverage data, you just need to add the cobertura-maven-plugin to
the build section of your pom.xml file:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<formats>
<format>html</format>
<format>xml</format>
(^1) http://cobertura.sourceforge.net
(^2) With the notable exception of Sonar, which we will look at later on in the book.
(^3) This is actually a slight over-simplification; in fact, Cobertura stores other data as well, such as how many times each possible
outcome of a boolean test was executed. However this does not alter the general approach.