You want to write unit tests for XML files.
Use XMLUnit.
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:
<person> <name>Tanner Burke</name> </person>
Example 11-1 shows how to use XMLUnit to test your XML without worrying about whitespace differences.
public class TestPersonXml extends XMLTestCase {
...
public void testPersonXml( ) {
String xml = new Person("Tanner", "Burke").toXml( );
setIgnoreWhitespace(true);
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
XMLUnit is available at http://xmlunit.sourceforge.net.