Mock File.Exists Method in Unit Test (C #)

Possible duplicate:
.NET File System Wrapper Library

I would like to write a test where the contents of the file are loaded. In the example, the class that is used to load the content,

FileClass 

and method

 GetContentFromFile(string path). 

Is there a way to mock

 File.exists(string path) 

in this example with moq? A.

Example:

I have a class with this method:

 public class FileClass { public string GetContentFromFile(string path) { if (File.exists(path)) { //Do some more logic in here... } } } 
+7
source share
1 answer

Since the Exists method is a static method in the File class, you cannot mock it (see the note below). The easiest way to get around this is to write a thin shell 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 structures, for example. Moq, Rhino Mocks, etc., None.

+5
source

All Articles