Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mock object in a static method

If I have something like this:

static class ManifestGenerator
{
    public static void GenerateManifestFile(){
    var doc = new XDocument();
    ...
    ... xml stuff added to doc
    ...
    doc.Save(manifestFilePath)
}

Now can you please tell me how can I create a unit test that will ensure that the method generates correct xml? How can I mock XDocument (I am using Moq), without adding additional parameters to the method call

like image 729
iLemming Avatar asked Apr 19 '12 19:04

iLemming


1 Answers

Don't try to mock XDocument. That's not the problem here - it's the access to the file system which is annoying. You could pass in a Stream to write the manifest to instead:

public static void GenerateManifestFile(Stream output) {
  var doc = new XDocument();
  ...
  ... xml stuff added to doc
  ...
  doc.Save(output);
}

Then you can test that with a MemoryStream, but use a FileStream to the manifest path in reality. You might even make this method internal (using [InternalsVisibleTo] so you can still access it from tests) and a public parameterless overload along the lines of:

using (Stream output = File.OpenWrite(manifestFilePath))
{
    GenerateManifestFile(output);
}

You then don't test that code, but you can test all your real logic.

like image 106
Jon Skeet Avatar answered Oct 06 '22 23:10

Jon Skeet