Unit test assertions against Xml Schemas

Some methods that I have needed to test against recently return xml usually as a string. I initially thought that it would be tricky to test against XML but actually most of the tools that you need are available in Visual Studio.

In my case as I knew that the XML should be of a certain format and knew the constraints of each element and attribute, I was able to first create a XML schema to assert against which is known as a XSD (XML Schema Document).

To validate your xml against a schema the xml must contain a namespace correlating to your xsd. As I didn't want to change the actual xml produced by the method in production, I just had to inject the namespace for testing purposes.

A slight drawback is that most xml passed over the wire, uses attributes extensively and not too many elements. This is valid as it means you can have smaller packets of data that essentially represent the same thing. However when you want to use an xsd to assert against this data there are limitations to the constraints that you can place against an attribute centric xml document:

So if I want to use the more granular set of constraints to validate the xml its worth running an xslt transform on the xml attributes to convert them to elements then validate against an element centric schema with tighter defined facets.

Testing process then becomes: