通过相对路径c ++ cmake guest查找单元测试的外部测试文件

Tea*_*cum 11 c++ unit-testing cmake googletest

访问外部测试文件以进行c ++项目单元测试的正确方法是什么?我正在使用CMake和Gtest.

这是目录结构的示例.

Project
   -src
       -test (unit tests here)
   -test-data (data file here)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Dar*_*nas 8

我更喜欢找到与我的可执行测试相关的测试数据.为此,我通常在一些中定义一个辅助方法TestHelpers.h,然后传递我想要解决的文件的相对路径.

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!");
}
Run Code Online (Sandbox Code Playgroud)

要使用它,我去:

std::string foofullPath = resolvePath("test/data/foo.txt");
Run Code Online (Sandbox Code Playgroud)

只要我的执行目录从项目根目录的后代运行,这就给了我测试文件的完整路径.


小智 7

将文件名传递给 gtest 参数:

add_executable(foo ...)
enable_testing()
add_test(FooTest foo "${CMAKE_CURRENT_LIST_DIR}/data/input.file")
Run Code Online (Sandbox Code Playgroud)

获取gtest解析输入后的参数:

int main(int argc, char** argv) {
  ::testing::InitGoogleTest(&argc, argv);
  assert(argc == 2); // gtest leaved unparsed arguments for you
Run Code Online (Sandbox Code Playgroud)

并将其保存到某个全局*:

  file_name = argv[1];
  return RUN_ALL_TESTS();
Run Code Online (Sandbox Code Playgroud)

* 通常污染全局命名空间并不是一个好主意,但我认为这对于测试应用程序来说很好

有关的


Jua*_*eni 5

在您的 CMakefile 中,添加您的测试并使用您的数据路径设置一些环境变量。

add_test(mytests ${PROJECT_BINARY_DIR}/unittests)
set_tests_properties(mytests PROPERTIES 
                     ENVIRONMENT
                     DATADIR=${CMAKE_CURRENT_SOURCE_DIR}/tests/testvectors)
Run Code Online (Sandbox Code Playgroud)

您以后可以DATADIR在任何测试中从环境中检索。

您的另一个选择是定义不同的工作目录

set_tests_properties(mytests PROPERTIES
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/tests)
Run Code Online (Sandbox Code Playgroud)

在我看来,这是侵入性较小且更简单的方法。