6

I have a native C++ unit test project in Visual Studio (2012).
In one of my tests I would like to read a file included in my unit test project. Is it possible? What properties of the file should I set and what path should I use?

I added a test.txt file to my project (and tried to set its Content property to true). And in a unit test I tried to open the file with a relative path like this:

std::ifstream file("text.txt");

But it does not work.

I guess the file should be copied to the place from where the unit test runs. Is there a simple solution for this?

3
  • use the full path such as "C:\\some_dir\\text.txt" Apr 8, 2013 at 8:58
  • 1
    Even if you want to use a relative path ultimately, use a full path first just to eliminate any other causes of the problem.
    – john
    Apr 8, 2013 at 8:59
  • 1
    With absolute paths I can open files without any problem. But that does not work for me, because I want these unit tests to work for every programmer on our team, so it is important to open the files contained by the project with relative paths. Apr 8, 2013 at 11:48

1 Answer 1

10

This can be accomplished by using the __FILE__ macro, in my case I did like this:

//Returns my solution's directory
#define TEST_CASE_DIRECTORY GetDirectoryName(__FILE__)

string GetDirectoryName(string path){
    const size_t last_slash_idx = path.rfind('\\');
    if (std::string::npos != last_slash_idx)
    {
        return path.substr(0, last_slash_idx + 1);
    }
    return "";
}

TEST_METHOD(MyTest)
{
    string filename = std::string(TEST_CASE_DIRECTORY) + "MyTestFile.txt";

    TestOutputForFile(filename);
}
2
  • 1
    Remember FILE is a compile time path. This is the full path at the time of compile. This is usually fine as the unit tests are usually run on the same environment/machine as they are built .
    – Menace
    Aug 28, 2015 at 15:27
  • 1
    Excellent solution. Thanks.
    – TinyRacoon
    Apr 26, 2018 at 10:16

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.