简体   繁体   English

如何对 assert() 失败进行单元测试?

[英]How to unit-test for assert() failing?

I want to unit-test some code which uses assert() occasionally.我想对一些偶尔使用assert()代码进行单元测试。 Specifically, I want to make sure that certain commands do indeed trigger an assert.具体来说,我想确保某些命令确实触发了断言。 But - I don't actually want the program to be aborted.但是 - 我实际上并不希望该程序被中止。 (If that happened I would need both to ensure program abortion from outside the program and have a different program for each such testcase.) (如果发生这种情况,我需要同时确保程序从程序外部中止,并为每个此类测试用例使用不同的程序。)

I also know that assert() is a macro, so if the code I'm testing is header-only, I could theoretically write some kind of replacement macro to trigger a failure using my unit-testing library ( doctest ).我也知道assert()是一个宏,所以如果我正在测试的代码是仅标头的,理论上我可以编写某种替换宏来使用我的单元测试库 ( doctest ) 触发失败。

My question:我的问题:

  • Perhaps doctest already has some facility for this kind of testing?也许 doctest 已经有一些用于这种测试的工具?
  • If not, is there some idiomatic way of implementing assert-firing-tests?如果没有,是否有一些惯用的方式来实现断言测试? Perhaps with other testing frameworks/libraries, which I could adapt?也许与我可以适应的其他测试框架/库一起使用?

Note: I've noticed here on SO that Google Test has some kind of related facility, ASSERT_DEATH , but it's not clear to me that it does what I want to do.注意:我在 SO上注意到 Google Test 有某种相关的工具ASSERT_DEATH ,但我不清楚它是否能完成我想做的事情。

In general, what you can do is spawn a child process, perform the operations there, and test in the parent process whether the child terminated successfully or not, and possibly check any output generated by the child.一般来说,你可以做的是产生一个子进程,在那里执行操作,并在父进程中测试子进程是否成功终止,并可能检查子进程生成的任何输出。 I would assume that's what Google's test does.我认为这就是 Google 的测试所做的。

There is no standard way in C++ for spawning sub-processes. C++ 中没有用于生成子进程的标准方法。 The standard doesn't acknowledge the existence of other processes.该标准不承认其他进程的存在。 Multi tasking operating systems will provide an API for this.多任务操作系统将为此提供 API。 In POSIX standard, child processes can be created with the fork function.在 POSIX 标准中,可以使用fork函数创建子进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM