3.17 Running Specific Tests

3.17.1 Problem

You want to use Ant to run a single test case.

3.17.2 Solution

Use the junit task with a nested test element.

3.17.3 Discussion

Recipe 3.16 showed how to use junit in conjunction with batchtest to run every test in one or more paths. There may be times, however, when you want to selectively run a single test. For instance, you might be working on a specific class and don't want to run hundreds of tests for each change you make. To run a single test using Ant, use the test element instead of batchtest. Example 3-8 shows how to define a target that runs a specific test.

Example 3-8. Running a single test
  <target name="junit2" depends="compile">
    <!-- you may override this on the command line:
         ant -Dtestcase=com/oreilly/javaxp/junit/TestGame junit2 -->
    <property name="testcase" 
              value="com/oreilly/javaxp/junit/TestPerson"/>

    <junit fork="false">
      <classpath refid="classpath.project"/>
      <formatter type="plain" usefile="false"/>

      <test name="${testcase}"/>
    </junit>
  </target>

Rather than hardcode the name of the test, our example allows the user to specify the test name on the Ant command line. This takes advantage of Ant's ability to obtain properties from the command line using the -D syntax.

3.17.4 See Also

The previous recipe showed how to run all tests.