Running testng.xml programmatically from Ant

Standard

In this post I would like to share how I used ant programmatically to run and execute my tests contained inside my testng.xml file.The history behind this requirement is such that I created a custom swing application for running testng tests from GUI. Hence I had to run ant from a button click.

Lets dive in..

Make sure the build.xml has the target mentioned below in p.executeTarget("run"); , in this case which is run.

The testng.xml for this example looks like this


The java code for running the ant build file programatically.

public void RunTask(){

File buildFile = new File(srcdir+"//build.xml");
Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
DefaultLogger consoleLogger = new DefaultLogger();
consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out);
consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
p.addBuildListener(consoleLogger);

try {
p.fireBuildStarted();
p.init();
ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile);
p.executeTarget("run");
p.fireBuildFinished(null);

} catch (BuildException e1) {}
}

Make sure your compile target contains fork = "yes" else the compiler will struggle to locate the jdk from classpath.

<javac
debug="true"
destdir="${test.dest}"
srcdir="${test.src}"
target = "1.7"
classpath = "${test.classpath}"
includeantruntime ="false"
fork = "yes">

Hope this helps.

Advertisements