public class JUnitTask extends Task
JUnit is a framework to create unit tests. It has been initially created by Erich Gamma and Kent Beck. JUnit can be found at http://www.junit.org.
JUnitTask
can run a single specific
JUnitTest
using the test
element.
<target name="test-int-chars" depends="jar-test"> <echo message="testing international characters"/> <junit printsummary="no" haltonfailure="yes" fork="false"> <classpath refid="classpath"/> <formatter type="plain" usefile="false" /> <test name="org.apache.ecs.InternationalCharTest" /> </junit> </target>
runs a single junit test
(org.apache.ecs.InternationalCharTest
) in the current
VM using the path with id classpath
as classpath and
presents the results formatted using the standard
plain
formatter on the command line.
This task can also run batches of tests. The
batchtest
element creates a BatchTest
based on a fileset. This allows, for example, all classes found in
directory to be run as testcases.
For example,
<target name="run-tests" depends="dump-info,compile-tests" if="junit.present"> <junit printsummary="no" haltonfailure="yes" fork="${junit.fork}"> <jvmarg value="-classic"/> <classpath refid="tests-classpath"/> <sysproperty key="build.tests" value="${build.tests}"/> <formatter type="brief" usefile="false" /> <batchtest> <fileset dir="${tests.dir}"> <include name="**/*Test*" /> </fileset> </batchtest> </junit> </target>
this target finds any classes with a test
directory
anywhere in their path (under the top ${tests.dir}
, of
course) and creates JUnitTest
's for each one.
Of course, <junit>
and
<batch>
elements can be combined for more
complex tests. For an example, see the ant build.xml
target run-tests
(the second example is an edited
version).
To spawn a new Java VM to prevent interferences between
different testcases, you need to enable fork
. A
number of attributes and elements allow you to set up how this JVM
runs.
Modifier and Type | Class and Description |
---|---|
static class |
JUnitTask.ForkMode
These are the different forking options
|
protected static class |
JUnitTask.JUnitLogOutputStream
A stream handler for handling the junit task.
|
protected static class |
JUnitTask.JUnitLogStreamHandler
A log stream handler for junit.
|
static class |
JUnitTask.SummaryAttribute
Print summary enumeration values.
|
protected static class |
JUnitTask.TestResultHolder
A value class that contains the result of a test.
|
Modifier and Type | Field and Description |
---|---|
static java.lang.String |
ENABLE_TESTLISTENER_EVENTS
Name of magic property that enables test listener events.
|
static java.lang.String |
TESTLISTENER_PREFIX |
description, location, project
Constructor and Description |
---|
JUnitTask()
Creates a new JUnitRunner and enables fork of a new Java VM.
|
Modifier and Type | Method and Description |
---|---|
protected void |
actOnTestResult(int exitValue,
boolean wasKilled,
JUnitTest test,
java.lang.String name)
Logs information about failed tests, potentially stops
processing (by throwing a BuildException) if a failure/error
occurred or sets a property.
|
protected void |
actOnTestResult(JUnitTask.TestResultHolder result,
JUnitTest test,
java.lang.String name)
Logs information about failed tests, potentially stops
processing (by throwing a BuildException) if a failure/error
occurred or sets a property.
|
void |
addAssertions(Assertions asserts)
Assertions to enable in this program (if fork=true)
|
protected void |
addClasspathEntry(java.lang.String resource)
Search for the given resource and add the directory or archive
that contains it to the classpath.
|
void |
addConfiguredSysproperty(Environment.Variable sysp)
Adds a system property that tests can access.
|
void |
addEnv(Environment.Variable var)
Adds an environment variable; used when forking.
|
void |
addFormatter(FormatterElement fe)
Add a new formatter to all tests of this task.
|
void |
addSysproperty(Environment.Variable sysp)
Deprecated.
since Ant 1.6
|
void |
addSyspropertyset(PropertySet sysp)
Adds a set of properties that will be used as system properties
that tests can access.
|
void |
addTest(JUnitTest test)
Add a new single testcase.
|
protected java.util.Enumeration<JUnitTest> |
allTests()
return an enumeration listing each test, then each batchtest
|
protected void |
cleanup()
Removes resources.
|
BatchTest |
createBatchTest()
Adds a set of tests based on pattern matching.
|
Path |
createBootclasspath()
Adds a path to the bootclasspath.
|
Path |
createClasspath()
Adds path to classpath used for tests.
|
Commandline.Argument |
createJvmarg()
Adds a JVM argument; ignored if not forking.
|
Path |
createModulepath()
Add a path to the modulepath.
|
Permissions |
createPermissions()
Sets the permissions for the application run inside the same JVM.
|
Path |
createUpgrademodulepath()
Add a path to the upgrademodulepath.
|
protected ExecuteWatchdog |
createWatchdog() |
void |
execute()
Runs the testcase.
|
protected void |
execute(JUnitTest arg)
Run the tests.
|
protected void |
execute(JUnitTest arg,
int thread)
Run the tests.
|
protected void |
execute(java.util.List testList)
Execute a list of tests in a single forked Java VM.
|
protected void |
execute(java.util.List testList,
int thread)
Execute a list of tests in a single forked Java VM.
|
protected java.util.Collection<java.util.List> |
executeOrQueue(java.util.Enumeration<JUnitTest> testList,
boolean runIndividual)
Executes all tests that don't need to be forked (or all tests
if the runIndividual argument is true.
|
protected CommandlineJava |
getCommandline()
Get the command line used to run the tests.
|
protected java.io.OutputStream |
getDefaultOutput()
Get the default output for a formatter.
|
boolean |
getEnableTestListenerEvents()
Whether test listener events shall be generated.
|
protected java.util.Enumeration<JUnitTest> |
getIndividualTests()
Merge all individual tests from the batchtest with all individual tests
and return an enumeration over all JUnitTest.
|
protected java.io.File |
getOutput(FormatterElement fe,
JUnitTest test)
If the formatter sends output to a file, return that file.
|
void |
handleErrorFlush(java.lang.String output)
Pass output sent to System.err to the TestRunner so it can
collect it for the formatters.
|
void |
handleErrorOutput(java.lang.String output)
Pass output sent to System.err to the TestRunner so it can
collect it for the formatters.
|
protected void |
handleFlush(java.lang.String output)
Pass output sent to System.out to the TestRunner so it can
collect ot for the formatters.
|
protected int |
handleInput(byte[] buffer,
int offset,
int length)
Handle an input request by this task.
|
protected void |
handleOutput(java.lang.String output)
Pass output sent to System.out to the TestRunner so it can
collect it for the formatters.
|
void |
init()
Adds the jars or directories containing Ant, this task and
JUnit to the classpath - this should make the forked JVM work
without having to specify them directly.
|
void |
setCloneVm(boolean cloneVm)
If set, system properties will be copied to the cloned VM - as
well as the bootclasspath unless you have explicitly specified
a bootclasspath.
|
void |
setDir(java.io.File dir)
The directory to invoke the VM in.
|
void |
setEnableTestListenerEvents(boolean b)
Whether test listener events shall be generated.
|
void |
setErrorProperty(java.lang.String propertyName)
Property to set to "true" if there is a error in a test.
|
void |
setFailureProperty(java.lang.String propertyName)
Property to set to "true" if there is a failure in a test.
|
void |
setFiltertrace(boolean value)
If true, smartly filter the stack frames of
JUnit errors and failures before reporting them.
|
void |
setFork(boolean value)
If true, JVM should be forked for each test.
|
void |
setForkMode(JUnitTask.ForkMode mode)
Set the behavior when
fork fork has been enabled. |
void |
setHaltonerror(boolean value)
If true, stop the build process when there is an error in a test.
|
void |
setHaltonfailure(boolean value)
If true, stop the build process if a test fails
(errors are considered failures as well).
|
void |
setIncludeantruntime(boolean b)
If true, include ant.jar, optional.jar and junit.jar in the forked VM.
|
void |
setJvm(java.lang.String value)
The command used to invoke the Java Virtual Machine,
default is 'java'.
|
void |
setLogFailedTests(boolean logFailedTests)
If true, write a single "FAILED" line for failed tests to Ant's
log system.
|
void |
setMaxmemory(java.lang.String max)
Set the maximum memory to be used by all forked JVMs.
|
void |
setNewenvironment(boolean newenv)
If true, use a new environment when forked.
|
void |
setOutputToFormatters(boolean outputToFormatters)
If true, send any output generated by tests to the formatters.
|
void |
setPrintsummary(JUnitTask.SummaryAttribute value)
If true, print one-line statistics for each test, or "withOutAndErr"
to also show standard output and error.
|
void |
setReloading(boolean value)
If true, force ant to re-classload all classes for each JUnit TestCase
|
void |
setShowOutput(boolean showOutput)
If true, send any output generated by tests to Ant's logging system
as well as to the formatters.
|
void |
setTempdir(java.io.File tmpDir)
Where Ant should place temporary files.
|
void |
setThreads(int threads)
Set the number of test threads to be used for parallel test
execution.
|
void |
setTimeout(java.lang.Integer value)
Set the timeout value (in milliseconds).
|
protected void |
setupJUnitDelegate()
Sets up the delegate that will actually run the tests.
|
bindToOwner, getOwningTarget, getRuntimeConfigurableWrapper, getTaskName, getTaskType, getWrapper, isInvalid, log, log, log, log, maybeConfigure, perform, reconfigure, setOwningTarget, setRuntimeConfigurableWrapper, setTaskName, setTaskType
clone, getDescription, getLocation, getProject, setDescription, setLocation, setProject
public static final java.lang.String TESTLISTENER_PREFIX
public static final java.lang.String ENABLE_TESTLISTENER_EVENTS
public JUnitTask() throws java.lang.Exception
java.lang.Exception
- neverpublic void setReloading(boolean value)
value
- force class reloading for each test casepublic void setFiltertrace(boolean value)
This property is applied on all BatchTest (batchtest) and JUnitTest (test) however it can possibly be overridden by their own properties.
value
- false if it should not filter, otherwise
truepublic void setHaltonerror(boolean value)
value
- true if it should halt, otherwise
falsepublic void setErrorProperty(java.lang.String propertyName)
This property is applied on all BatchTest (batchtest) and JUnitTest (test), however, it can possibly be overridden by their own properties.
propertyName
- the name of the property to set in the
event of an error.public void setHaltonfailure(boolean value)
value
- true if it should halt, otherwise
falsepublic void setFailureProperty(java.lang.String propertyName)
This property is applied on all BatchTest (batchtest) and JUnitTest (test), however, it can possibly be overridden by their own properties.
propertyName
- the name of the property to set in the
event of an failure.public void setFork(boolean value)
It avoids interference between testcases and possibly avoids hanging the build. this property is applied on all BatchTest (batchtest) and JUnitTest (test) however it can possibly be overridden by their own properties.
value
- true if a JVM should be forked, otherwise
falsesetTimeout(java.lang.Integer)
public void setForkMode(JUnitTask.ForkMode mode)
fork
fork has been enabled.
Possible values are "once", "perTest" and "perBatch". If set to "once", only a single Java VM will be forked for all tests, with "perTest" (the default) each test will run in a fresh Java VM and "perBatch" will run all tests from the same <batchtest> in the same Java VM.
This attribute will be ignored if tests run in the same VM as Ant.
Only tests with the same configuration of haltonerror, haltonfailure, errorproperty, failureproperty and filtertrace can share a forked Java VM, so even if you set the value to "once", Ant may need to fork multiple VMs.
mode
- the mode to use.public void setThreads(int threads)
This attribute will be ignored if tests run in the same VM as Ant.
threads
- intpublic void setPrintsummary(JUnitTask.SummaryAttribute value)
value
- true to print a summary,
withOutAndErr to include the test's output as
well, false otherwise.SummaryJUnitResultFormatter
public void setTimeout(java.lang.Integer value)
If the test is running for more than this value, the test will be canceled. (works only when in 'fork' mode).
value
- the maximum time (in milliseconds) allowed before
declaring the test as 'timed-out'setFork(boolean)
public void setMaxmemory(java.lang.String max)
max
- the value as defined by -mx or -Xmx
in the java command line options.public void setJvm(java.lang.String value)
value
- the new VM to use instead of javasetFork(boolean)
public Commandline.Argument createJvmarg()
setFork(boolean)
public void setDir(java.io.File dir)
dir
- the directory to invoke the JVM from.setFork(boolean)
@Deprecated public void addSysproperty(Environment.Variable sysp)
sysp
- environment variable to addpublic void addConfiguredSysproperty(Environment.Variable sysp)
sysp
- new environment variable to addpublic void addSyspropertyset(PropertySet sysp)
This might be useful to transfer Ant properties to the testcases when JVM forking is not enabled.
sysp
- set of properties to be addedpublic Path createClasspath()
public Path createBootclasspath()
public Path createModulepath()
public Path createUpgrademodulepath()
public void addEnv(Environment.Variable var)
Will be ignored if we are not forking a new VM.
var
- environment variable to be addedpublic void setNewenvironment(boolean newenv)
Will be ignored if we are not forking a new VM.
newenv
- boolean indicating if setting a new environment is wishedpublic void addTest(JUnitTest test)
test
- a new single testcaseJUnitTest
public BatchTest createBatchTest()
BatchTest
public void addFormatter(FormatterElement fe)
fe
- formatter elementpublic void setIncludeantruntime(boolean b)
b
- include ant run time yes or nopublic void setShowOutput(boolean showOutput)
Output will always be passed to the formatters and not by shown by default. This option should for example be set for tests that are interactive and prompt the user to do something.
showOutput
- if true, send output to Ant's logging system toopublic void setOutputToFormatters(boolean outputToFormatters)
outputToFormatters
- if true, send output to formatters (Default
is true).public void setLogFailedTests(boolean logFailedTests)
logFailedTests
- booleanpublic void addAssertions(Assertions asserts)
asserts
- assertion setpublic Permissions createPermissions()
public void setCloneVm(boolean cloneVm)
Doesn't have any effect unless fork is true.
cloneVm
- a boolean
value.public void setTempdir(java.io.File tmpDir)
tmpDir
- location where temporary files should go topublic void setEnableTestListenerEvents(boolean b)
Defaults to false.
This value will be overridden by the magic property ant.junit.enabletestlistenerevents if it has been set.
b
- booleanpublic boolean getEnableTestListenerEvents()
public void init()
protected void setupJUnitDelegate()
Will be invoked implicitly once the delegate is needed.
public void execute() throws BuildException
execute
in class Task
BuildException
- in case of test failures or errorsprotected void execute(JUnitTest arg, int thread) throws BuildException
arg
- one JUnitTestthread
- Identifies which thread is test running in (0 for single-threaded runs)BuildException
- in case of test failures or errorsprotected void execute(JUnitTest arg) throws BuildException
arg
- one JUnitTestBuildException
- in case of test failures or errorsprotected void execute(java.util.List testList, int thread) throws BuildException
testList
- the list of tests to execute.thread
- Identifies which thread is test running in (0 for single-threaded runs)BuildException
- on error.protected void execute(java.util.List testList) throws BuildException
testList
- the list of tests to execute.BuildException
- on error.protected void handleOutput(java.lang.String output)
handleOutput
in class Task
output
- output coming from System.outprotected int handleInput(byte[] buffer, int offset, int length) throws java.io.IOException
handleInput
in class Task
buffer
- the buffer into which data is to be read.offset
- the offset into the buffer at which data is stored.length
- the amount of data to read.java.io.IOException
- if the data cannot be read.This implementation delegates to a runner if it
present.
protected void handleFlush(java.lang.String output)
handleFlush
in class Task
output
- output coming from System.outpublic void handleErrorOutput(java.lang.String output)
handleErrorOutput
in class Task
output
- output coming from System.errpublic void handleErrorFlush(java.lang.String output)
handleErrorFlush
in class Task
output
- coming from System.errprotected ExecuteWatchdog createWatchdog() throws BuildException
BuildException
- under unspecified circumstancesprotected java.io.OutputStream getDefaultOutput()
protected java.util.Enumeration<JUnitTest> getIndividualTests()
protected java.util.Enumeration<JUnitTest> allTests()
protected java.io.File getOutput(FormatterElement fe, JUnitTest test)
fe
- formatter elementtest
- one JUnit testprotected void addClasspathEntry(java.lang.String resource)
Doesn't work for archives in JDK 1.1 as the URL returned by getResource doesn't contain the name of the archive.
resource
- resource that one wants to lookupprotected void cleanup()
Is invoked in execute
. Subclasses that
don't invoke execute should invoke this method in a finally
block.
protected CommandlineJava getCommandline()
protected java.util.Collection<java.util.List> executeOrQueue(java.util.Enumeration<JUnitTest> testList, boolean runIndividual)
testList
- the list of tests to be executed or queued.runIndividual
- if true execute each test individually.protected void actOnTestResult(int exitValue, boolean wasKilled, JUnitTest test, java.lang.String name)
exitValue
- the exitValue of the test.wasKilled
- if true, the test had been killed.test
- the test in question.name
- the name of the test.protected void actOnTestResult(JUnitTask.TestResultHolder result, JUnitTest test, java.lang.String name)
result
- the result of the test.test
- the test in question.name
- the name of the test.