Wednesday, September 26, 2007

The difficulty with testing XML is that there are several ways of writing the same thing and each of them is valid.

For example, the two XML snippets below are equivalent:

Indented XML using an explicit end tag to close empty elements:

<Person>
  <FirstName></FirstName>
  <LastName>Smith</LastName>
</Person>

Non-indented XML with no additional whitespace and abbreviated empty tag:

<Person><FirstName/><LastName>Smith</LastName></Person>

XML Unit (http://xmlunit.sourceforge.net/) allows you to test if two pieces of XML are equivalent:

[Test]
public void TestEquivalentXmlFragmentsAreEqual( )
{
   string actualXml = "<Person><FirstName/><LastName>Smith</LastName></Person>";
   string expectedXml = "<Person>\r\n <FirstName></FirstName>\r\n <LastName>Smith</LastName></Person>";

   XmlDiff xmlDifference = new XmlDiff(new StringReader(actualXml), new StringReader(expectedXml));
   DiffResult result = xmlDifference.Compare();

   Assert.IsTrue(result.Equal);
}

The only negative thing to say about XmlUnit is the information it provides when the XML is not equivalent doesn’t make it particular easy to understand why the two pieces of XML differ.

Wednesday, September 26, 2007 7:23:09 AM (GMT Daylight Time, UTC+01:00)