我正在尝试使用系统.IO.抽象 https://github.com/System-IO-Abstractions/System.IO.Abstractions项目与 System.IO.Abstraction.TestingHelpers 一起模拟FileStream
.
这是使用我要测试的文件流的代码:
private readonly IFileSystem _fileSystem;
public void ExtractImageAndSaveToDisk(IXLPicture xlPicture, string filePath)
{
using (MemoryStream ms = new MemoryStream())
{
xlPicture.ImageStream.CopyTo(ms);
using (FileStream fs = (FileStream)_fileSystem.FileStream.Create(filePath, FileMode.Create))
{
ms.CopyTo(fs);
fs.Flush();
fs.Close();
}
}
}
这就是我设置测试的方式:
[TestMethod]
public void CheckFileIsSavedToDisk()
{
// Arrange
var mockFileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ @"c:\Test\Images\", new MockDirectoryData() },
});
var xlPicture = GetXLPicture();
var filePath = @"c:\Test\Images\myimage.jpeg";
var sut = new CostSheetImageExtractor(mockFileSystem);
// Act
sut.ExtractImagesAndSaveToDisk(xlPicture, filePath);
}
运行我得到异常:
System.InvalidCastException: Unable to cast object of type 'System.IO.Abstractions.TestingHelpers.MockFileStream' to type 'System.IO.FileStream'.
on the using (FileStream fs = ...
line.
第一个想法是我需要改变FileStream fs
使用真实对象和模拟对象共享的接口,但据我所知,没有IFileStream
接口FileStream
and MockFileStream
分享,所以我猜我做的完全错误?
实际上有没有办法用 System.IO.Abstraction 测试这段代码?
This 现有答案 https://stackoverflow.com/a/44820425/1879019似乎表明这应该是可能的,我也尝试这样做,但得到了相同的结果。