Search code examples
c#.netunit-testingfilemocking

How do I create a FileSystemStream?


Background

I am using System.IO.Abstractions to mock File.OpenRead(). File.OpenRead() returns a FileSystemStream (as opposed to System.IO's FileStream).


Problem

I need to give the mocked method a FileSystemStream object to return, and I'm having trouble creating one. The below attempt produces an error.

Unit-test code:

var stream = new MemoryStream();
// Mock System.IO.Abstractions's FileSystem
var mockFS = new Mock<FileSystem>();
mockFS.Setup(x => x.File.OpenRead(dropFolderPath)).Returns(stream);

Error:

cannot convert from 'System.IO.MemoryStream' to 'System.IO.Abstraction.FileSystemStream'

Things I've tried

  • System.IO.Abstractions's README.md doesn't document this.
  • Various iterations of casting MemoryStreams and other objects result in cannot convert from 'System.IO.MemoryStream' to 'System.IO.Abstraction.FileSystemStream'

Solution

  • I need to give the mocked method a FileSystemStream object to return, and I'm having trouble creating one.

    Solution

    What worked was using System.IO.Abstraction's FileSystem to create the FileSystemStream object. Then I had an object I could return from my File.OpenRead() mock.

    var fileSystem = new System.IO.Abstractions.FileSystem();
    // Mock System.IO.Abstractions's FileSystem
    var mockFS = new Mock<FileSystem>();
    var stream = fileSystem.File.Create("my file path.txt");
    mockFS.Setup(x => x.File.OpenRead("my file path.txt")).Returns(stream);
    

    Note: @ProgrammingLlama's answer is also useful, though it requires an extra NuGet package.