基本上,情况就是这样。我有以下内容:
public IService Service { get; set; } //Set to MyMockedService class.
public Boolean DoFoo()
{
//possible other ways of returning true/false...
Boolean success = true;
//Get FileInfo[] items
foreach (var item in items)
DoOtherFoo(item);
}
public Boolean DoOtherFoo(FileInfo fileInfo)
{
String filepath = //manipulate fileInfo.FullName;
Byte[] file = Service.GetFile(filepath)
try
{
WriteBinaryFile(filepath, file); //How can I force file writing to throw an exception
}
catch (Exception)
{
return false;
}
}
基本上,在测试 DoFoo() 时,我有很多可以返回真/假的路径。除了最后一个之外,我已经对所有这些都进行了单元测试......它尝试写入文件,如果由于某种原因甚至无法写入其中一个文件,它就会失败并返回错误。起初,我想如果我尝试设置一个错误的文件名,例如“bad*file”,它会在 WriteFile 中引发异常,但我什至没有做到这一点,因为我无法使用非法字符创建 FileInfo 对象。所以我正在寻找另一种方法来制作它,这样就不可能写入文件,这样我就可以取回一个错误。