如何为单元测试生成文件打开失败

How to generate a file open failure for unit testing

为了完整起见,我在 Visual Studio 2012 年 Windows 7.

下使用 C++

我有一些基本的文件读取代码:

在class中定义:

std::ifstream iniFileHandle;

有问题的方法:

FileLoader::FILE_STATUS FileLoader::loadFile(const std::string& fullpathandfilename)
{
    if (fullpathandfilename.empty())
    {
        iniFileStatus = FILE_NOT_SPECIFIED;
    }
    else // parameter has 'something'...
    {
        if (!doesFileExist(fullpathandfilename))
        {
            iniFileStatus = FILE_NOT_FOUND;
        }
        else // file found...
        {
            iniFileHandle.open(fullpathandfilename, std::ios::in);

            if (!iniFileHandle.is_open()) // something went wrong
            {
                iniFileStatus = FILE_CANNOT_LOAD; // <== HOW TO TEST?
            }
            else // file opened!
            {
                iniFileStatus = FILE_OPEN;
            }
        }
    }

    return iniFileStatus;
}

所有这些工作正常,但我很难覆盖 Google 单元测试。

我缺少的是 simulate/create is_open() 失败场景的方法。

我试过:

这种错误情况真的有可能发生吗?如果是这样,我如何模拟故障以便进行测试?

如评论中所述,尝试打开目录将导致 is_open() 到 return false。您尝试的所有案例都成功了,因为您以只读方式打开文件(std::ios::in,这也是 ifstream 的默认设置)。

I've tried:

a file opened in another application but they all open.

发生这种情况是因为文件以共享模式打开,允许其他人阅读。您需要以独占文件访问模式打开文件。要实现它,如果您使用 MSVS,您可以将第三个参数 int _Prot 传递给 ifstream, otherwise you could use CreateFile()

要模拟此问题,您可以打开 Windows 独占使用的文件,例如:

c:\pagefile.sys