How to expect program exit in gtest?

2019-06-22 12:18发布

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条回答
beautiful°
2楼-- · 2019-06-22 13:09

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!

查看更多
登录 后发表回答