Java Reference
In-Depth Information
5.1.2
Introduction to Cobertura
Cobertura is a code coverage tool that integrates with
JU
nit. Cobertura provides the
following features:
Is free and open source
■
Integrates with Ant and Maven; also callable from a command line
■
Generates reports in
HTML
or
XML
■
Sorts the
HTML
results by various criteria
■
Computes the percentage of code lines and code branches covered for each
class, package, and the entire project
■
In order to measure test coverage, Cobertura creates
instrumented
copies of class files
you specify. This process, called byte-code instrumentation, adds byte codes to
existing
compiled code to enable logging of what executed byte codes. Instead of, or in addi-
tion to, running the normally compiled unit tests, you run the compiled and instru-
mented tests. Let's now get started with Cobertura.
Download Cobertura from
http://cobertura.sourceforge.net/
and extract the
archive. Define a
COBERTURA_HOME
environment variable and add it to the execution
PATH
environment variable. The
COBERTURA_HOME
folder contains several com-
mand-line scripts we use in this section. Although our examples drive Cobertura
from the command line, note that the program also provides Ant tasks.
We start by compiling our test cases with the following command:
>javac -cp junit-4.6.jar -d uninstrumented src\*.java
We instrument our classes with the following command:
>cobertura-instrument --destination instrumented
uninstrumented\Calculator.class
The
--destination
parameter specifies where to place the instrumented classes.
The application argument specifies the path to the precompiled classes, in our case,
uninstrumented\Calculator.class
.
Next, we run the unit tests against the instrumented code. Cobertura integrates
with
JU
nit and Ant, but it's also tool agnostic and can work with any other testing
framework. To run your tests, you need to place two resources on your
CLASSPATH
:
Cobertura.jar
■
The directory containing the instrumented classes before the directory contain-
ing the uninstrumented classes. You can run the tests from the command line
or Ant, with identical results. For example, the following runs tests from the
command line:
■
>java -cp junit-4.6.jar;$COBERTURA_HOME\
➥
cobertura.jar;instrumented;uninstrumented;
-Dnet.sourceforge.cobertura.datafile=
cobertura.ser org.junit.runner.JUnitCore TestCalculator