Home > Enterprise >  How can I test whether std::terminate is NOT called in googletest
How can I test whether std::terminate is NOT called in googletest

Time:12-11

I have a custom assertion like this:

#define MY_ASSERT(condition, message)                                        \
do {                                                                         \
  if (!(condition)) {                                                        \
    std::cerr << "Assertion `" #condition "` failed in " << __FILE__         \
              << " line " << __LINE__ << ": " << message << std::endl;       \
    std::terminate();                                                        \
  }                                                                          \
} while (false)

I know that I can use Death Tests to check if assertions are called. However, I want to check whether the assertion does not actually happen. I want the specific test to actually FAIL instead of the whole application exit with code 3 because assertion failed. Here is the test that I have written:

TEST_F(RenderGraphDeathTest, BuildOnlyCalledOnce) {
  liquid::RenderGraph graph;

  graph.addPass<EmptyScope>(
      "A", [](auto &builder, auto &scope) { builder.write("a-b", {}); },
      noopExecutor);

  graph.compile();

  // Looking for something like EXPECT_NOT_DEATH
  graph.compile();
}

CodePudding user response:

Set a custom terminate handler in the test start. The default handler is std::abort. See std::terminate_handler.

CodePudding user response:

I ended up forcefully exiting and checking the exit status code in a Death Test:

TEST_F(RenderGraphDeathTest, BuildOnlyCalledOnce) {
  liquid::RenderGraph graph;

  graph.addPass<EmptyScope>(
      "A", [](auto &builder, auto &scope) { builder.write("a-b", {}); },
      noopExecutor);

  ASSERT_EXIT({
    graph.compile();
    graph.compile();
    
    // If no assertion is happening,
    // this test will exit with code 0,
    // otherwise, it will exit with the
    // SIGABORT due to std::abort
    // default terminate handler
    exit(0);
  }, ::testing::ExitedWithCode(0), ".*");
}
  • Related