我如何测试代码没有调用 exit()

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

我想用 Google 测试这个函数:

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

我希望我的测试在 foo 调用 std::exit() 时失败。我该怎么做呢?它与 EXPECT_EXIT 的作用相反?

您应该使 foo() 可测试:

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

奇迹般地,你所有的烦恼都消失了:

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