Ant Tasks

JaCoCo comes with Ant tasks to launch Java programs with execution recording and for creating coverage reports from the recorded data. Execution data can be collected and managed with the tasks coverage, agent, dump and merge. Reports in different formats are created with the report task. For offline instrumentation the task instrument can be used to prepare class files.

If you want to have line number information included in the coverage reports or you want source code highlighting the class files of the test target must be compiled with debug information.

Example

The JaCoCo distribution contains a simple example how code coverage can be added to a Ant based build. The build script compiles Java sources, runs an simple Java program and creates a coverage report. The complete example is located in the ./doc/examples/build folder of the distribution.

Prerequisites

The JaCoCo Ant tasks require

All tasks are defined in jacocoant.jar (which is part of the distribution) and can be included in your Ant scripts with the usual taskdef declaration:

<project name="Example" xmlns:jacoco="antlib:org.jacoco.ant">

    <taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
        <classpath path="path_to_jacoco/lib/jacocoant.jar"/>
    </taskdef>
    
    ...
    
</project>

Alternatively you might also place the jacocoant.jar in your Ant ANT_HOME/lib folder. If you use the name space URI antlib:org.jacoco.ant for JaCoCo tasks Ant will find them automatically without the taskdef declaration above.

Declaring a XML namespace for JaCoCo tasks is optional but always recommended if you mix tasks from different libraries. All subsequent examples use the jacoco prefix declared above. If you don't declare a separate namespace the jacoco prefix must be removed from the following examples.

Task coverage

The standard Ant tasks to launch Java programs are java, junit and testng. To add code coverage recording to these tasks they can simply be wrapped with the coverage task as shown in the following examples:

<jacoco:coverage>
    <java classname="org.jacoco.examples.HelloJaCoCo" fork="true">
        <classpath>
            <pathelement location="./bin"/>
        </classpath>
    </java>
</jacoco:coverage>


<jacoco:coverage>
    <junit fork="true" forkmode="once">
        <test name="org.jacoco.examples.HelloJaCoCoTest"/>
        <classpath>
            <pathelement location="./bin"/>
        </classpath>
    </junit>
</jacoco:coverage>

Resulting coverage information is collected during execution and written to a file when the process terminates. Note the fork attribute above in the wrapped java task.

The nested task always has to declare fork="true", otherwise the coverage task can't record coverage information and will fail. In addition the junit task should declare forkmode="once" to avoid starting a new JVM for every single test case and decreasing execution performance dramatically (unless this is required by the nature of the test cases). Note that forkmode="perTest" or forkmode="perBatch" should not be combined with append="false" as the execution data file is overwritten with the execution of every test.

The coverage task must wrap exactly one task. While it typically works without any configuration, the behavior can be adjusted with some optional attributes:

Attribute Description Default
enabled If set to true coverage data will be collected for the contained task. true
destfile Path to the output file for execution data. jacoco.exec
append If set to true and the execution data file already exists, coverage data is appended to the existing file. If set to false, an existing execution data file will be replaced. true
includes A list of class names that should be included in execution analysis. The list entries are separated by a colon (:) and may use wildcard characters (* and ?). Except for performance optimization or technical corner cases this option is normally not required. * (all classes)
excludes A list of class names that should be excluded from execution analysis. The list entries are separated by a colon (:) and may use wildcard characters (* and ?). Except for performance optimization or technical corner cases this option is normally not required. empty (no excluded classes)
exclclassloader A list of class loader names, that should be excluded from execution analysis. The list entries are separated by a colon (:) and may use wildcard characters (* and ?). This option might be required in case of special frameworks that conflict with JaCoCo code instrumentation, in particular class loaders that do not have access to the Java runtime classes. sun.reflect.DelegatingClassLoader
inclbootstrapclasses Specifies whether also classes from the bootstrap classloader should be instrumented. Use this feature with caution, it needs heavy includes/excludes tuning. false
inclnolocationclasses Specifies whether also classes without a source location should be instrumented. Normally such classes are generated at runtime e.g. by mocking frameworks and are therefore excluded by default. false
sessionid A session identifier that is written with the execution data. Without this parameter a random identifier is created by the agent. auto-generated
dumponexit If set to true coverage data will be written on VM shutdown. true
output Output method to use for writing coverage data. Valid options are:
  • file: At VM termination execution data is written to the file specified in the destfile attribute.
  • tcpserver: The agent listens for incoming connections on the TCP port specified by the address and port attribute. Execution data is written to this TCP connection.
  • tcpclient: At startup the agent connects to the TCP port specified by the address and port attribute. Execution data is written to this TCP connection.
  • none: Do not produce any output.
file
address IP address or hostname to bind to when the output method is tcpserver or connect to when the output method is tcpclient. In tcpserver mode the value "*" causes the agent to accept connections on any local address. loopback interface
port Port to bind to when the output method is tcpserver or connect to when the output method is tcpclient. In tcpserver mode the port must be available, which means that if multiple JaCoCo agents should run on the same machine, different ports have to be specified. 6300
classdumpdir Location relative to the working directory where all class files seen by the agent are dumped to. This can be useful for debugging purposes or in case of dynamically created classes for example when scripting engines are used. no dumps
jmx If set to true the agent exposes functionality via JMX under the name org.jacoco:type=Runtime. false

Task agent

If the coverage task is not suitable for your launch target, you might alternatively use the agent task to create the Java agent parameter. The following example defines a Ant property with the name agentvmparam that can be directly used as a Java VM parameter:

<jacoco:agent property="agentvmparam"/>

This task has the same attributes as the coverage task plus an additional property to specify the target property name:

Attribute Description Default
enabled When this variable is set to false the value of property will be set to an empty string, effectively disabling coverage instrumentation for any tasks that used the value. true
property Name of the Ant property to set. none (required)
All attributes of the coverage task.

Task dump

This task allows to remotely collect execution data from another JVM without stopping it. For example:

<jacoco:dump address="server.example.com" reset="true" destfile="remote.exec"/>

Remote dumps are usefull for long running Java processes like application servers.

The target JVM needs to have a JaCoCo agent configured with output mode tcpserver. See coverage and agent tasks above.

The dump task has the following attributes:

Attribute Description Default
address Target IP address or DNS name. localhost
port Target TCP port. 6300
retryCount Number of retries which the goal will attempt to establish a connection. This can be used to wait until the target JVM is successfully launched. 10
dump Flag whether execution data should be dumped. true
reset Flag whether execution data should be reset in the target agent after the dump. false
destfile File location to write the collected execution data to. none (required if dump=true)
append If set to true and the execution data file already exists, coverage data is appended to the existing file. If set to false, an existing execution data file will be replaced. true

Task merge

This task can be used to merge the execution data from multiple test runs into a single data store.

<jacoco:merge destfile="merged.exec">
    <fileset dir="executionData" includes="*.exec"/>
</jacoco:merge>

The task definition can contain any number of resource collection types and has the following mandatory attribute:

Attribute Description Default
destfile File location to write the merged execution data to. none (required)

Task report

Finally different reports can be created with the report task. A report task declaration consists of different sections, two specify the input data, additional ones specify the output formats:

<jacoco:report>
			
    <executiondata>
        <file file="jacoco.exec"/>
    </executiondata>
			
    <structure name="Example Project">
        <classfiles>
            <fileset dir="classes"/>
        </classfiles>
        <sourcefiles encoding="UTF-8">
            <fileset dir="src"/>
        </sourcefiles>
    </structure>
			
    <html destdir="report"/>
			
</jacoco:report>

As you can see from the example above the report task is based on several nested elements:

Element executiondata

Within this element Ant resources and resource collections can be specified, that represent JaCoCo execution data files. If more than one execution data file is specified, execution data is combined. A particular piece of code is considered executed when it is marked as such in any of the input files.

Element structure

This element defines the report structure. It might contain the following nested elements:

The sourcefiles element has these optional attributes:

Attribute Description Default
encoding Character encoding of the source files. Platform default encoding
tabwidth Number of whitespace characters that represent a tab character. 4 characters

Important: Source file resources must always be specified relative to the respective source folder. If directory resources are given, they must directly point to source folders. Otherwise source lookup will not succeed.

Note that the classfiles and sourcefiles elements accept any Ant resource collection. Therefore also filtering the class file set is possible and allows to narrow the scope of the report, for example:

<classfiles>
    <fileset dir="classes">
        <include name="org/jacoco/examples/important/**/*.class"/>
    </fileset>
</classfiles>

Performance Warning: Although it is technically possible and sometimes convenient to use Ant's zipfileset to specify class or source files, this resource type has poor performance characteristics and comes with an huge memory overhead especially for large scale projects.

The structure can be refined with a hierarchy of group elements. This way the coverage report can reflect different modules of a software project. For each group element the corresponding class and source files can be specified separately. For example:

<structure name="Example Project">
    <group name="Server">
        <classfiles>
            <fileset dir="${workspace.dir}/org.jacoco.example.server/classes"/>
        </classfiles>
        <sourcefiles>
            <fileset dir="${workspace.dir}/org.jacoco.example.server/src"/>
        </sourcefiles>
    </group>
    <group name="Client">
        <classfiles>
            <fileset dir="${workspace.dir}/org.jacoco.example.client/classes"/>
        </classfiles>
        <sourcefiles>
            <fileset dir="${workspace.dir}/org.jacoco.example.client/src"/>
        </sourcefiles>
    </group>
    
    ...
    
</structure>

Both structure and group elements have the following mandatory attribute:

Attribute Description Default
name Name of the structure or group. none (required)

Element html

Create a multi-page report in HTML format. The report can either be written as multiple files into a directory or compressed into a single ZIP file.

Attribute Description Default
destdir Directory to create the report in. Either this property or destfile has to be supplied. none (required)
destfile Zip file to create the report in. Either this property or destdir has to be supplied. none (required)
footer Footer text for each report page. no footer
encoding Character encoding of generated HTML pages. UTF-8
locale Locale specified as ISO code (en, fr, jp, ...) used for number formatting. Locale country and variant can be separated with an underscore (de_CH). platform locale

Element xml

Create a single-file report in XML format.

Attribute Description Default
destfile Location to write the report file to. none (required)
encoding Encoding of the generated XML document. UTF-8

Element csv

Create single-file report in CSV format.

Attribute Description Default
destfile Location to write the report file to. none (required)
encoding Encoding of the generated CSV document. UTF-8

Element check

This report type does not actually create a report. It checks coverage counters and reports violations of configured rules. Every rule is applied to elements of a given type (class, package, bundle, etc.) and has a list of limits which are checked for every element. The following example checks that for every package the line coverage is at least 80% and no class is missed:

<check>
    <rule element="PACKAGE">
        <limit counter="LINE" value="COVEREDRATIO" minimum="0.80"/>
        <limit counter="CLASS" value="MISSEDCOUNT" maximum="0"/>
    </rule>
</check>

The check element has the following attributes:

Attribute Description Default
rules List of rules to check. none
failonviolation Specifies whether build should fail in case of rule violations. true
violationsproperty The name of an Ant property which is filled with the violation messages. none

Within the check element any number of rule elements can be nested:

Attribute Description Default
element The elements this rule applies to. Possible values are BUNDLE, PACKAGE, CLASS, SOURCEFILE and METHOD. BUNDLE
includes A list of element names that should be checked. The list entries are separated by a colon (:) and may use wildcard characters (* and ?). *
excludes A list of element names that should not be checked. The list entries are separated by a colon (:) and may use wildcard characters (* and ?). empty (no excludes)
limits List of limits to check. none

Within the rule element any number of limit elements can be nested:

Attribute Description Default
counter The counter which should be checked. Possible options are INSTRUCTION, LINE, BRANCH, COMPLEXITY, METHOD and CLASS. INSTRUCTION
value The counter value that should be checked. Possible options are TOTALCOUNT, MISSEDCOUNT, COVEREDCOUNT, MISSEDRATIO and COVEREDRATIO. COVEREDRATIO
minimum Expected minimum value. If the minimum refers to a ratio the range is from 0.0 to 1.0 where the number of decimal places will also determine the precision in error messages. none
maximum Expected maximum value. none

Task instrument

Warning: The preferred way for code coverage analysis with JaCoCo is on-the-fly instrumentation. Offline instrumentation has several drawbacks and should only be used if a specific scenario explicitly requires this mode. Please consult documentation about offline instrumentation before using this mode.

This task is used for offline instrumentation of class files. The task takes a set of files and writes instrumented versions to a specified location. The task takes any file type as input. Java class files are instrumented. Archives (jar, war, ear etc. or Pack200) are searched recursively for class files which then get instrumented. All other files are copied without modification.

<jacoco:instrument destdir="target/classes-instr">
    <fileset dir="target/classes" includes="**/*.class"/>
</jacoco:instrument>

The task definition can contain any number of resource collection types and has the following mandatory attribute:

Attribute Description Default
destdir Directory location to write the instrumented files to. none (required)
removesignatures If set to true all signature related information is stripped from JARs. This is typically necessary as instrumentation breaks the signatures of the original class files. true