c++cppunit

Test an aborting assertion failure in CppUnit


I want to unit test a C++ function which throws aborting assertion error on invalid input.

The function is as follows:

uint64_t FooBar::ReadTimeStamp(std::string& name) {
  auto iter = hash_table_.find(name);
  assert(iter != hash_table_.end());
  ....
}

In unit test, I use CPPUNIT_ASSERT_ASSERTION_FAIL to assert on assertion failure:

void FooBarTest::
  TestReadNonexistentTimestamp() {
  CPPUNIT_ASSERT_ASSERTION_FAIL(ReadTimestamp("NON_EXISTENT"));
}

But I got abort message and unit test failed.

I read this page. It's not clear to me if I need to throw exception here and what the correct way to unit test this scenario would be. Thanks!


Solution

  • Firstly, your misunderstanding is caused by the different ways to use the term "assertion". The test framework itself talks about assertions, but it does not mean the assert() macro provided by the standardlibrary. Since the standard assertion failure causes program termination, you get those results.

    Now, how to fix that:

    Which of these works best is up to you to decide, based on your use case and, admittedly, personal preference.