Unittesting Methods Containing File System Calls

I have a method that I want unittest in which there are file system calls, and I am wondering how to do this. I looked at unit test code with a file system dependency , but it does not answer my question.

The method I'm 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 the file, because I am removing the Process method and not the Transform (..) method, and therefore the output.txt file does not exist. Therefore, the if check is not performed.

How should I do it right? Should I create some kind of wrapper around io-method files that I would also mock?

+4
source share
2 answers

Edit I answered before adding C # to the question (or I skipped it ...), so my answer is a bit java-esque, but the principles are the same ...


Your idea of ​​wrapping around an IO file is good. This is one such example, but something like this can 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 generic template to simplify validation:

  • During testing, you can use a mocking framework like NMock to mock the FileProvider implementation;

  • At runtime, you just plug in the real implementation.

+5
source

I think you should create two files: one with zero length and the other with some data in it. Then you must pass the test for each file. At the preparation stage, you should copy this file to the test directory, run the test and after it confirms whether there is a file.

0
source

All Articles