我该如何测试代码未调用exit()

时间:2018-10-01 14:33:20

标签: c++ unit-testing googletest

我想使用Google Test来测试此功能:

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

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

1 个答案:

答案 0 :(得分:6)

您应该使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);
}