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
MemoryStream
s and other objects result incannot convert from 'System.IO.MemoryStream' to 'System.IO.Abstraction.FileSystemStream'
2
You can use MockFileSystem
from the System.IO.Abstractions.TestingHelpers
NuGet package for this:
var fileData = new MockFileData("hello");
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>()
{
["my file path.txt"] = fileData
});
mockFS.Setup(x => x.File.OpenRead("my file path.txt")).Returns(fileSystem.File.OpenRead("my file path.txt"));
See the Test helpers section on the GitHub repo page.
1
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.
0