We now have a build file that can compile our
Java files and make distributable jar files. In the next step, we'll add the
ability to run our unit tests from our build. We'll use the JUnit optional Ant
task to run our tests and generate an HTML report. Note that to run the
JUnit optional task, you'll need to add the JUnit JAR file to the Ant
classpath. This is usually done by putting the JUnit JAR into the
[anthome]/lib
directory, or by adding it to the
LOCALCLASSPATH
environment variable.
|
|
|
|
<property name="test-out.dir" location="${work.dir}/test-out" />
<property name="tests" value="**/*Test.class" />
<target name="test"
description="Run unit tests and create a report">
<delete dir="${test-out.dir}" failonerror="false" />
<mkdir dir="${test-out.dir}" />
<junit
printsummary="true"
fork="false"
dir="${test-out.dir}"
tempdir="${test-out.dir}"
errorproperty="unit-test.error"
failureproperty="unit-test.failure">
<formatter type="plain" />
<classpath>
<path refid="path.simpleproject-tests.jar.build" />
<pathelement location="${classes-tests.dir}" />
</classpath>
<batchtest todir="${test-out.dir}">
<fileset dir="${classes-tests.dir}" includes="${tests}" />
</batchtest>
</junit>
<fail if="unit-test.error" />
<fail if="unit-test.failure" />
</target>
|
|
|
|
|
The only non-standard bit in this target is the
<classpath>
, which uses the Path reference created by the
<libraryDef>
when we
created the compile task.
By storing the TestCase naming convention in a property, it allows users to
alter which test they want to run when they invoke Ant, by adding the
parameter -Dtests=my/package/*Test.class
.
The ${test-out.dir}
directory here stores the output files
generated for each TestCase executed by the <batchtest>
task. It also stores the output generated by any unit test (if they didn't
clean themselves up). We delete this directory before running the tests to
ensure that we have a clean unit test run.