views:

144

answers:

2

I have a method I want to unittest that has filesystem calls in it and am wondering how to go about it. I have looked at http://stackoverflow.com/questions/129036/unit-testing-code-with-a-file-system-dependency but it does not answer my question.

The method I am testing looks something like this (c#)

public void Process(string input)
{
    string outputFile = "output.txt";
    this.Transform(input, Resources.XsltFile, outputFile);
    if ((new FileInfo(outputFile)).Length == 0)
    {
        File.Delete(outputFile);
    }
}

I am mocking the Transform(..) method to not output anything to a file as I am unittesting the Process method and not the Transform(..) method and therefore no output.txt file exists. Therefore the if check fails.

How should I do this properly? Should I create some sort of wrapper around the file io methods that i would mock out as well?

A: 

I think you should create two files: one with zero length, and other with some data in it. Then, you should have a test for each file. In the preparation phase, you should copy the given file to a test dir, run the test, and after it asserts if the file is there.

Alexandre
+5  A: 

Edit I answered before you added C# to the question (or I missed it...) so my answer is a little java-esque, but the principles are the same...


Your thought about a wrapper around file IO is a good one. This is one such example, but anything similar could do:

interface FileProvider {
    public Reader getContentReader(String file);
        // notice use of the Reader interface
        //   - real-life returns a FileReader;
        //   - testing mock returns a StringReader;


    public FileInfo getFileInfo(String path);
        // easy to mock out...
}

class Processor {

    private FileProvider fileProvider;

    public void setFileProvider(FileProvider provider) { 
        this.provider = provider; 
    }

    public void process(String input) {
        // use this.fileProvider for all filesystem operations...
    }
}

This is an example of dependency injection - a common pattern for making things easily testable:

  • At testing time you can use a mocking framework like NMock to mock out a testing FileProvider implementation;

  • At runtime you just plug in the real implementation.

Dan Vinton