O'Reilly logo

Java Enterprise in a Nutshell, Third Edition by William Crawford, Jim Farley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required