Using JUnit extensions in TestNG

Just because a framework claims to be a JUnit extension doesn’t necessarily mean it can’t be used within TestNG. So long as the target framework:

  • isn’t a decorator based one, such as the hip JUnitPerf
  • has a composition enabling API, like XMLUnit

it can be easily incorporated into TestNG.

For example, XMLUnit can easily be used with TestNG- all that’s required is a configuration annotation on a setUp style method which will configure various copasetic parsers for XMLUnit.

/**
  * @testng.configuration beforeTestClass = "true"
  */
 protected void configure() throws Exception {
  XMLUnit.setControlParser(
       "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
  XMLUnit.setTestParser(
       "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
  XMLUnit.setSAXParserFactory(
       "org.apache.xerces.jaxp.SAXParserFactoryImpl");
  XMLUnit.setIgnoreWhitespace(true);
}

Notice how I’ve signified this fixture to be run once, rather than the establishment one-for-every-test-case JUnit standard.

Now I can test an application’s generated XML with abandon!

/**
  * @testng.test
  */
 public void assertToXML() throws Exception{
   BatchDependencyXMLReport report =
	new BatchDependencyXMLReport(new Date(9000000),
             this.getFilters());

   report.addTargetAndDependencies("com.vanward.test.MyTest",
       this.getDependencies());
   report.addTargetAndDependencies("com.xom.xml.Test",
       this.getDependencies());

   Diff diff = new Diff(new FileReader(
	new File("./test/conf/report-control.xml")),
	new StringReader(report.toXML()));

   Assert.assertTrue(diff.identical(),"XML was not identical");
}

XMLUnit isn’t the only JUnit extension that one can use within TestNG- DbUnit, JWebUnit, and JUnit-addons are just a few of the many available ones to choose from!

If the fear of not being able to use a JUnit extension is holding you back from giving TestNG a try, look closely on how the extension was designed for extensibility. Dig it?

Related odds and ends
 

One Response to “Using JUnit extensions in TestNG”

  1. on 29 Mar 2006 at 2:16 am t800t8

    Trackback: http://t800t8.blogspot.com/2006/03/using-junit-extensions-in-testng.html

Trackback this Post | Feed on comments to this Post

Leave a Reply