user1523271
user1523271

Reputation: 1063

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?

Upvotes: 3

Views: 2240

Answers (1)

YSC
YSC

Reputation: 40150

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);
}

Upvotes: 7

Related Questions