Testing for assert in the Boost Test framework

后端 未结 6 836
忘掉有多难
忘掉有多难 2021-02-05 06:54

I use the Boost Test framework to unit test my C++ code and wondered if it is possible to test if a function will assert? Yes, sounds a bit strange but bear with me! Many of m

6条回答
  •  忘掉有多难
    2021-02-05 07:33

    At work I ran into the same problem. My solution is to use a compile flag. When my flag GROKUS_TESTABLE is on my GROKUS_ASSERT is turned into an exception and with Boost you can test code paths that throw exceptions. When GROKUS_TESTABLE is off, GROKUS_ASSERT is translated to c++ assert().

    #if GROKUS_TESTABLE
    #define GROKUS_ASSERT ... // exception
    #define GROKUS_CHECK_THROW    BOOST_CHECK_THROW
    #else
    #define GROKUS_ASSERT ... // assert
    #define GROKUS_CHECK_THROW(statement, exception)  {}  // no-op
    #endif
    

    My original motivation was to aid debugging, i.e. assert() can be debugged quickly and exceptions often are harder to debug in gdb. My compile flag seems to balance debuggability and testability pretty well.

    Hope this helps

提交回复
热议问题