Thursday, 20 September 2012

Cobertura Line and Branch coverage Example


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.vinod;

public class SimpleValidate {
    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;

3. Junit test class

package com.vinod.test;

import org.junit.Before;

import com.vinod.SimpleValidate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.Test;

public class SimpleValidateTest {
    SimpleValidate simpleValidate = null;

    public void setUp() throws Exception {
        simpleValidate = new SimpleValidate();
    public void tearDown() throws Exception {
        simpleValidate = null;
    public void testSimpleValidateaValidation() {

        String result = simpleValidate.validation("Vinod", "male");
        assertEquals("try again", result);
    public void testSimpleValidateValidation1() {
        String result = simpleValidate.validation("", "male");
        assertEquals("try again", result);


Run it (Use below command)

mvn clean install cobertura:cobertura

After the build we can see the cobertura report has been generated with test coverage statistics..

Download example