Mocking a Using with a FileStream

You have to abstract File.Open() by an interface method then you would be able mocking call to it.

So

1) Create an interface:

public interface IFileDataSource
{
   FileStream Open(string path,
                   FileMode mode,
                   FileAccess access,
                   FileShare share);
}

2) Change LoadConnectionDetailsFromDisk() as following:

private Connection LoadConnectionDetailsFromDisk(string path, IFileDataSource fileSource)
{     
   using (FileStream fs = fileSource.Open(bodyFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
   {
      return this.serverConfiguration.LoadConfiguration(fs, flowProcess);
   }

   //more logic
}

3) In a test mock the interface and inject a mock

// create a mock instance
var sourceMock = MockRepository.GenerateMock<IFileDataSource>();

// setup expectation
sourceMock.Expect(m => m.Open("path", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
         .CallBack(
 delegate (string path, FileMode mode, FileAccess access, FileShare share)
 {
      // handle a call

     return true;
 }).Repeat.Any();

// TODO: depends on how you are triggering LoadConnectionDetailsFromDisk method call
// inject a mock

Considering that LoadConnectionDetailsFromDisk() you can not inject mock directly to this method call froma test so please show how this method is invoked.


The System.IO.Abstractions project and NuGet package also allow for mocking of FileStreams.

To use that you have to slightly change how you get the FileStream in the first place, to something like:

private readonly IFileSystem _fileSystem; // this is from the third-party System.IO.Abstractions package

// This is assuming dependency injection to insert the mock file system during testing, 
// or the real one in production
public YourConstructor(IFileSystem fileSystem)
{
   _fileSystem = fileSystem;
}

private Connection LoadConnectionDetailsFromDisk(string bodyFile)
{     
   using (Stream fs = _fileSystem.FileStream.Create(bodyFile, FileMode.Open))
   {
       return this.serverConfiguration.LoadConfiguration(fs, flowProcess);
   }

   //more logic
}

Tags:

C#

Rhino Mocks