8.7 Running a TestSuite with Ant

8.7.1 Problem

You want to integrate JUnitPerf tests into your Ant build process.

8.7.2 Solution

Add another target to the Ant buildfile that executes a junit task for all JUnitPerf classes.

8.7.3 Discussion

Ensuring all unit tests execute whenever a code change is made, no matter how trivial the change, is critical for an XP project. We have already seen numerous examples throughout this book discussing how to integrate unit testing into an Ant build process using the junit task, and JUnitPerf is no different. The only twist is that JUnitPerf tests generally take longer to execute than normal JUnit tests because of the varying loads placed on them. Remember that the ultimate goal of a test is to execute as quickly as possible. With this said, it may be better to execute JUnitPerf tests during a nightly build, or perhaps during specified times throughout the day.

No matter how your project chooses to incorporate JUnitPerf tests, the technique is the same: use the junit Ant task. Example 8-5 shows an Ant target for executing only JUnitPerf tests. This example should look similar to what you have seen in other chapters. The only difference is the names of the files to include. This book uses the naming convention "Test" for all JUnit tests, modified to "TestPerf" for JUnitPerf tests so Ant can easily separate normal JUnit tests from JUnitPerf tests.

Example 8-5. Executing JUnitPerf tests using Ant
<target name="junitperf" depends="compile">
  <junit printsummary="on" fork="false" haltonfailure="false">
    <classpath refid="classpath.project"/>
    <formatter type="plain" usefile="false"/>
    <batchtest fork="false" todir="${dir.build}">
      <fileset dir="${dir.src}">
        <include name="**/TestPerf*.java"/>
      </fileset>
    </batchtest>
  </junit>
</target>

If you examine the examples in the previous recipes you may notice that JUnitPerf classes do not extend or implement any type of JUnit-specific class or interface. So how does the junit Ant task know to execute the class as a bunch of JUnit tests? The answer lies in how the Ant JUnitTestRunner locates the tests to execute. First JUnitTestRunner uses reflection to look for a suite( ) method. Specifically, it looks for the following method signature:

public static junit.framework.Test suite(  )

If JUnitTestRunner locates this method, the returned Test is executed. Otherwise, JUnitTestRunner uses reflection to find all public methods starting with "test". This little trick allows us to provide continuous integration for any class that provides a valid JUnit suite( ) method.