单元测试作为构建的一部分 [英] Unit testing as part of the build

查看:35
本文介绍了单元测试作为构建的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个分为三部分的 CMake 项目:

I have a CMake project separated in three parts:

  1. 编译我的库
  2. 编译许多单元测试程序来测试这些库的每个精确子部分
  3. 使用这些库编译程序示例

我的问题是关于 2nd 部分.我的单元测试可执行文件是简短的二进制程序,main 成功时返回 0,失败时返回 1.我想将它们的运行集成为构建的一部分.

My question is about the 2nd part. My unit tests executables are short binary programs with a main returning 0 on success, 1 on fail. I would like to integrate their running as part of the build.

是否可以使用 CMake 来执行这两种解决方案之一:

Is it possible to use CMake to do one of those two solutions:

  • 运行每个单元测试程序并检查返回值,如果有任何失败则生成错误.
  • 生成一个测试脚本,该脚本将运行并检查每个单元测试程序并检查返回值以在任何失败时产生错误.

我不是在寻找完整的 CMake 脚本代码,通过指向相应文档的链接来简单说明可能的内容就足够了.

I'm not looking for a complete CMake script code, a simple indication on what is possible with a link to corresponding documentation would be enough.

推荐答案

看到一个类似的问题和我的回答 这里.

See a similar problem and my answer here.

我的主要建议是向运行 ctest 的单元测试目标添加一个 POST_BUILD 步骤.如果 POST_BUILD 步骤确实失败(返回代码不是 0),构建将失败.

Mainly my recommendation is to add a POST_BUILD step to your unit test targets that runs ctest. If a POST_BUILD step does fail (return code is not 0), the build will fail.

类似于:

set(UNIT_TEST MyLibUnitTestTargetName)
add_test(NAME ${UNIT_TEST} COMMAND ${UNIT_TEST})
add_custom_command(
     TARGET ${UNIT_TEST}
     COMMENT "Run tests"
     POST_BUILD 
     WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
     COMMAND ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> -R "^${UNIT_TEST}$" --output-on-failures
)

这样做的好处是它运行起来就像调用 ctest 一样.

This has the advantage that it runs like you would call ctest.

简短版本 - 没有 add_test()/ctest - 将是:

The short version - without add_test() / ctest - would be:

set(UNIT_TEST MyLibUnitTestTargetName)
add_custom_command(
     TARGET ${UNIT_TEST}
     COMMENT "Run tests"
     POST_BUILD 
     COMMAND ${UNIT_TEST}
)

参考文献:

这篇关于单元测试作为构建的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆