Using JUnit with Ant

The Ant project build tool includes a few built-in tasks that can be used to integrate JUnit tests into your build scripts. The JUnit support tasks discussed here are included among the optional tasks in the Ant distribution since, in addition to the core Ant libraries, they also require the JUnit libraries in order to run. That means that before using these tasks, you need to ensure that you have the optional Ant tasks as well as the JUnit library in the appropriate CLASSPATH. See Chapter 17 for more details on general Ant usage.

It’s possible, of course, to use the core Java support tasks to drive JUnit in your Ant buildfiles. For example, we could simply use the java task to invoke a TestRunner on a compiled TestCase, like our AllModelTests example:

<target name="run-tests"
        description="Run unit tests for the system"
        depends="compile-tests">
    <java classname="junit.textui.TestRunner"
          fork="true">
        <classpath>
            <path refid="java.compile.classpath"/>
            <path location="${java.classes.dir}"/>
            <path location="${junit.jar}"/>
            <path location="${java.test.classes.dir}"/>
        </classpath>
        <arg line="com.oreilly.jent.people.AllModelTests"/>
    </java>
</target>

This isn’t too difficult—we invoke the java task with the name of the TestRunner class, and within the task we define the CLASSPATH to be used (making sure to include both our compiled application classes and the JUnit library), and we specify the test to be run using an arg child on the java task, mimicking the use of command-line ...

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.