Code coverage
| Excerpt |
|---|
is a useful measure of the effectiveness of unit tests and can be derived for Groovy tests |
Consider the following Groovy code:
| Code Block |
|---|
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:
| Code Block |
|---|
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:
| Code Block | ||
|---|---|---|
| ||
<?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="${dir.build}" debug="true">
<classpath refid="project.classpath"/>
</javac>
<groovyc srcdir="${dir.src}" destdir="${dir.build}" stacktrace="true">
<classpath refid="project.classpath"/>
</groovyc>
</target>
<!-- instrument already compiled class files -->
<target name="instrument" depends="compile" >
<cobertura-instrument todir="target/instrumented-classes">
<fileset dir="${dir.build}">
<include name="**/*.class"/>
</fileset>
</cobertura-instrument>
</target>
<!-- run all junit tests using the instrumented classes -->
<target name="cover-test" depends="instrument">
<mkdir dir="${dir.report}/cobertura" />
<junit printsummary="yes" haltonerror="no" haltonfailure="no" fork="yes">
<formatter type="plain" usefile="false"/>
<batchtest>
<fileset dir="target/instrumented-classes" includes="**/*Test.class" />
</batchtest>
<classpath refid="cover-test.classpath"/>
</junit>
</target>
<!-- create the html reports -->
<target name="coverage-report" depends="cover-test">
<cobertura-report srcdir="${dir.src}" destdir="${dir.report}/cobertura"/>
</target>
</project>
|
For more details, see GINA or the Cobertura web site or Code Coverage with Cobertura.