I'm parsing a bespoke XML format into an object graph using .NET 4.0. My parser is using the System.XML namespace internally, I'm then interrogating the relevant properties of XmlNodes to create my object graph.

I've got a first cut of the parser working on a basic input file and I want to put some unit tests around this before I progress on to more complex input files.

Is there a pattern for how to test a parser such as this?

When I started looking at this, my first move was to new up and XmlDocument, XmlNamespaceManager and create an XmlElement. But it occurs to me that this is quite lengthy and prone to human error. My parser is quite recursive as you can imagine and this might lead to testing the full system rather than the individual units (methods) of the system. So a second question might be What refactoring might make a recursive parser more testable?

1 Answer 1


Create a separate test project, add a reference to your parser project, write your test class, and add your test document as an embedded resource (under "Build Actions"). In your test class, use Assembly.GetExecutingAssembly().GetManifestResourceStream('test-data.xml') to get your test data as a stream. You should be able to feed that stream to your parser and run your tests.

  • This seems more brute force than I was envisaging. It's not so much a unit test as a system test; e.g. "Does the parser parse the whole document", rather than testing each method parses an XML fragment as expected.
    – Greg B
    Mar 5, 2012 at 15:12
  • Playing around some more, the big overhead is creating the test data so I'm going to go with embedding XML documents in the assembly, but I'm still curious about testing individual methods of the parser.
    – Greg B
    Mar 5, 2012 at 15:50
  • You can add multiple test files, with varying levels of complexity. You can also hard-code snippets of XML if you want to test individual functions. If you're not writing an XML parser per se, but instead your XML parsing is interleaved with other parts of your project, it may be difficult to test individual methods effectively.
    – TMN
    Mar 5, 2012 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.