我该如何对这类功能进行单元测试?当然我无法创建真正的文件,我无法对Example类和Func进行任何更改以使其更容易测试.
正如我发现的那样,Exists使用流行的免费框架(如moq)来模拟静态是不可能的.我找到了一些模拟文件系统的框架,如System.IO.Abstractions(https://github.com/tathamoddie/System.IO.Abstractions),但在我发现的所有样本中,方法(如此处CreateDirectory等Exists)都是从模拟中调用的对象,我不知道如何使它适应这种方法(如果可能的话).
public class Example
{
public int Func()
{
if(System.IO.File.Exists("some hard-coded path"))
{
return 1;
}
else
{
return 2
}
}
}
Run Code Online (Sandbox Code Playgroud)