What would be the proper way to access an external test file for the unit test of a c++ project? I am using CMake and Gtest.
This is a sample of the directory structure.
Project
-src
-test (unit tests here)
-test-data (data file here)
Thanks!
I prefer to find my test data relative to my executable test. To do so, I usually define a helper method in some TestHelpers.h
and then pass the relative path of the file I'm looking to resolve.
inline std::string resolvePath(const std::string &relPath)
{
namespace fs = std::tr2::sys;
// or namespace fs = boost::filesystem;
auto baseDir = fs::current_path();
while (baseDir.has_parent_path())
{
auto combinePath = baseDir / relPath;
if (fs::exists(combinePath))
{
return combinePath.string();
}
baseDir = baseDir.parent_path();
}
throw std::runtime_error("File not found!");
}
To use it, I go:
std::string foofullPath = resolvePath("test/data/foo.txt");
and that gives me a full path of the test file as long as my executing directory runs from on a descendant of the project's root directory.