Wednesday, April 2, 2014

Code coverage report using Cobertura with gradle

According to wikipedia Code coverage is

code coverage is a measure used to describe the degree to which the source code of a program is tested by a particular test suite. A program with high code coverage has been more thoroughly tested and has a lower chance of containing software bugs than a program with low code coverage. Many different metrics can be used to calculate code coverage; some of the most basic are the percent of program subroutines and the percent of program statements called during execution of the test suite.

There are several tools which help in getting code coverage. Out of then Cobertura is one. From the official site of 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.
Gradle is a popular build tool. Many a times one would like to get code coevage report during build time about Unit Tests' code coverage. This can be easily achieved using following piece of code in build.gradle

1. Using Cobertura with gradle

paste this in build.gradle

buildscript {
    repositories {
    dependencies {
        classpath "net.saliman:gradle-cobertura-plugin:1.1.0"

apply plugin: 'cobertura'

This will give you 2 new tasks called instrument and cobertura

instrument task will instrument the classes of the project. And cobertura task will build > instrument > test > createReport

test Task will build and run the classes in src/test folder. These are unit tests of the project

Code coverage report for Unit Tests is as follows 

2. QA Tests

QA can also use gradle in their project and run tests or can follow following process

Download cobertura from 

To Compile Test Code

javac -cp ~/Desktop/cobertura-2.0.3/cobertura-2.0.3.jar:projectname/build/classes/main/

To Run Test Code on instrumented classes

java -cp ~/Desktop/cobertura-2.0.3/cobertura-2.0.3.jar:projectname/build/classes/main/:. -Dnet.sourceforge.cobertura.datafile=cobertura.ser Test

To Create Cobertura Report Outside gradle

~/Desktop/cobertura-2.0.3/ --format html --datafile cobertura.ser --destination coverage projectname/src/

3. Merge reports

Once both the reports are ready we can use following command to merge

./ --datafile cobertura.ser cobertura1.ser 

now create report using command

cobertura.ser --destination coverage projectname/src/

4. Check for a condition on code coverage

~/Desktop/cobertura-2.0.3/ --datafile projectname/build/cobertura/cobertura.ser  --line 30


No comments:

Post a Comment