Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open a file from the project in a native C++ unit test (Visual Studio)?

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?

like image 247
Mark Vincze Avatar asked Apr 08 '13 08:04

Mark Vincze


People also ask

How do I open test project in Visual Studio?

Run tests in Test Explorer If Test Explorer is not visible, choose Test on the Visual Studio menu, choose Windows, and then choose Test Explorer (or press Ctrl + E, T). As you run, write, and rerun your tests, the Test Explorer displays the results in a default grouping of Project, Namespace, and Class.

How do I test C in Visual Studio?

Create a test project in Visual Studio 2019 Right-click on the Solution node in Solution Explorer. In the pop-up menu, choose Add > New Project. Set Language to C++ and type "test" into the search box.


1 Answers

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);
}
like image 113
Eduardo Wada Avatar answered Nov 15 '22 07:11

Eduardo Wada