Catch lib (unit testing) and CTest (CMake) integra

2019-03-09 03:24发布

问题:

I'm looking for successful example of Catch CatchLib integration with CMake test (Ctest) . as I understand this is additional cmake script which has to parse application ouput? Did someone already written this? probably shared this?

==================================================

update (solution has been found) :

I've committed cmake script to CatchLib , for the integration Catch with CTest. this is a simplified version of Fraser99's cmake script here

回答1:

Integrating Catch with CMake is rather simple, as it's a header-only library.

Here's a quick rundown of what you have to do:

You can either assume that the Catch sources are already installed on the build machine or use ExternalProject for fetching them as part of the build process.

In either case, you will end up with the Catch header files in some known directory on your build machine. I would recommend creating an interface target for making this information known to your test executables:

add_library(Catch INTERFACE)
target_include_directories(Catch INTERFACE ${YOUR_CATCH_INCLUDE_DIR})

That way, you can simply specify Catch as a dependency to target_link_libraries:

add_executable(my_test ${MY_TEST_SOURCES})
target_link_libraries(my_test Catch)

As usual with CMake, add_test takes care of introducing the tests to CTest:

enable_testing()
add_test(NAME MyAwesomeTest COMMAND my_test)

And that's it already. Run make test on the built project to run your tests.

I have a project on Github that does this if you need to see a complete working example.



回答2:

EDIT2: these days Catch2 installs its own cmake module so, after install, it can be used in another cmake project with

include(GNUInstallDirs)
find_package(Catch2 REQUIRED)

You can make your CMake project depend on Catch using find_package. That way you don't include Catch yourself and can update it independently. The process is explained in this recipe, except in this case you don't need to deal with libraries, since Catch is header only.

CMakeLists.txt (assuming you have your FindCatch.cmake in place [see below] and your tests in my_tests.cpp):

list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/Modules/")
find_package(Catch REQUIRED)

include_directories(${CATCH_INCLUDE_DIRS})

add_executable(my_tests my_tests.cpp)
add_test(NAME MyTests COMMAND my_tests)

An example my_tests.cpp:

#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main()
#include "catch/catch.hpp"

#include "stuff_to_test.h"

TEST_CASE("A test case")
{
  ...
}

...

You will need to add a FindCatch.cmake module to your project, under cmake/Modules. Search the web for FindCatch.cmake.

Finally, you can build and run the tests with make test.


EDIT: Alternatively, you can have cmake download Catch from git during the build, following these instructions from Catch's github. This requires a dependency on git though.