Code coverage

is a useful measure of the effectiveness of unit tests and can be derived for Groovy tests


Consider the following Groovy code:

class BiggestPairCalc
    int sumBiggestPair(int a, int b, int c) {
        def op1 = a
        def op2 = b
        if (c > a) {
            op1 = c
        } else if (c > b) {
            op2 = c
        return op1 + op2

And the following test:

class BiggestPairCalcTest extends GroovyTestCase
    void testSumBiggestPair() {
        def calc = new BiggestPairCalc()
        assertEquals(9, calc.sumBiggestPair(5, 4, 1))

If you use Cobertura to perform your coverage, the resulting report might look like:

Your Ant build file to make all this happen might look like:

<?xml version="1.0"?>
<project name="sample" default="coverage-report" basedir=".">
  <!-- set up properties, paths, taskdefs, prepare targets -->
  [details deleted]

  <!-- compile java (if you have any) and groovy source -->
  <target name="compile" depends="prepare">
    <javac srcdir="${dir.src}" destdir="${}" debug="true">
      <classpath refid="project.classpath"/>
    <groovyc srcdir="${dir.src}" destdir="${}" stacktrace="true">
      <classpath refid="project.classpath"/>

  <!-- instrument already compiled class files -->
  <target name="instrument" depends="compile" >
    <cobertura-instrument todir="target/instrumented-classes">
      <fileset dir="${}">
          <include name="**/*.class"/>

  <!-- run all junit tests using the instrumented classes -->
  <target name="cover-test" depends="instrument">
    <mkdir dir="${}/cobertura" />
    <junit printsummary="yes" haltonerror="no" haltonfailure="no" fork="yes">
      <formatter type="plain" usefile="false"/>
        <fileset dir="target/instrumented-classes" includes="**/*Test.class" />
      <classpath refid="cover-test.classpath"/>

  <!-- create the html reports -->
  <target name="coverage-report" depends="cover-test">
    <cobertura-report srcdir="${dir.src}" destdir="${}/cobertura"/>

For more details, see GINA or the Cobertura web site or Code Coverage with Cobertura.