Java Reference
In-Depth Information
already on your classpath, you don't need to specify it in the
javac
task to compile
your tests.
You need to add a nested
classpath
element
G
in order to add the production
classes you just compiled to the classpath because the test classes call the produc-
tion classes.
Last, we have a
compile
target
H
that depends on the
compile.java
and
compile
.
test
targets.
9.4.2
The JUnit task
In chapter 3, we ran the
DefaultController
tests manually. To test changes, we had
to do the following:
■
Compile the source code.
■
Run the
TestDefaultController
test case against the compiled classes.
We can get Ant to perform both steps as part of the same
build
target. Listing 9.3
shows the
test
target.
Listing 9.3
The build file
test
target
B
<target name="test" depends="compile">
<junit printsummary="yes" haltonerror="yes" haltonfailure="yes"
fork="yes">
<formatter type="plain" usefile="false"/>
<test name="junitbook.example.TestDefaultController"/>
<classpath>
<pathelement location="${target.classes.java.dir}"/>
<pathelement location="${target.classes.test.dir}"/>
</classpath>
</junit>
</target>
We declare the
test
target and define it to depend on the
compile
target
B
. If we ask
Ant to run the
test
target, it'll run the
compile
target before running the
test
target
(unless Ant has already called
compile
). The only task defined in this target is to call
junit
C
. The
junit
printsummary
attribute causes the task to print a one-line sum-
mary at the end of the test. Setting
fork
to
yes
forces Ant to use a separate Java Virtual
Machine for each test. Although this is a performance hit, it's a good practice if you're
worried about interference between test cases. The
haltonfailure
and
haltonerror
attributes direct the build to stop if any test returns an error or a failure. In Ant, an
error is an unexpected error, like an exception, whereas a failure is a failed assert call.
We configure the
junit
task formatter to use plain text and output the test result to
the console
D
. The
test
name
attribute defines the class name of the test to run
E
.
Finally, we extend the classpath to use for this task to include the production and test
classes we just compiled
F
.
This makes up our first
test
target; next, we run the Ant build.
C
D
E
F