Search code examples
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:

    • Don't use assert(). Instead, you could throw an exception.
    • Don't test this code path. Since this is a programming error that's not recoverable anyway, it can only be caused by misuse of your code (i.e. violating preconditions). Since it's not your code that's at fault, not testing it doesn't have any negative impact on its quality.
    • Hijack assert() to throw a failure that CppUnit understands. This could be tricky because for one, assert() is part of C++ and shouldn't be redefined carelessly (perhaps substituting it with a different macro would be better). Further, you now have three different behaviours: Throw in tests, abort() in regular use, UB with NDEBUG defined.

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