Java Unit And Ant

There is a task named junit in ApacheAnt that can be used run JavaUnit tests. The full documentation can be found at http://ant.apache.org/manual/OptionalTasks/junit.html

There are two ways to define which testcases to run, either specify them explicitly or let Ant pick up all testcase classes from the source directory automatically. From Ant's own buildfile for example:

    <junit printsummary="no" haltonfailure="yes" fork="${junit.fork}">
      <classpath>
        <pathelement location="${lib.dir}/${name}.jar" />
        <pathelement location="${build.tests}" />
        <path refid="classpath" />
        <pathelement path="${java.class.path}" />
      </classpath>

<formatter type="plain" usefile="false" />

<batchtest> <fileset dir="${src.tests.dir}"> <include name="**/*Test*" /> <!-- abstract class, not a testcase --> <exclude name="org/apache/tools/ant/taskdefs/TaskdefsTest.java" />

<!-- these depend on order --> <exclude name="org/apache/tools/ant/taskdefs/GUnzipTest.java" /> <exclude name="org/apache/tools/ant/taskdefs/GzipTest.java" /> </fileset> </batchtest>

<test name="org.apache.tools.ant.taskdefs.GzipTest" /> <test name="org.apache.tools.ant.taskdefs.GUnzipTest" /> </junit>

This will use the specified CLASSPATH and a plain text result formatter (see below) to run all testcases found somewhere below the directory ${src.tests.dir} (src.tests.dir is a property that has been defined somewhere else). All files that contain the string Test in their name shall be considered test cases except the ones listed. Additionally the test cases for the gzip and gunzip tasks depend on each other so they need to be specified separately.

The haltonfailure attribute of the tasks ensures that the build process will fail if any testcase fails.

A formatter is used to collect the results of a test run (how many tests have been run, which have been successful, which failed ...). Formatters need to implement a formatter interface which is Ant's extension of junit.framework.TestListener?. Formatters that write results as plain text or XML have been provided by Ant.


This article http://today.java.net/pub/a/today/2003/09/12/individual-test-cases.html has some nice examples of using Ant to run individual tests or even test cases.


CategoryAnt


EditText of this page (last edited January 20, 2009) or FindPage with title or text search