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.

<plugin>
	<groupid>org.codehaus.mojo</groupid>
	<artifactid>cobertura-maven-plugin</artifactid>
	<version>2.5.1</version>
	<configuration>
		<instrumentation>
			<includes></includes>
			<excludes>
				<exclude>net/bryansaunders/**/*Test.class</exclude>
			</excludes>
		</instrumentation>
		<check>
			<linerate>75</linerate>
			<totallinerate>85</totallinerate>
			<haltonfailure>true</haltonfailure>
		</check>
	</configuration>
	<executions>
		<execution>
			<id>clean</id>
			<phase>clean</phase>
			<goals>
				<goal>clean</goal>
			</goals>
		</execution>
		<execution>
			<id>package</id>
			<phase>package</phase>
			<goals>
				<goal>check</goal>
			</goals>
		</execution>
	</executions>
</plugin>
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


Published

03 July 2012

Tags