Thursday, February 14, 2013

Ant task for generating Cobertura report

The post describes how to use coburtura in the ant task. First of all you must tell ant about the Cobertura Ant tasks using a taskdef statement. The best practice is to place this before any target statements.
 
 
  
  
   
   
   
   
   
  
 

 
 
We must specify for Cobertura which class files to instrument by passing in ant filesets. You need to specify the directory location in "todir" to place the instrumented classes. You can exclude classes by using "excludeclasses" tag or using "ignore". Specify the name of the coverage data file to use in the "datafile" attribute. The default file is "cobertura.ser".

Cobertura-Instrument Task:
 
 
  
   
   
  
 

Running tests(Here i used TestNG to run tests):
The following components are the most important to get cobertura code coverage to work with testng.
This is a static variable that contains the location of the datafile. If the datafile moves, this lets the JVM know that the datafile has moved and is not in the current(or present) working directory.


Adding the instrumented classes before the actual classes guarantees that cobertura source code gets used first. This is required because we want to use the cobertura instrumented code instead of the regular compiled code, however we keep both versions just in case there's an issue with instrumentation.

Creating a reference id that contains just the cobertura.jar is important to guarantee that there is no NoClassDefFound exception with cobertura. When executing test units, the only dependency cobertura requires is the cobertura.jar file. All the other files are necessary for instrumentation, reporting and merging of tasks.
  
 
  
  
  
  
  
  
  
 

Cobertura-Report Task:
For generating cobertura report we need to use "cobertura-report" tag with the source file director specified in "srcdir" and destination report directory in "destdir" attribute.
 
 
 
  
   
   
   
   
   
   
   
  

  
  
 

The report generated by the cobertura looks like as the below snapshot:


Ant task to print all the test environment information

Below are the list of ant properties that gives the information about test environment. For example, if you want to know which java version is used, we can use "ant.java.version" property in the "echo" tag to print in the ant console. Similarly, for 

ant version - ant.version 
current project name - ant.project.name 
current user name - user.name 
current user directory - user.dir 

Below is the ant code to do this:
 
 
 
  
  
  
  
  
 
You will get the following message in your console:
Buildfile: /Users/aksahu/MySpace/Web_Workspace/AutoTest/build.xml
info:
     [echo] Java Version : 1.6
     [echo] Ant Version : Apache Ant version 1.7.1 compiled on June 27 2008
     [echo] Project Name : autoTest
     [echo] User Name : aksahu
     [echo] Project Location : /Users/aksahu/MySpace/Web_Workspace/AutoTest
BUILD SUCCESSFUL
Total time: 753 milliseconds