Mock File IO static class in c#

2019-06-18 05:14发布

I am new to Unit Testing, and I need to mock the File static class in System.IO namespace. I am using Rhinomock, what is the best way to accomplish this,

Lets say I need to mock the File.Exists,File.Delete ...

7条回答
祖国的老花朵
2楼-- · 2019-06-18 06:14

You should create a wrapper service called IFileService, then you can create a concrete that uses the statics for use in your app, and a mock IFileService that will have fake functionality for testing. Make it so you have to pass IFileService into the constructor or a property for what ever class is using it, this way normal operation requires you pass in the IFileService. Remember in Unit Testing you are testing just that part of code not the things its calling to like 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");
    }
}
查看更多
登录 后发表回答