Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I gtest that code did not call exit()

I'd like to test this function with Google Test:

foo() {
    if(some_grave_error)
        exit(1);
    // do something
}

I want my test to fail if foo calls std::exit(). How do I do this? It is sort of inverse to what EXPECT_EXIT does?

like image 763
user1523271 Avatar asked Jan 19 '26 03:01

user1523271


1 Answers

You should make foo() testable:

using fexit_callback = void(*)(int);
void foo(fexit_callback exit = &std::exit)
{
    if(some_condition)
        exit(1);
}

And magically, all your troubles disappear:

#include <cstdlib>
#include <cassert>

using fexit_callback = void(*)(int);
void foo(fexit_callback exit = &std::exit)
{
    if(true)
        exit(1);
}

namespace mockup
{
    int result = 0;
    void exit(int r) { result = r; }
}

int main()
{
    foo(mockup::exit);
    assert(mockup::result == 1);
}
like image 191
YSC Avatar answered Jan 20 '26 17:01

YSC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!