Search code examples
c++windowsunit-testingifstreamfile-handling

How to generate a file open failure for unit testing


For completeness, I'm using C++ in Visual Studio 2012 under Windows 7.

I have some basic file reading code:

Defined in class:

std::ifstream iniFileHandle;

Method in question:

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;
}

All this works fine but I'm having difficulty getting coverage with Google Unit Tests.

What i'm missing is a way to simulate/create a scenario where is_open() fails.

I've tried:

  • read only files
  • the 'exe' being currently run
  • a file opened in another application but they all open.

Is this error condition actually possible to occur? If so, how can I mimic the failure so I can test it?


Solution

  • As mentioned in the comments, trying to open a directory will cause is_open() to return false. The cases you tried all succeed because you open the file as read-only (std::ios::in, which is also the default for an ifstream).