Unit-testing – How to test a parser for a bespoke XML schema

parsingunit testing

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?

Best Answer

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.

Related Topic