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

How do you add separate test files with Catch2 and CMake?

documentation, they only compile a single file test.cpp which presumably contains all the tests. I want to separate my individual tests from the file that contains #define CATCH_CONFIG_MAIN, like so.

如果我有一个包含 #define CATCH_CONFIG_MAIN 的文件 test.cpp 和一个单独的测试文件 simple_test.cpp,我已经设法生成了一个包含 [=16= 中的测试的可执行文件] 这样:

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)

但是,这是生成可执行文件的可接受方式吗?从不同的教程中,如果我有更多测试,我应该能够制作一个测试源库并将它们 link 到 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)

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

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

How do you add separate test files with Catch2 and CMake?

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

Could you give an example 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)

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)