11.2 Testing XML Files

11.2.1 Problem

You want to write unit tests for XML files.

11.2.2 Solution

Use XMLUnit.

11.2.3 Discussion

Suppose you have a Java class that generates an XML document and you want to write unit tests to ensure the XML data is correct. Your first inclination might be to compare the XML to a string. If the text is equal, you know the XML is correct. While this works, it is highly fragile and fails in cases where ignorable whitespace is the only difference between two XML documents. Consider this unit test:

public void testPersonXml(  ) {
    String xml = new Person("Tanner", "Burke").toXml(  );
    assertEquals("<person><name>Tanner Burke</name></person>", xml);

This test only works if the XML is formatted exactly as you expect. Unfortunately, the following XML contains the same data, but it causes the test to fail:

  <name>Tanner Burke</name>

Example 11-1 shows how to use XMLUnit to test your XML without worrying about whitespace differences.

Example 11-1. Simple XMLUnit test
public class TestPersonXml extends XMLTestCase {


    public void testPersonXml(  ) {
        String xml = new Person("Tanner", "Burke").toXml(  );

        assertXMLEquals("<person><name>Tanner Burke</name></person>", xml);

XMLUnit also supports the following types of XML tests:

  • Validating against a DTD

  • Transforming via XSLT and checking the results

  • Evaluating XPath expressions and checking the results

  • Treating badly formed HTML as XML and running tests

  • Using the DOM API to traverse and test XML documents

11.2.4 See Also

XMLUnit is available at http://xmlunit.sourceforge.net.