【问题标题】:Corrections to CMakeList.txt file for Google testing?更正 CMakeList.txt 文件以进行 Google 测试?
【发布时间】:2020-05-31 17:08:15
【问题描述】:

我一直在查看 CMake 示例,以帮助我使用其测试文件夹构建我的项目。主要问题是我必须将我的测试文件夹中的所有 test/.cpp* 文件包含到 tests/main.cpp 中才能运行测试。我想我应该在我的 test/CMakeLists.txt 中使用 add_test 调用来包含我的测试。以下是我当前的 CMakeLists 文件:

enable_testing()

find_package(需要 GTest)

add_executable(test main.cpp)

target_include_directories(测试 PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../include)

target_link_libraries(测试 MainProjectLib ${GTEST_LIBRARIES})

而我的 main.cpp 如下。

#include "file_in_test1.cpp"
#include "file_in_test2.cpp"
#include <gtest/gtest.h>

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

我阅读了一些使用标准 CTest 库进行单元测试的示例,但我使用的是 Google Test。 我希望能够运行 cmakemake./test 来运行 file_in_test1.cppfile_in_test2.cpp 中的所有测试方法em> 无需直接将这些文件导入 test/main.cpp 我必须对 CMakeLists.txt 进行哪些添加?

【问题讨论】:

    标签: c++ cmake include googletest


    【解决方案1】:

    您可以在最后添加的一行是:

    gtest_discover_tests(test)
    

    这是自 cmake 版本 3.10 以来 gtest_add_tests 的替代品,然后在您构建完所有内容后,您可以运行 ctest,它会为您提供刚刚运行的测试的一个很好的总结。您可以阅读有关此选项的更多信息here

    另外,请注意,最好为您拥有的每个测试制作单独的测试文件,而不是在主测试文件中包含 .cpp 文件。

    我通常做的是定义一个允许测试的选项和一个创建我需要的测试的函数(见下文):

    option(build_all_tests "Build all unit tests in the test directory." OFF)
    
    if (build_all_tests)
        include(CTest)
        include(GoogleTest)
    
        enable_testing()
    
        ## Function to create a new test based off the pre-defined naming template ##
        function(new_test testname interiorDirectory)
            add_executable(${testname} ${interiorDirectory}/${testname}.cpp)
    
            target_link_libraries(${testname} ${GTEST_LIBRARIES})
    
            gtest_discover_tests(${testname}
                            WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${interiorDirectory})
        endfunction(new_test)
    
        ## Locate GTest ##
        find_package(GTest REQUIRED)
        include_directories(${GTEST_INCLUDE_DIRS})
    
        ## Create all tests ##
        new_test(test1 test/test1)
        new_test(test2 test/test2)
        ...
    endif()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-29
      • 2019-07-22
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多