Running Unit Tests

Problem

You want to run all of the unit tests in your project using Ant.

Solution

Follow a consistent naming convention for all of your test classes, and then use Ant’s junit and batchtest tasks to locate and run the tests.

Discussion

Writing unit tests is a key XP practice, and Ant makes it easy to run those tests. A well-written buildfile should provide a target for running all tests in the project with a single command. In Example 3-7, programmers type ant junit to compile everything and then run all of the unit tests.

Example 3-7. Running unit tests

<?xml version="1.0"?> <project name="Java XP Cookbook" default="compile" basedir="."> <property name="dir.build" value="build"/> <property name="dir.src" value="src"/> <property environment="env"/> <path id="classpath.project"> <pathelement path="${dir.build}"/> </path> <target name="install.junit"> <fail unless="env.JUNIT_HOME"> The JUNIT_HOME environment variable must be set. </fail> <available property="junit.already.installed" file="${ant.home}/lib/junit.jar"/> <copy file="${env.JUNIT_HOME}/junit.jar" todir="${ant.home}/lib" failonerror="true"/> <fail unless="junit.already.installed"> junit.jar was not found in ANT_HOME/lib prior to this build, so it was copied for you. Please try your build again. </fail> </target> <target name="prepare" depends="install.junit"> <mkdir dir="${dir.build}"/> </target> <target name="clean" description="Remove all generated files."> <delete dir="${dir.build}"/> </target> <target name="compile" ...

Get Java Extreme Programming Cookbook 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.