如何使用 Catch2 和 CMake 添加单独的测试文件?

W. *_*que 6 c++ unit-testing cmake catch2

文档中,他们只编译一个文件test.cpp,其中可能包含所有测试。我想将我的个人测试与包含的文件分开#define CATCH_CONFIG_MAIN,就像这样

如果我有一个test.cpp包含#define CATCH_CONFIG_MAIN一个单独的测试文件的文件simple_test.cpp,我已经设法以simple_test.cpp这种方式生成一个包含测试的可执行文件:

find_package(Catch2 REQUIRED)

add_executable(tests test.cpp simple_test.cpp)
target_link_libraries(tests Catch2::Catch2)

include(CTest)
include(Catch)
catch_discover_tests(tests)

Run Code Online (Sandbox Code Playgroud)

但是,这是生成可执行文件的可接受的方式吗?从不同的教程中,如果我有更多的测试,我应该能够创建一个测试源库并将它们链接到test.cpp生成可执行文件:

find_package(Catch2 REQUIRED)

add_library(test_sources simple_test.cpp another_test.cpp)
target_link_libraries(test_sources Catch2::Catch2)

add_executable(tests test.cpp)
target_link_libraries(tests test_sources)
target_link_libraries(tests Catch2::Catch2)

include(CTest)
include(Catch)
catch_discover_tests(tests)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试这个时,我收到了 CMake 警告Test executable ... contains no tests!

总而言之,我应该创建一个测试库吗?如果是这样,我怎样才能让它包含我的测试。否则,将新的 test.cpp 文件添加到函数中是否正确add_executable

Kam*_*Cuk 7

如何使用 Catch2 和 CMake 添加单独的测试文件?

使用对象库或使用--Wl,--whole-archive. 链接器在链接时从静态库中删除未引用的符号,因此测试不在最终的可执行文件中。

你能举一个 CMakeLists.txt 的例子吗?

喜欢

find_package(Catch2 REQUIRED)

add_library(test_sources OBJECT simple_test.cpp another_test.cpp)
target_link_libraries(test_sources Catch2::Catch2)

add_executable(tests test.cpp)
target_link_libraries(tests test_sources)
target_link_libraries(tests Catch2::Catch2)

include(CTest)
include(Catch)
catch_discover_tests(tests)
Run Code Online (Sandbox Code Playgroud)

或者

find_package(Catch2 REQUIRED)

add_library(test_sources simple_test.cpp another_test.cpp)
target_link_libraries(test_sources Catch2::Catch2)

add_executable(tests test.cpp)
target_link_libraries(tests -Wl,--whole-archive test_sources -Wl,--no-whole-archive)
target_link_libraries(tests Catch2::Catch2)

include(CTest)
include(Catch)
catch_discover_tests(tests)
Run Code Online (Sandbox Code Playgroud)