einpoklum
einpoklum

Reputation: 131405

How to unit-test for assert() failing?

I want to unit-test some code which uses assert() occasionally. 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).

My question:

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.

Upvotes: 2

Views: 1388

Answers (1)

eerorika
eerorika

Reputation: 238291

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.

There is no standard way in C++ for spawning sub-processes. The standard doesn't acknowledge the existence of other processes. Multi tasking operating systems will provide an API for this. In POSIX standard, child processes can be created with the fork function.

Upvotes: 2

Related Questions