Save This Page
Home » apache-ant-1.8.1 » org.apache.tools » ant » taskdefs » optional » junit » [javadoc | source]
org.apache.tools.ant.taskdefs.optional.junit
public class: JUnitTask [javadoc | source]
java.lang.Object
   org.apache.tools.ant.ProjectComponent
      org.apache.tools.ant.Task
         org.apache.tools.ant.taskdefs.optional.junit.JUnitTask

All Implemented Interfaces:
    Cloneable

Runs JUnit tests.

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.

For example, the following target
  <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.

Nested Class Summary:
public static class  JUnitTask.SummaryAttribute  Print summary enumeration values. 
public static final class  JUnitTask.ForkMode  These are the different forking options 
protected class  JUnitTask.TestResultHolder  A value class that contains the result of a test. 
protected static class  JUnitTask.JUnitLogOutputStream  A stream handler for handling the junit task. 
protected static class  JUnitTask.JUnitLogStreamHandler  A log stream handler for junit. 
Field Summary
public static final  String TESTLISTENER_PREFIX   
    since: Ant - 1.7
 
static final  String TIMEOUT_MESSAGE     
static final  String NAME_OF_DUMMY_TEST     
Fields inherited from org.apache.tools.ant.Task:
target,  taskName,  taskType,  wrapper
Fields inherited from org.apache.tools.ant.ProjectComponent:
project,  location,  description
Constructor:
 public JUnitTask() throws Exception 
    Creates a new JUnitRunner and enables fork of a new Java VM.
    Throws:
    Exception - under ??? circumstances
    since: Ant - 1.2
Method from org.apache.tools.ant.taskdefs.optional.junit.JUnitTask Summary:
actOnTestResult,   actOnTestResult,   addAssertions,   addClasspathEntry,   addConfiguredSysproperty,   addEnv,   addFormatter,   addSysproperty,   addSyspropertyset,   addTest,   allTests,   cleanup,   createBatchTest,   createBootclasspath,   createClasspath,   createJvmarg,   createPermissions,   createWatchdog,   execute,   execute,   execute,   executeOrQueue,   getCommandline,   getDefaultOutput,   getIndividualTests,   getOutput,   handleErrorFlush,   handleErrorOutput,   handleFlush,   handleInput,   handleOutput,   init,   setCloneVm,   setDir,   setErrorProperty,   setFailureProperty,   setFiltertrace,   setFork,   setForkMode,   setHaltonerror,   setHaltonfailure,   setIncludeantruntime,   setJvm,   setLogFailedTests,   setMaxmemory,   setNewenvironment,   setOutputToFormatters,   setPrintsummary,   setReloading,   setShowOutput,   setTempdir,   setTimeout,   setupJUnitDelegate
Methods from org.apache.tools.ant.Task:
bindToOwner,   execute,   getOwningTarget,   getRuntimeConfigurableWrapper,   getTaskName,   getTaskType,   getWrapper,   handleErrorFlush,   handleErrorOutput,   handleFlush,   handleInput,   handleOutput,   init,   isInvalid,   log,   log,   log,   log,   markInvalid,   maybeConfigure,   perform,   reconfigure,   setOwningTarget,   setRuntimeConfigurableWrapper,   setTaskName,   setTaskType
Methods from org.apache.tools.ant.ProjectComponent:
clone,   getDescription,   getLocation,   getProject,   log,   log,   setDescription,   setLocation,   setProject
Methods from java.lang.Object:
clone,   equals,   finalize,   getClass,   hashCode,   notify,   notifyAll,   toString,   wait,   wait,   wait
Method from org.apache.tools.ant.taskdefs.optional.junit.JUnitTask Detail:
 protected  void actOnTestResult(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.
 protected  void actOnTestResult(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.
 public  void addAssertions(Assertions asserts) 
    Assertions to enable in this program (if fork=true)
 protected  void addClasspathEntry(String resource) 
    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.

 public  void addConfiguredSysproperty(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.
 public  void addEnv(Variable var) 
    Adds an environment variable; used when forking.

    Will be ignored if we are not forking a new VM.

 public  void addFormatter(FormatterElement fe) 
    Add a new formatter to all tests of this task.
 public  void addSysproperty(Variable sysp) 
Deprecated! since - ant 1.6

    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.
 public  void addSyspropertyset(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.
 public  void addTest(JUnitTest test) 
    Add a new single testcase.
 protected Enumeration allTests() 
    return an enumeration listing each test, then each batchtest
 protected  void cleanup() 
    Removes resources.

    Is invoked in execute . Subclasses that don't invoke execute should invoke this method in a finally block.

 public BatchTest createBatchTest() 
    Adds a set of tests based on pattern matching.
 public Path createBootclasspath() 
    Adds a path to the bootclasspath.
 public Path createClasspath() 
    Adds path to classpath used for tests.
 public Argument createJvmarg() 
    Adds a JVM argument; ignored if not forking.
 public Permissions createPermissions() 
    Sets the permissions for the application run inside the same JVM.
 protected ExecuteWatchdog createWatchdog() throws BuildException 
 public  void execute() throws BuildException 
    Runs the testcase.
 protected  void execute(JUnitTest arg) throws BuildException 
    Run the tests.
 protected  void execute(List testList) throws BuildException 
    Execute a list of tests in a single forked Java VM.
 protected Collection executeOrQueue(Enumeration testList,
    boolean runIndividual) 
    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.
 protected CommandlineJava getCommandline() 
    Get the command line used to run the tests.
 protected OutputStream getDefaultOutput() 
    Get the default output for a formatter.
 protected Enumeration getIndividualTests() 
    Merge all individual tests from the batchtest with all individual tests and return an enumeration over all JUnitTest.
 protected File getOutput(FormatterElement fe,
    JUnitTest test) 
    If the formatter sends output to a file, return that file. null otherwise.
 public  void handleErrorFlush(String output) 
    Pass output sent to System.err to the TestRunner so it can collect it for the formatters.
 public  void handleErrorOutput(String output) 
    Pass output sent to System.err to the TestRunner so it can collect it for the formatters.
 protected  void handleFlush(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) throws IOException 
    Handle an input request by this task.
 protected  void handleOutput(String output) 
    Pass output sent to System.out to the TestRunner so it can collect ot for the formatters.
 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.
 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.

 public  void setDir(File dir) 
    The directory to invoke the VM in. Ignored if no JVM is forked.
 public  void setErrorProperty(String propertyName) 
    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.

 public  void setFailureProperty(String propertyName) 
    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.

 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.

 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.

 public  void setForkMode(ForkMode mode) 
    Set the behavior when 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 mutliple VMs.

 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.
 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.
 public  void setIncludeantruntime(boolean b) 
    If true, include ant.jar, optional.jar and junit.jar in the forked VM.
 public  void setJvm(String value) 
    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.
 public  void setLogFailedTests(boolean logFailedTests) 
    If true, write a single "FAILED" line for failed tests to Ant's log system.
 public  void setMaxmemory(String max) 
    Set the maximum memory to be used by all forked JVMs.
 public  void setNewenvironment(boolean newenv) 
    If true, use a new environment when forked.

    Will be ignored if we are not forking a new VM.

 public  void setOutputToFormatters(boolean outputToFormatters) 
    If true, send any output generated by tests to the formatters.
 public  void setPrintsummary(SummaryAttribute value) 
    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.
 public  void setReloading(boolean value) 
    If true, force ant to re-classload all classes for each JUnit TestCase
 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.

 public  void setTempdir(File tmpDir) 
    Where Ant should place temporary files.
 public  void setTimeout(Integer value) 
    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).

 protected  void setupJUnitDelegate() 
    Sets up the delegate that will actually run the tests.

    Will be invoked implicitly once the delegate is needed.