Catch lib(单元测试)和 CTest(CMake)集成

我正在寻找 Catch CatchLib 与 CMake 测试 (Ctest) 集成的成功示例.据我了解,这是必须解析应用程序输出的附加 cmake 脚本?有人已经写过这个了吗?大概分享了这个?

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) :

我已将 cmake 脚本 提交给 CatchLib ,用于与 CTest 的集成 Catch.这是 Fraser99 的 cmake 脚本的简化版本 rel="rrep">

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

推荐答案

将 Catch 与 CMake 集成相当简单,因为它是一个只有头文件的库.

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:

您可以假设 Catch 源已经安装在构建机器上或使用 ExternalProject 用于在构建过程中获取它们.

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.

无论哪种情况,您最终都会在构建机器上的某个已知目录中获得 Catch 头文件.我建议创建一个接口目标,让您的测试可执行文件知道这些信息:

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})

那样,您可以简单地将 Catch 指定为对 target_link_libraries 的依赖:

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 PUBLIC Catch)

与 CMake 一样,add_test 负责将测试引入 CTest:

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

enable_testing()
add_test(NAME MyAwesomeTest COMMAND my_test)

就这样了.在构建的项目上运行 make test 以运行您的测试.

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

我有一个 Github 上的项目需要查看完整的工作示例.

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

更新 Catch 的更新版本:如果您已经升级到 Catch2,那么它带有自己的包配置文件,因此您只需调用 find_package.这提供了整体上更流畅的 CMake 集成不必开始定义您自己的接口目标.虽然上面的方法即使使用 Catch2 仍然有效,但如果您的 Catch 版本已经支持它,我建议使用 find_package.

Update for newer versions of Catch: If you've already upgraded to Catch2, that one comes with its own package config file so you can just integrate it calling find_package. This provides a smoother CMake integration overall and you don't have to start defining your own interface target. While the approach above will still work even with Catch2, I would recommend using find_package if your Catch version supports it already.

相关文章