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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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 aMemoryStreamaround 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 useAssembly.GetManifestResourceStreamto 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?