Creating JUnit tests out of Canoo WebTests
Wednesday, 16 January 2008 00:00

In an earlier post, I had given a few lines of code to show how you can launch an Ant task from within Java code. Using this trick, it is easy to run your Canoo WebTests as a JUnit test. I like running my Canoo tests from JUnit, as it makes it easier for me to run all my tests at once and easily see if they pass/fail. It is also integrated into Eclipse, meaning only a few mouse clicks to get everything started.

First, here is a core method to help run a given Canoo WebTest script. Note that this is similar to the configuration to run an Ant task from Java, with a couple Canoo-related additions:

protected void runCanooTest(String buildFile) throws Exception {
  URL url = Thread.currentThread().getContextClassLoader().getResource("canoo/build.xml");
  File f = new File(url.toURI());

  Project prj = new Project();
  prj.init();
  ProjectHelper.configureProject(prj, f);

  File resultsDir = new File("c:/canoo.results/");
  resultsDir.mkdirs();

  // optional: this check allows multiple canoo tests to
  // be run and append the results files together
  if (hasRunCanooTest) {
    prj.setProperty("wt.deleteReports.skip", "true");
  } else {
    hasRunCanooTest = true;
  }

  prj.setProperty("wt.headless", "true");
  prj.setProperty("wt.testInWork", buildFile);
  prj.setProperty("wt.config.resultpath", resultsDir.toString());
  prj.executeTarget("wt.full");
}

You should change "canoo/build.xml" to point to your Canoo build file (this would be the build.xml file that Canoo will auto-generate for you). You should also change "c:/canoo.results/" to point to a directory where you would like the results files saved.

Once you have this core method setup, you simply need to call runCanooTest(), passing in the name of the buildFile you would like to run. Note that the buildFile would be a XML file that you have written to run your Canoo test. The default target of this buildFile will be run. This allows you to break your Canoo tests into multiple build files and run them each within its own test case, so that you don't need to run your entire library at once.

That's all there is to it! If any errors occur while running your Canoo test, an Exception will be thrown, which causes the JUnit test to fail. Otherwise, the JUnit test will pass. In either case, you can browse through the Canoo results files to get additional details about the test run.