First, you need to add a task definition to the build.xml file. This top-level
taskdef
element specifies that the cobertura.jar file is in the current working directory:<taskdef classpath="cobertura.jar" resource="tasks.properties" /> For eclipse IDE, you need to add the cobertura.jar, junit.jar in the global path of Ant through Eclipse--} preferences--} Ant --} Global entry.
Next, you need a
cobertura-instrument
task that adds the logging code to the already compiled class files. Thetodir
attribute instructs where to put the instrumented classes. Thefileset
child element specifies which .class files to instrument:<target name="instrument"> <cobertura-instrument todir="target/instrumented-classes"> <fileset dir="target/classes"> <include name="**/*.class"/> </fileset> </cobertura-instrument> </target>
You run the tests with the same type of Ant task that normally runs the test suite. The only differences are that the instrumented classes need to appear in the classpath before the original classes, and you need to add the Cobertura JAR file to the classpath:
<target name="cover-test" depends="instrument"> <mkdir dir="${testreportdir}" /> <junit dir="./" failureproperty="test.failure" printSummary="yes" fork="true" haltonerror="true"> <formatter type="plain" usefile="false"/> <!-- Normally you can create this task by copying your existing JUnit target, changing its name, and adding these next two lines. You may need to change the locations to point to wherever you've put the cobertura.jar file and the instrumented classes. --> <classpath location="cobertura.jar"/> <classpath location="target/instrumented-classes"/> <classpath> <fileset dir="${libdir}"> <include name="*.jar" /> </fileset> <pathelement path="${testclassesdir}" /> <pathelement path="${classesdir}" /> </classpath> <batchtest todir="${testreportdir}"> <fileset dir="src/java/test"> <include name="**/*Test.java" /> <include name="org/jaxen/javabean/*Test.java" /> </fileset> </batchtest> </junit> </target>>
The Jaxen project uses JUnit as its test framework, but Cobertura is framework agnostic. It works equally well with TestNG, Artima SuiteRunner, HTTPUnit, or the home-brewed system you cooked up in your basement.
Finally, the
cobertura-report
task generates the HTML files you saw at the beginning of the article:<target name="coverage-report" depends="cover-test"> <cobertura-report srcdir="src/java/main" destdir="cobertura"/> </target>
The
srcdir
attribute specifies where the original .java source code files reside. Thedestdir
attribute names the directory where Cobertura should place the output HTML.Once you've added similar tasks to your own Ant build file, you generate a coverage report by typing:
% ant instrument % ant cover-test % ant coverage-report
Thursday, March 20, 2008
Cobertura- junit coverage tool
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment