Search code examples
c++windowsunit-testinggoogletestassertions

Catching custom assert in GoogleTest using __debugbreak


On Windows, my assert macro essentially looks like this:

#define MYASSERT(condition) (if (!(condition)) { ReportFailture( #condition, __FILE__, __LINE__, __FUNCTION__); __debugbreak(); }

And in Google Test I am trying to check the output of a bad condition to test out of bound assertions, etc:

ASSERT_DEATH( { MYASSERT(false); }, "");

However all this does it report the following message:

Running main() from gtest_main.cc
..\Test\FormatUnitTest\Test_Format.cpp(59): error: Death test: { if (!(false)) { ReportFailture( "false", ..\\Test\\UnitTest\\Test.cpp", 59,  __FSTREXP __FUNCTION_
_   ); __debugbreak(); }; }

Result: illegal return in test statement.
Error msg:
[  DEATH   ]

It seems that GoogleTest is handling the Debug Exception in the structured exception handler (SEH) as a special case. However, I want to catch the assert and validate it's contents.

What's the right move here? Do I need to define a special assert macro for google test? If so what should it do?

I note that replacing my assert with assert(false) (included via assert.h) doesn't call this problem - what is it doing differently?


Solution

  • The problem is that you are calling __debugbreak(), which causes a breakpoint exception to be thrown by your code. As you can see in documentation for death tests (https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#death-tests), if code throws an exception it is not considered "death" by death tests in googletest.

    As far as you other question goes, assert from assert.h calles std::abort (which causes program to terminate). This is "death" by definition of a death test.