Thursday, 20 September 2012

1. What is 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. It is based on jcoverage.

2. Cobertura Advantages and Features

Cobertura is a open source Java tool
Helps to get the code coverage details
It shows the percentage of line and branch test cases have been covered
Cobertura report shows which line of code is lacking of test cases
It can be executed with Maven, Ant or command line

3. What is Line and Branch Coverage?

Line coverage –> During the test cases run how much percentage of lines have been covered
Branch coverage-> During the test coverage how much percentage of branches have been covered.

4. Cobertura Example

Below example will show how cobertura calculating line and branch coverage.

1. Create a Maven Project and add below plugin/configuration in pom.xml

Note: Please check the include tag to add package details

    <!-- cobertura -->

2. Create a Sample Java Program and its Junit Test

package com.pretechsol;
public class PretechCobertura {
public String validation(String name, String gender) {
if (name.equals("")) {
System.out.println("name should not be null");
if (gender.equals("")) {
System.out.println("gender should not be null");
String result = null;
if (name.equals("pretech")) {
if (gender.equals("male")) {
result = "success";
} else {
result = "fail";
} else {
result = "try again";
return result;

package com.pretechsol;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PretechCoberturaTest {
PretechCobertura pretechCobertura;
public void setUp() throws Exception {
pretechCobertura = new PretechCobertura();
public void tearDown() throws Exception {
pretechCobertura = null;
* @Test public void testPretechCoberturaValidation() {
* String result = pretechCobertura.validation("pretech1", "male");
* assertEquals("try again", result); }
* @Test public void testPretechCoberturaValidation1() {
* String result = pretechCobertura.validation("", "male");
* //assertEquals("try again", result); }

3. Run Cobertura

1. In command prompt use this command = mvn cobertura:cobertura
2. In eclipse run as maven build and add goal as cobertura:cobertura

4. Check the report file generated in target directory.

Note: Please uncomment the test cases from PretechCoberturaTest file and run cobertura again, you can see branch coverage is above 75%