简体   繁体   English

如何gtest代码没有调用exit()

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

I'd like to test this function with Google Test: 我想用Google Test测试这个功能:

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

I want my test to fail if foo calls std::exit() . 如果foo调用std::exit()我希望我的测试失败。 How do I do this? 我该怎么做呢? It is sort of inverse to what EXPECT_EXIT does? 它与EXPECT_EXIT的作用相反?

You should make foo() testable: 你应该使foo()可测试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM