Search code examples
antcode-analysisemma

How do I generate Emma code coverage reports using Ant?


How do I setup an Ant task to generate Emma code coverage reports?


Solution

  • To answer questions about where the source and instrumented directories are (these can be switched to whatever your standard directory structure is):

    <property file="build.properties" />
    <property name="source" location="src/main/java" />
    <property name="test.source" location="src/test/java" />
    <property name="target.dir" location="target" />
    <property name="target" location="${target.dir}/classes" />
    <property name="test.target" location="${target.dir}/test-classes" />
    <property name="instr.target" location="${target.dir}/instr-classes" />
    

    Classpaths:

    <path id="compile.classpath">
      <fileset dir="lib/main">
        <include name="*.jar" />
      </fileset>
    </path>
    
    <path id="test.compile.classpath">
      <path refid="compile.classpath" />
      <pathelement location="lib/test/junit-4.6.jar" />
      <pathelement location="${target}" />
    </path>
    
    <path id="junit.classpath">
      <path refid="test.compile.classpath" />
      <pathelement location="${test.target}" />
    </path>
    

    First you need to setup where Ant can find the Emma libraries:

    <path id="emma.lib" >
        <pathelement location="${emma.dir}/emma.jar" />
        <pathelement location="${emma.dir}/emma_ant.jar" />
    </path>
    

    Then import the task:

    <taskdef resource="emma_ant.properties" classpathref="emma.lib" />
    

    Then instrument the code:

    <target name="coverage.instrumentation">
        <mkdir dir="${instr.target}"/>
        <mkdir dir="${coverage}"/>
        <emma>
            <instr instrpath="${target}" destdir="${instr.target}" metadatafile="${coverage}/metadata.emma" mode="copy">
                <filter excludes="*Test*"/>
            </instr>
        </emma>
        <!-- Update the that will run the instrumented code -->
        <path id="test.classpath">
            <pathelement location="${instr.target}"/>
            <path refid="junit.classpath"/>
            <pathelement location="${emma.dir}/emma.jar"/>
        </path>
    </target>
    

    Then run a target with the proper VM arguments like:

    <jvmarg value="-Demma.coverage.out.file=${coverage}/coverage.emma" />
    <jvmarg value="-Demma.coverage.out.merge=true" />
    

    Finally generate your report:

    <target name="coverage.report" depends="coverage.instrumentation">
        <emma>
            <report sourcepath="${source}" depth="method">
                <fileset dir="${coverage}" >
                    <include name="*.emma" />
                </fileset>
                <html outfile="${coverage}/coverage.html" />
            </report>
        </emma>
    </target>