Examining code coverage in Maven projects
This document describes how to display test coverage for your Maven project in NetBeans, via the Cobertura Maven plugin.
Installation and setup
This document assumes NetBeans 7.0 or later.
The test coverage functionality is provided by the Maven Test Coverage plugin, which is available for 7.0 on the dev update center and also the plugin portal. Start up the IDE, go to
Tools | Plugins and search for "coverage". If NetBeans finds the plugin, install it by pressing the
Install button and following the wizard. You can also download it from the Plugin Portal.
NetBeans 7.1 and later include the plugin by default, so you do not need to download anything.
Configuring your project
We now need a suitable Maven project. If you already have your own Maven project which contains some tests, just open it using
File | Open Project.
If not, just create one using
File | New Project, selecting one of the templates in the Maven category and following the wizard. You will also need some code and tests for this code: the easiest way is to do this is right-clicking an existing Java class, and choosing
Tools | Create JUnit Tests.
The most important part of the setup is to configure the Cobertura Maven plugin in your project. The simplest way is to add the following snippet of code to the
pom.xml file of your project:
<reporting> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <version>2.4</version> </plugin> </plugins> </reporting>
For a more comprehensive documentation, see the cobertura-maven-plugin website.
Examining Code Coverage
Now you are ready to run the code coverage report for your project. In the pop-up menu of the project node in the
Projects tab, you will now see a new
Code Coverage submenu. In this submenu, choose
The Code Coverage Report window appears. When you press the
Run All Tests button in this window, you will see the code coverage summary for the project.
Now you can also double-click individual items to get code coverage details for individual classes. In this detailed view, lines covered by tests are displayed with green background, whereas lines that are not covered have pink background.
In NetBeans 7.2, JaCoCo is supported as a code coverage engine, since Cobertura does not work with JDK 7 language constructs. Usage is essentially the same as for Cobertura; you just need to configure JaCoCo as per its recommendations:
<build> <plugins> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.5.7.201204190339</version> <executions> <execution> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>report</id> <phase>prepare-package</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin> </plugins> </build>