Search code examples
c++unit-testingassertgoogletest

gtest assertions in non-test code


I'm working on a C++ library, and I'm using gtest for unit testing. I want to add ASSERT_* statements to the library code itself, not just the unit test code. I want these ASSERTions to cause a unit test to fail if the code is run under a unit test, or turn into regular asserts if the code is not running under a unite test.

Something like:

if(gtest::is_running)
    ASSERT_TRUE(...);
else
    assert(...);

How can I achieve that?


Solution

  • What about approaching this from the alternate direction? Instead of changing your gtest behavior, change your assert's behavior.

    Boost.Assert, for example, provides a BOOST_ASSERT macro that, by default, behaves identically to assert. However, if BOOST_ENABLE_ASSERT_HANDLER is defined, then it instead looks for a ::boost::assertion_failed function, which you must provide. You could design your library code to build with standard assertion behavior outside of the test suite and with a ::boost::assertion_failed that calls gtest's FAIL() inside of a test suite.

    If you don't want to use Boost, it would be trivial to implement something similar yourself.

    This would require building your library twice (once for the test suite, once for regular use), which may not fit well with your overall goals.