.netunit-testingnmock2

How to unit test class that reads xml file?


I need to write a unit tests for a class that reads a xml file and parses it's content. How can I Mock the file reading ? Because all the content of the tests should be against read file .

I use nmock2 with nUnit.

Thanks


Solution

  • As rwwilden suggests, life is a lot easier if you use a stream-based API instead of a filename-based one. Using mocking isn't terribly appropriate here, IMO; you're not doing "protocol testing" - you just want a data source.

    You can also provide an overload which is a simple utility method:

     public Result ParseXml(string file)
     {
         using (Stream stream = File.OpenRead(file))
         {
             return ParseXml(stream);
         }
     }
    

    You could then reasonably safely not test that method - it has no significant logic in it, after all.

    Now you could test the stream-based API by using a hard-coded string in your code, then calling Encoding.UTF8.GetBytes(xml) and building a MemoryStream around the resulting byte array... but I generally prefer to use separate data files in my test project. Set the content type to "embedded resource" and then use Assembly.GetManifestResourceStream to obtain a stream to the test file.

    If this is genuinely a normal XML file though, do you really want to do the parsing yourself? Is there any reason you don't want to leave that to the framework, and express your API either in terms of the DOM API, LINQ to XML, or XmlReader?