Search code examples
c++unit-testinggoogletest

Usage of --gtest_throw_on_failure together with ASSERT_ANY_THROW in test


During the execution of a unit test, I expect my program to fail an assertion and then crash.

My plan was to test that the programm effectively crashes given some conditions that I prepare with the test. For this, I wanted to use in my test ASSERT_ANY_THROW(statement_causing_crash);.

and run my tests with the flag --gtest_throw_on_failure.

The result when running from the command line is:

  1. The executable generated crashes when reaching the assertion (as expected)
  2. A window pops up reporting the crash
  3. In the command line, where I see the result of the tests, the line and reason of the fail is reported
  4. The execution of the tests does not continue (the .exe crashed)

What is that, that I have not yet understood about the usage of ASSERT_ANY_THROW and --gtest_throw_on_failure?

I also don't want to see the window reporting the crash, because the tests should run automatically on a regular basis.

By the way, something else that I also tried, was to use ASSERT_DEATH instead of ASSERT_ANY_THROW, and it works better, because all the tests are executed.

Nevertheless, the .exe keeps crashing and I need to press "Close the program" so that the tests continue after the crash, which is really not good, because as I mentioned above, these tests run automatically, and many tasks depend on the result of the tests.


Solution

    • ASSERT_ANY_THROW is used to test if an exception is thrown from the code being tested. Read this.

    • Executing the tests with the flag --gtest_throw_on_failure makes Google Test assertion failures to throw an exception. The idea behind this is that another testing framework will detect this exception and fail a test. Complete information here.

    In summary, ASSERT_ANY_THROW and the flag --gtest_throw_on_failure don't have anything to do with each other.

    And by the way, using GCC I could not find a way to avoid the pop up windows and use ASSERT_DEATH. My solution to my problem was to fake the assert, and use it in my tests. My assert's fake throws an exception, which is detected by ASSERT_ANY_THROW.