Extending ANT JUnitTask

1 minute read

I needed to run the JUnitTask from code (since i needed to create a custom FileSet for the BatchTest). I started out with a plan Task, but while the code below runs the classpath details that the task uses are incorrect.

<pre class="prettyprint">
public class JunitTestExistsTask extends Task {

private void runAntJUnitTests()
throws BuildException {

try
{
JUnitTask jUnitTask = new JUnitTask();
jUnitTask.setOutputToFormatters(true);
jUnitTask.setProject(getProject());
jUnitTask.setShowOutput(true);
jUnitTask.setFork(true);

FormatterElement formatterElement = new FormatterElement();
TypeAttribute typeAttribute = new TypeAttribute();
typeAttribute.setValue(“xml”);
formatterElement.setType(typeAttribute);
jUnitTask.addFormatter(formatterElement);

BatchTest batchtest = super.createBatchTest();
File results = new File(getProject().getProperty(“dir.test.results”));
batchtest.setTodir(results);
batchtest.addFileSet(createFileSet());

log(“runAntJUnitTests –> execute()”);
jUnitTask.execute();
}
catch(Throwable e)
{
e.printStackTrace();
throw new BuildException(e);
}
}
}
</pre>

I wanted to avoid having to set the classpath in code, so i took another aproach to the issue. I decided my Task would extend from the JUnitTask, this allows me to keep that majority of the task config in xml, and reuse the default handling of classpaths and jvm args.

<pre class="prettyprint">
public class JunitTestExistsTask extends JUnitTask {

/**
* Add the test files to a BatchTest and start the JUnit process.
* @throws BuildException
*/
private void runAntJUnitTests()
throws BuildException {
try {
BatchTest batchtest = super.createBatchTest();
File results = new File(getProject().getProperty(“dir.test.results”));

batchtest.setTodir(results);
batchtest.addFileSet(createFileSet());
super.execute();
} catch (Exception e) {
throw new BuildException(e);
}
}
}
</pre>

The xml for this command

<pre name="code" class="xml">

<taskdef
name="junitTestsExist"
classname="curam.uic.tools.policing.junit.JunitTestExistsTask"
classpathref="junit.target.cp"/>









</pre>

Categories:

Updated:

Leave a Comment