I need to be able to retrieve the project directory path of my unit testing in order to load some files required by the tests. I don't want to hard-code it in case the solution structure and absolute paths changes in the future.
Applies to: Visual Studio Visual Studio for Mac Visual Studio Code This topic lists the public members of the Microsoft::VisualStudio::CppUnitTestFramework namespace. Use these APIs to write C++ unit tests based on the Microsoft Native Unit Test Framework.
Right-click your solution and choose Add > New > Project. Click the Visual C++ category, and choose the Test sub-category. Select Native Unit Test Project, give the project a descriptive name, and then click OK. Visual Studio will create a new project containing unit tests, with all dependencies to the native test framework already set up.
The Microsoft Unit Testing Framework for C++ is included by default in the Desktop Development with C++ workload. Typically, you run your test code in its own project in the same solution as the code you want to test. To set up and configure a new test project, see Writing unit tests for C/C++.
You define and run tests inside one or more test projects. You create the projects in the same solution as the code you want to test. To add a new test project, right-click on the Solution node in Solution Explorer and choose Add > New Project. In the left pane, choose Visual C++ Test. Then, choose one of the project types from the center pane.
Ok, this is how I did it:
In my project Properties -> Configuration -> C/C++ -> Preprocessor I added this preprocessor definition UNITTESTPRJ="$(ProjectDir)."
Then in my cpp file I did:
#define STRINGIFY(x) #x
#define EXPAND(x) STRINGIFY(x)
string s = EXPAND(UNITTESTPRJ);
s.erase(0, 1); // erase the first quote
s.erase(s.size() - 2); // erase the last quote and the dot
string my_project_dir = s;
The stupid .
at the end was necessary to escape the trailing \"
in the project directory.
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