Friday, 13 July 2007

Extending ANT JUnitTask

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.


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);
}
}
}


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.


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);
}
}
}


The xml for this command



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









No comments: