catchorg/Catch2

Most approachable way to check for exit?

Opened this issue · 1 comments

Hello everyone,

as far as I know, there's no built in assertion macro to check for an exit call using Catch2.

What's an approachable way to test for an exit() ?

Thanks in advance!

Hi there,

I'm not sure what machinery is in Catch2 dedicated to handle this, but here's how I've handled it in my own project which uses Catch2 (where the code calling exit is actually a C library).

Often exit is a weak symbol, so can be redefined by the calling code (the tester). You could redefine it to throw a specific C++ exception which you can then recognise as the result of an attempted exit. I think the result is nice and idiomatic.

Let's say there's some function f(void) which invokes exit. Your test code can be
E.g.

// changes f's internal behaviour
void exit(int status) {
    throw "exit"; 
}

TEST_CASE( "f" ) {

    REQUIRE_THROWS_WITH( f(), "exit" );
}

Note that the code providing f, when intending to call exit, will not expect the process to stay alive (even though control flow will be 'yanked' back to Catch) and so may be in an internally invalid state. Hence subsequent use of f or other functions may have unexpected behaviour.