问题
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