Launching Ant from within Java code
Thursday, 10 January 2008 00:00

As you may have noticed from an earlier post, I've been using Canoo WebTest to help write automated testing scripts. But I also like using JUnit, along with the Eclipse plugin, to easily run tests and view the results. As such, I was hoping to be able to run my Canoo tests via JUnit.

Since Canoo is based on Ant, the first hurdle was figuring out how to launch an Ant project directly from Java code. The documentation for this was a little shaky, but I ended up figuring it out. I figured it would be best to demonstrate how this works via an example:

Project prj = new Project();
File f = ResourceReader.getResourceAsFile("build.xml");

prj.init();
ProjectHelper.configureProject(prj, f);

prj.executeTarget("target");

Pretty simple, once you are able to figure it out. Note that you may need to place the Ant jars onto your classpath (found in the /lib directory in your ant installation). In particular, it seems I needed ant.jar, ant-laucher.jar, and ant-trax.jar.

Once you have this running, it was relatively simple to get Canoo WebTest running as JUnit tests. I'll cover some additional details of how I set this up in a future post.