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...
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With