I am using System.IO.Abstractions to mock File.OpenRead()
. File.OpenRead()
returns a FileSystemStream
(as opposed to System.IO
's FileStream
).
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'
MemoryStream
s and other objects result in cannot convert from 'System.IO.MemoryStream' to 'System.IO.Abstraction.FileSystemStream'
I need to give the mocked method a FileSystemStream object to return, and I'm having trouble creating one.
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.