开发者

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

This question already has answers here: Closed 11 years ago.

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 th开发者_如何学编程e

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...
       }
   }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜