System.IO.Abstraction can't find IStreamWriter

社会主义新天地 提交于 2020-01-05 05:26:05

问题


I am trying to unit test a method that calls StreamWriter, I am trying to use System.IO.Abstraction in order to mock StreamWriter however i can't find the interface on the last Nuget looked into the source code as well but have no idea what is the replacement for this, other stuff like FileInfo is working as expected.

Thanks,


回答1:


I was also looking for how to mock a FileStream via System.IO.Abstractions and couldn't see it initially. It's Hanging off the FileInfo Object. It results in slightly clunky code and required a cast. My Original Code:

FileStream fileStreamBack = null;
using (fileStreamBack = new FileStream(fileFrom, FileMode.Open, FileAccess.Read))
using (var fileStreamf = new FileStream(fileTo, FileMode.Create, FileAccess.Write))
{
                fileStreamBack.CopyTo(fileStreamf);             // Use the .Net 
                fileStreamBack.Flush(); // Making sure
                fileStreamBack.Close(); // Making sure
}

Now Replaced with

FileStream fileStreamBack = null;
using (fileStreamBack = (FileStream)_fileSystem.FileInfo.FromFileName(fileFrom).Open(FileMode.Open, FileAccess.Read))
using (var fileStreamf = (FileStream)_fileSystem.FileInfo.FromFileName(fileTo).Open(FileMode.Create, FileAccess.Write))
        {
            fileStreamBack.CopyTo(fileStreamf);             // Use the .Net 
            fileStreamBack.Flush(); // Making sure
            fileStreamBack.Close(); // Making sure
        }

There is also a MockFileStream object in the System.IO.Abstractions.TestingHelpers (for our convenience!)




回答2:


Taking @BarryMcDermid's answer and altering it slightly you can do something along the lines of:

using (Stream fs = _fileSystem.FileStream.Create(filePath, FileMode.Create))
{
    ms.CopyTo(fs);
    fs.Flush();
    fs.Close(); 
}

By declaring the 'FileStream' as a Stream instead of a FileStream you'll then be able to use System.IO.Abstraction.TestingHelpers to test this code without getting exceptions.

There's a more fully worked example of that in my question here.



来源:https://stackoverflow.com/questions/25844856/system-io-abstraction-cant-find-istreamwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!