c#中的模拟文件IO静态类

Dav*_* MZ 6 c# nunit unit-testing rhino-mocks

我是Unit Testing的新手,我需要在System.IO命名空间中模拟File静态类.我正在使用Rhinomock,实现这一目标的最佳方法是什么,

可以说我需要模拟File.Exists,File.Delete ......

Don*_*kby 7

你不能用Rhino mock模拟静态方法.有关详细信息,请参阅此问题.您可以创建一个外观类来包装您将使用的文件系统调用,然后创建它的模拟版本.


Cra*_*art 5

您应该创建一个名为 IFileService 的包装器服务,然后您可以创建一个使用静态数据的具体对象,以及一个具有用于测试的虚假功能的模拟 IFileService。让它这样你必须将 IFileService 传递给构造函数或任何类正在使用它的属性,这种方式正常操作需要你传入 IFileService。请记住,在单元测试中,您只测试那部分代码,而不是它调用的内容,例如 IFileService。

interface IFileService
{
    bool Exists(string fileName);
    void Delete(string fileName);
}

class FileService : IFileService
{
    public bool Exists(string fileName)
    {
        return File.Exists(fileName);
    }

    public void Delete(string fileName)
    {
        File.Delete(fileName);
    }
}

class MyRealCode
{
    private IFileService _fileService;
    public MyRealCode(IFileService fileService)
    {
        _fileService = fileService;
    }
    void DoStuff()
    {
        _fileService.Exists("myfile.txt");
    }
}
Run Code Online (Sandbox Code Playgroud)