Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock File.Exists method in Unit Test (C#) [duplicate]

Possible Duplicate:
.NET file system wrapper library

I would like to write a test where the content of a file get's loaded. In the example the class which is used to load the content is

FileClass

and the method

GetContentFromFile(string path).

Is there any way to mock the

File.exists(string path)

method in the given example with moq?

Example:

I have a class with a method like that:

public class FileClass 
{
   public string GetContentFromFile(string path)
   {
       if (File.exists(path))
       {
           //Do some more logic in here...
       }
   }
}
like image 447
Dirk von Grünigen Avatar asked Jul 31 '11 23:07

Dirk von Grünigen


1 Answers

Since the Exists method is a static method on the File class, you can't mock it (see note at bottom). The simplest way to work around this is to write a thin wrapper around the File class. This class should implement an interface that can be injected into your class.

public interface IFileWrapper {
    bool Exists(string path);
}

public class FileWrapper : IFileWrapper {
    public bool Exists(string path) {
        return File.Exists(path);
    }
}

Then in your class:

public class FileClass {
   private readonly IFileWrapper wrapper;

   public FileClass(IFileWrapper wrapper) {
       this.wrapper = wrapper;
   }

   public string GetContentFromFile(string path){
       if (wrapper.Exists(path)) {
           //Do some more logic in here...
       }
   }
}

NOTE: TypeMock allows you to mock static methods. Other popular frameworks, e.g. Moq, Rhino Mocks, etc, don't.

like image 77
csano Avatar answered Sep 27 '22 19:09

csano