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?
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With