Nelz's Blog

Mah blogginess

XMLUnit and TestNG

Our entire testing system is based on TestNG, but one of our developers recently invoked XMLUnit to test some of the XML he was producing.

Now, XMLUnit is built to be used with JUnit (old JUnit… like 3.8.1 style JUnit…), which at first glance doesn’t seem to play well with TestNG test runners. (We were having some build timeouts and other mysterious behavior when trying to run these tests.)

To give you an idea, here is a snippet from the examples:

package net.nelz.test.xmlunit;
import org.custommonkey.xmlunit.XMLTestCase;
public class MyXMLTestCase extends XMLTestCase {
public MyXMLTestCase(String name) {
super(name);
}
public void testForEquality() throws Exception {
String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
String myTestXML = "<msg><localId>2376</localId></msg>";
assertXMLEqual("comparing test xml to control xml", myControlXML, myTestXML);
assertXMLNotEqual("test xml not similar to control xml", myControlXML, myTestXML);
}
}

If you look at that example, the only methods that seem to add any value are assertXMLEqual(…) and assertXMLNotEqual(…).

If you look at the source code for those methods, you’ll realize that they just delegate to parallel static methods in the class XMLAssert:

...
public void assertXMLEqual(String control, String test)
throws SAXException, IOException {
XMLAssert.assertXMLEqual(control, test);
}
...

What this all means is that XMLUnit already is TestNG friendly. Here’s what that snippet from XMLUnit’s example code would look like if it were rewritten to target TestNG.:

package net.nelz.test.xmlunit;
import org.custommonkey.xmlunit.XMLAssert;
import org.testng.annotations.Test;
public class MyXMLTestCase {
@Test
public void testForEquality() throws Exception {
String myControlXML = "<msg><uuid>0x00435A8C</uuid></msg>";
String myTestXML = "<msg><localId>2376</localId></msg>";
XMLAssert.assertXMLEqual("comparing test xml to control xml", myControlXML, myTestXML);
XMLAssert.assertXMLNotEqual("test xml not similar to control xml", myControlXML, myTestXML);
}
}