0

In a method I would usually do something like this:

string[] lines = File.ReadAllLines(filename);

To test, I'd like to be able to mock out the file system, and I have heard positive comments about SystemWrapper, so I'd like to use this library.

As I understand, using SystemWrapper requires that I do interface based calling. That's fine. So my above line of code becomes:

string[] lines = new FileWrap().ReadAllLines(filename);

Now, my test method looks like this: (I am using Microsoft.VisualStudio.TestTools.UnitTesting in conjunction with Rhino Mock)

[TestMethod()]
public void Test_this_method()
{
    IFileWrap fileWrapRepository = MockRepository.GenerateMock<IFileWrap>();
    fileWrapRepository.expect(x => x.ReadAllLines("abc.txt").Return(new string[] {"Line 1", "Line 2", "Line 3"});

    MethodThatReadsLines();
}

This example is adapted from an example on SystemWrapper's Getting Started page.

However, when I do this, the method is not calling my mocked method, it is calling File.ReadAllLines, which is not what I am expecting.

What is the correct way to mock File.ReadAllLines?

Michael Plautz
  • 3,578
  • 4
  • 27
  • 40

1 Answers1

3

Moq's are test doubles, for the mock to be invoked, you have to actually invoke the method on the mock, not on some other object.

Instead of doing this in your code:

string[] lines = new FileWrap().ReadAllLines(filename);

You need to do something like this:

public void MethodThatReadsLines(IFileWrap fileReader) {
    string[] lines = fileReader.ReadAllLines(filename);
}

That way you can inject the mock object from you test and it is used by your production code, rather than the newly created instance that you're currently using:

[TestMethod()]
public void Test_this_method()
{
    IFileWrap fileWrapRepository = MockRepository.GenerateMock<IFileWrap>();
    fileWrapRepository.expect(x => x.ReadAllLines("abc.txt").Return(new string[] {"Line 1", 
                                                                      "Line 2", "Line 3"});

    MethodThatReadsLines(fileWrapRepository.Object);
}
forsvarir
  • 10,749
  • 6
  • 46
  • 77