Mocking File.OpenWrite()

Mar 19, 2015 at 3:54 PM
I'm trying to write a unit test that writes to a file it opens with File.OpenWrite().

I'm wrapping File with SystemWrapper's IFileWrap interface. In production, I'm using SimpleInjector to inject an instance of SystemWrapper's FileWrap class, and that's working fine. But I'm trying to mock IFileWrap in my unit tests, using MOQ, and that's not working.

I'm new to SystemWrapper, and I'm doing my best to figure out how it is intended to be used. As far as I can tell, IFileWrap.OpenWrite() returns an IFileWrap instance, from which you can obtain the stream with FileStreamInstance.

So, in my class under test, I inject an IFileWrap in my constructor:
public class ClassUnderTest
    private readonly IFileWrap fileWrap;

    public ClassUnderTest(IFileWrap fileWrap)
        this.fileWrap = fileWrap;

And in my method under test, I get the stream from FileStreamInstance:
var fsWrap = this.fileWrap.OpenWrite(fullPath);
var ostream = fswrap.FileStreamInstance;
That works fine, in production, where fileWrap is instantiated with an instance of FileWrap. But in my tests, I'm trying to create a Mock for File.OpenWrite that returns a mocked FileStream:
var fileStreamMock = new Mock<IFileStreamWrap>();

var fileMock = new Mock<IFileWrap>();
fileMock.Setup(fm => fm.OpenWrite(It.IsAny<string>())).Returns(fileStreamMock.Object);

var classUnderTest = new ClassUnderTest(fileMock.Object);
And when I walk through the method under test, in the debugger, from my unit test, fsWrap.FileStreamInstance is null, when I'd expect it to be my mocked filestream.

Any ideas as to what I am doing wrong?