我想使用Google Test来测试此功能:
foo() {
if(some_grave_error)
exit(1);
// do something
}
如果foo
调用std::exit()
,我希望测试失败。我该怎么做呢?这与 EXPECT_EXIT 的作用相反?
答案 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);
}