How to expect program exit in gtest?

假装没事ソ 提交于 2019-12-23 09:48:32

问题


I'm testing some code that uses CHECK from glog and I'd like to test that this check fails in certain scenarios. My code looks like:

void MyClass::foo() {
  // stuff...
  // It's actually important that the binary gets aborted if this flag is false
  CHECK(some_flag) << "flag must be true";

  // more stuff...
}

I've done some research into gtest and how I might be able to test for this. I found EXPECT_FATAL_FALIURE, EXPECT_NONFATAL_FAILURE, and HAS_FATAL_FAILURE but I haven't managed to figure out how to use them. I'm fairly confident that if I change CHECK(some_flag) to EXPECT_TRUE(some_flag) then EXPECT_FATAL_FAILURE will work correctly but then I'm introducing test dependencies in non-test files which is...icky.

Is there a way for gtest to catch the abort signal (or whatever CHECK raises) and expect it?


回答1:


aaaand I found an answer 5 minutes after posting this question. Typical.

This can be done using Death tests from gtest. Here's how my test looks:

TEST(MyClassTest, foo_death_test) {
  MyClass clazz(false); // make some_flag false so the CHECK fails
  ASSERT_DEATH( { clazz.foo(); }, "must be true");
}

This passes. Woohoo!



来源:https://stackoverflow.com/questions/33485754/how-to-expect-program-exit-in-gtest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!