Class JUnitTask
- All Implemented Interfaces:
Cloneable
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).
fork. A
number of attributes and elements allow you to set up how this JVM runs.-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classThese are the different forking optionsprotected static classA stream handler for handling the junit task.protected static classA log stream handler for junit.static classPrint summary enumeration values.protected classA value class that contains the result of a test. -
Field Summary
FieldsFields inherited from class org.apache.tools.ant.Task
target, taskName, taskType, wrapperFields inherited from class org.apache.tools.ant.ProjectComponent
description, location, project -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidactOnTestResult(int exitValue, boolean wasKilled, JUnitTest test, String name) Logs information about failed tests, potentially stops processing (by throwing a BuildException) if a failure/error occurred or sets a property.protected voidactOnTestResult(JUnitTask.TestResultHolder result, JUnitTest test, String name) Logs information about failed tests, potentially stops processing (by throwing a BuildException) if a failure/error occurred or sets a property.voidaddAssertions(org.apache.tools.ant.types.Assertions asserts) Assertions to enable in this program (if fork=true)protected voidaddClasspathEntry(String resource) Search for the given resource and add the directory or archive that contains it to the classpath.voidaddConfiguredSysproperty(org.apache.tools.ant.types.Environment.Variable sysp) Adds a system property that tests can access.voidaddEnv(org.apache.tools.ant.types.Environment.Variable var) Adds an environment variable; used when forking.voidAdd a new formatter to all tests of this task.voidaddSyspropertyset(org.apache.tools.ant.types.PropertySet sysp) Adds a set of properties that will be used as system properties that tests can access.voidAdd a new single testcase.protected EnumerationallTests()return an enumeration listing each test, then each batchtestprotected voidcleanup()Removes resources.Adds a set of tests based on pattern matching.org.apache.tools.ant.types.PathAdds a path to the bootclasspath.org.apache.tools.ant.types.PathAdds path to classpath used for tests.org.apache.tools.ant.types.Commandline.ArgumentAdds a JVM argument; ignored if not forking.org.apache.tools.ant.types.PermissionsSets the permissions for the application run inside the same JVM.protected org.apache.tools.ant.taskdefs.ExecuteWatchdogvoidexecute()Runs the testcase.protected voidRun the tests.protected voidExecute a list of tests in a single forked Java VM.protected CollectionexecuteOrQueue(Enumeration testList, boolean runIndividual) Executes all tests that don't need to be forked (or all tests if the runIndividual argument is true.protected org.apache.tools.ant.types.CommandlineJavaGet the command line used to run the tests.protected OutputStreamGet the default output for a formatter.protected EnumerationMerge all individual tests from the batchtest with all individual tests and return an enumeration over all JUnitTest.protected FilegetOutput(FormatterElement fe, JUnitTest test) If the formatter sends output to a file, return that file.voidhandleErrorFlush(String output) Pass output sent to System.err to the TestRunner so it can collect it for the formatters.voidhandleErrorOutput(String output) Pass output sent to System.err to the TestRunner so it can collect it for the formatters.protected voidhandleFlush(String output) Pass output sent to System.out to the TestRunner so it can collect ot for the formatters.protected inthandleInput(byte[] buffer, int offset, int length) Handle an input request by this task.protected voidhandleOutput(String output) Pass output sent to System.out to the TestRunner so it can collect ot for the formatters.voidinit()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.voidsetAdditionalClasspath(String classpath) voidsetCloneVm(boolean cloneVm) If set, system properties will be copied to the cloned VM - as well as the bootclasspath unless you have explicitly specified a bootclaspath.voidThe directory to invoke the VM in.voidsetErrorProperty(String propertyName) Property to set to "true" if there is a error in a test.voidsetFailureProperty(String propertyName) Property to set to "true" if there is a failure in a test.voidsetFiltertrace(boolean value) If true, smartly filter the stack frames of JUnit errors and failures before reporting them.voidsetFork(boolean value) If true, JVM should be forked for each test.voidSet the behavior whenforkfork has been enabled.voidsetHaltonerror(boolean value) If true, stop the build process when there is an error in a test.voidsetHaltonfailure(boolean value) If true, stop the build process if a test fails (errors are considered failures as well).voidsetIncludeantruntime(boolean b) If true, include ant.jar, optional.jar and junit.jar in the forked VM.voidThe command used to invoke the Java Virtual Machine, default is 'java'.voidsetMaxmemory(String max) Set the maximum memory to be used by all forked JVMs.voidsetNewenvironment(boolean newenv) If true, use a new environment when forked.voidsetOutputToFormatters(boolean outputToFormatters) If true, send any output generated by tests to the formatters.voidsetPlatformHome(String platformhome) voidIf true, print one-line statistics for each test, or "withOutAndErr" to also show standard output and error.voidsetReloading(boolean value) If true, force ant to re-classload all classes for each JUnit TestCasevoidsetShowOutput(boolean showOutput) If true, send any output generated by tests to Ant's logging system as well as to the formatters.voidsetSuppressJunitTenant(boolean suppressJunitTenant) If true, Junit Tenant wil not be started for test execution.voidsetTempdir(File tmpDir) Where Ant should place temporary files.voidsetTimeout(Integer value) Set the timeout value (in milliseconds).voidprotected voidSets up the delegate that will actually run the tests.Methods inherited from class org.apache.tools.ant.Task
bindToOwner, getOwningTarget, getRuntimeConfigurableWrapper, getTaskName, getTaskType, getWrapper, isInvalid, log, log, log, log, maybeConfigure, perform, reconfigure, setOwningTarget, setRuntimeConfigurableWrapper, setTaskName, setTaskTypeMethods inherited from class org.apache.tools.ant.ProjectComponent
clone, getDescription, getLocation, getProject, setDescription, setLocation, setProject
-
Field Details
-
TESTLISTENER_PREFIX
- Since:
- Ant 1.7
- See Also:
-
-
Constructor Details
-
JUnitTask
Creates a new JUnitRunner and enables fork of a new Java VM.- Throws:
Exception- under ??? circumstances- Since:
- Ant 1.2
-
-
Method Details
-
setPlatformHome
-
setAdditionalClasspath
-
setToDir
-
setReloading
public void setReloading(boolean value) If true, force ant to re-classload all classes for each JUnit TestCase- Parameters:
value- force class reloading for each test case
-
setFiltertrace
public void setFiltertrace(boolean value) If true, smartly filter the stack frames of JUnit errors and failures before reporting them.This property is applied on all BatchTest (batchtest) and JUnitTest (test) however it can possibly be overridden by their own properties.
- Parameters:
value- false if it should not filter, otherwise true- Since:
- Ant 1.5
-
setHaltonerror
public void setHaltonerror(boolean value) If true, stop the build process when there is an error in a test. This property is applied on all BatchTest (batchtest) and JUnitTest (test) however it can possibly be overridden by their own properties.- Parameters:
value- true if it should halt, otherwise false- Since:
- Ant 1.2
-
setErrorProperty
Property to set to "true" if there is a error in a test.This property is applied on all BatchTest (batchtest) and JUnitTest (test), however, it can possibly be overriden by their own properties.
- Parameters:
propertyName- the name of the property to set in the event of an error.- Since:
- Ant 1.4
-
setHaltonfailure
public void setHaltonfailure(boolean value) If true, stop the build process if a test fails (errors are considered failures as well). This property is applied on all BatchTest (batchtest) and JUnitTest (test) however it can possibly be overridden by their own properties.- Parameters:
value- true if it should halt, otherwise false- Since:
- Ant 1.2
-
setFailureProperty
Property to set to "true" if there is a failure in a test.This property is applied on all BatchTest (batchtest) and JUnitTest (test), however, it can possibly be overriden by their own properties.
- Parameters:
propertyName- the name of the property to set in the event of an failure.- Since:
- Ant 1.4
-
setFork
public void setFork(boolean value) If true, JVM should be forked for each test.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.
- Parameters:
value- true if a JVM should be forked, otherwise false- Since:
- Ant 1.2
- See Also:
-
setForkMode
Set the behavior whenforkfork 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 mutliple VMs.
- Parameters:
mode- the mode to use.- Since:
- Ant 1.6.2
-
setSuppressJunitTenant
public void setSuppressJunitTenant(boolean suppressJunitTenant) If true, Junit Tenant wil not be started for test execution. Might be useful especially in case of webtests- Parameters:
suppressJunitTenant- true if Junit tenant should not be started, otherwise false
-
setPrintsummary
If true, print one-line statistics for each test, or "withOutAndErr" to also show standard output and error. Can take the values on, off, and withOutAndErr.- Parameters:
value- true to print a summary, withOutAndErr to include the test's output as well, false otherwise.- Since:
- Ant 1.2
- See Also:
-
setTimeout
Set the timeout value (in milliseconds).If the test is running for more than this value, the test will be canceled. (works only when in 'fork' mode).
- Parameters:
value- the maximum time (in milliseconds) allowed before declaring the test as 'timed-out'- Since:
- Ant 1.2
- See Also:
-
setMaxmemory
Set the maximum memory to be used by all forked JVMs.- Parameters:
max- the value as defined by -mx or -Xmx in the java command line options.- Since:
- Ant 1.2
-
setJvm
The command used to invoke the Java Virtual Machine, default is 'java'. The command is resolved by java.lang.Runtime.exec(). Ignored if fork is disabled.- Parameters:
value- the new VM to use instead of java- Since:
- Ant 1.2
- See Also:
-
createJvmarg
public org.apache.tools.ant.types.Commandline.Argument createJvmarg()Adds a JVM argument; ignored if not forking.- Returns:
- create a new JVM argument so that any argument can be passed to the JVM.
- Since:
- Ant 1.2
- See Also:
-
setDir
The directory to invoke the VM in. Ignored if no JVM is forked.- Parameters:
dir- the directory to invoke the JVM from.- Since:
- Ant 1.2
- See Also:
-
addConfiguredSysproperty
public void addConfiguredSysproperty(org.apache.tools.ant.types.Environment.Variable sysp) Adds a system property that tests can access. This might be useful to tranfer Ant properties to the testcases when JVM forking is not enabled.- Parameters:
sysp- new environment variable to add- Since:
- Ant 1.6
-
addSyspropertyset
public void addSyspropertyset(org.apache.tools.ant.types.PropertySet sysp) Adds a set of properties that will be used as system properties that tests can access. This might be useful to tranfer Ant properties to the testcases when JVM forking is not enabled.- Parameters:
sysp- set of properties to be added- Since:
- Ant 1.6
-
createClasspath
public org.apache.tools.ant.types.Path createClasspath()Adds path to classpath used for tests.- Returns:
- reference to the classpath in the embedded java command line
- Since:
- Ant 1.2
-
createBootclasspath
public org.apache.tools.ant.types.Path createBootclasspath()Adds a path to the bootclasspath.- Returns:
- reference to the bootclasspath in the embedded java command line
- Since:
- Ant 1.6
-
addEnv
public void addEnv(org.apache.tools.ant.types.Environment.Variable var) Adds an environment variable; used when forking.Will be ignored if we are not forking a new VM.
- Parameters:
var- environment variable to be added- Since:
- Ant 1.5
-
setNewenvironment
public void setNewenvironment(boolean newenv) If true, use a new environment when forked.Will be ignored if we are not forking a new VM.
- Parameters:
newenv- boolean indicating if setting a new environment is wished- Since:
- Ant 1.5
-
addTest
Add a new single testcase.- Parameters:
test- a new single testcase- Since:
- Ant 1.2
- See Also:
-
createBatchTest
Adds a set of tests based on pattern matching.- Returns:
- a new instance of a batch test.
- Since:
- Ant 1.2
- See Also:
-
addFormatter
Add a new formatter to all tests of this task.- Parameters:
fe- formatter element- Since:
- Ant 1.2
-
setIncludeantruntime
public void setIncludeantruntime(boolean b) If true, include ant.jar, optional.jar and junit.jar in the forked VM.- Parameters:
b- include ant run time yes or no- Since:
- Ant 1.5
-
setShowOutput
public void setShowOutput(boolean showOutput) If true, send any output generated by tests to Ant's logging system as well as to the formatters. By default only the formatters receive the output.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.
- Parameters:
showOutput- if true, send output to Ant's logging system too- Since:
- Ant 1.5
-
setOutputToFormatters
public void setOutputToFormatters(boolean outputToFormatters) If true, send any output generated by tests to the formatters.- Parameters:
outputToFormatters- if true, send output to formatters (Default is true).- Since:
- Ant 1.7.0
-
addAssertions
public void addAssertions(org.apache.tools.ant.types.Assertions asserts) Assertions to enable in this program (if fork=true)- Parameters:
asserts- assertion set- Since:
- Ant 1.6
-
createPermissions
public org.apache.tools.ant.types.Permissions createPermissions()Sets the permissions for the application run inside the same JVM.- Returns:
- .
- Since:
- Ant 1.6
-
setCloneVm
public 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 bootclaspath.Doesn't have any effect unless fork is true.
- Parameters:
cloneVm- abooleanvalue.- Since:
- Ant 1.7
-
setTempdir
Where Ant should place temporary files.- Parameters:
tmpDir- location where temporary files should go to- Since:
- Ant 1.6
-
init
public 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.- Overrides:
initin classorg.apache.tools.ant.Task- Since:
- Ant 1.4
-
setupJUnitDelegate
protected void setupJUnitDelegate()Sets up the delegate that will actually run the tests.Will be invoked implicitly once the delegate is needed.
- Since:
- Ant 1.7.1
-
execute
public void execute() throws org.apache.tools.ant.BuildExceptionRuns the testcase.- Overrides:
executein classorg.apache.tools.ant.Task- Throws:
org.apache.tools.ant.BuildException- in case of test failures or errors- Since:
- Ant 1.2
-
execute
Run the tests.- Parameters:
arg- one JunitTest- Throws:
org.apache.tools.ant.BuildException- in case of test failures or errors
-
execute
Execute a list of tests in a single forked Java VM.- Parameters:
testList- the list of tests to execute.- Throws:
org.apache.tools.ant.BuildException- on error.
-
handleOutput
Pass output sent to System.out to the TestRunner so it can collect ot for the formatters.- Overrides:
handleOutputin classorg.apache.tools.ant.Task- Parameters:
output- output coming from System.out- Since:
- Ant 1.5
-
handleInput
Handle an input request by this task.- Overrides:
handleInputin classorg.apache.tools.ant.Task- Parameters:
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.- Returns:
- the number of bytes read.
- Throws:
IOException- if the data cannot be read.- Since:
- Ant 1.6
- See Also:
-
This implementation delegates to a runner if it present.
-
handleFlush
Pass output sent to System.out to the TestRunner so it can collect ot for the formatters.- Overrides:
handleFlushin classorg.apache.tools.ant.Task- Parameters:
output- output coming from System.out- Since:
- Ant 1.5.2
-
handleErrorOutput
Pass output sent to System.err to the TestRunner so it can collect it for the formatters.- Overrides:
handleErrorOutputin classorg.apache.tools.ant.Task- Parameters:
output- output coming from System.err- Since:
- Ant 1.5
-
handleErrorFlush
Pass output sent to System.err to the TestRunner so it can collect it for the formatters.- Overrides:
handleErrorFlushin classorg.apache.tools.ant.Task- Parameters:
output- coming from System.err- Since:
- Ant 1.5.2
-
createWatchdog
protected org.apache.tools.ant.taskdefs.ExecuteWatchdog createWatchdog() throws org.apache.tools.ant.BuildException- Returns:
- null if there is a timeout value, otherwise the watchdog instance.
- Throws:
org.apache.tools.ant.BuildException- under unspecified circumstances- Since:
- Ant 1.2
-
getDefaultOutput
Get the default output for a formatter.- Returns:
- default output stream for a formatter
- Since:
- Ant 1.3
-
getIndividualTests
Merge all individual tests from the batchtest with all individual tests and return an enumeration over all JUnitTest.- Returns:
- enumeration over individual tests
- Since:
- Ant 1.3
-
allTests
return an enumeration listing each test, then each batchtest- Returns:
- enumeration
- Since:
- Ant 1.3
-
getOutput
If the formatter sends output to a file, return that file. null otherwise.- Parameters:
fe- formatter elementtest- one JUnit test- Returns:
- file reference
- Since:
- Ant 1.3
-
addClasspathEntry
Search for the given resource and add the directory or archive that contains it to the classpath.Doesn't work for archives in JDK 1.1 as the URL returned by getResource doesn't contain the name of the archive.
- Parameters:
resource- resource that one wants to lookup- Since:
- Ant 1.4
-
cleanup
protected void cleanup()Removes resources.Is invoked in
execute. Subclasses that don't invoke execute should invoke this method in a finally block.- Since:
- Ant 1.7.1
-
getCommandline
protected org.apache.tools.ant.types.CommandlineJava getCommandline()Get the command line used to run the tests.- Returns:
- the command line.
- Since:
- Ant 1.6.2
-
executeOrQueue
Executes all tests that don't need to be forked (or all tests if the runIndividual argument is true. Returns a collection of lists of tests that share the same VM configuration and haven't been executed yet.- Parameters:
testList- the list of tests to be executed or queued.runIndividual- if true execute each test individually.- Returns:
- a list of tasks to be executed.
- Since:
- 1.6.2
-
actOnTestResult
Logs information about failed tests, potentially stops processing (by throwing a BuildException) if a failure/error occurred or sets a property.- Parameters:
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.- Since:
- Ant 1.6.2
-
actOnTestResult
Logs information about failed tests, potentially stops processing (by throwing a BuildException) if a failure/error occurred or sets a property.- Parameters:
result- the result of the test.test- the test in question.name- the name of the test.- Since:
- Ant 1.7
-