[ Team LiB ] |
11.2 Testing XML Files11.2.1 ProblemYou want to write unit tests for XML files. 11.2.2 SolutionUse XMLUnit. 11.2.3 DiscussionSuppose 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. Example 11-1. Simple XMLUnit testpublic 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:
11.2.4 See AlsoXMLUnit is available at http://xmlunit.sourceforge.net. |
[ Team LiB ] |