Testing for assert in the Boost Test framework

后端 未结 6 753
忘掉有多难
忘掉有多难 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:41

    Having the same problem, I digged through the documentation (and code) and found a "solution".

    The Boost UTF uses boost::execution_monitor (in ). This is designed with the aim to catch everything that could happen during test execution. When an assert is found execution_monitor intercepts it and throws boost::execution_exception. Thus, by using BOOST_REQUIRE_THROW you may assert the failure of an assert.

    so:

    #include 
    #include   // for execution_exception
    
    BOOST_AUTO_TEST_CASE(case_1)
    {
      BOOST_REQUIRE_THROW(function_w_failing_assert(),
                          boost::execution_exception);
    }
    

    Should do the trick. (It works for me.)

    However (or disclaimers):

    • It works for me. That is, on Windows XP, MSVC 7.1, boost 1.41.0. It might be unsuitable or broken on your setup.

    • It might not be the intention of the author of Boost Test. (although it seem to be the purpose of execution_monitor).

    • It will treat every form of fatal error the same way. I e it could be that something other than your assert is failing. In this case you could miss e g a memory corruption bug, and/or miss a failed failed assert.

    • It might break on future boost versions.

    • I expect it would fail if run in Release config, since the assert will be disabled and the code that the assert was set to prevent will run. Resulting in very undefined behavior.

    • If, in Release config for msvc, some assert-like or other fatal error would occur anyway it would not be caught. (see execution_monitor docs).

    • If you use assert or not is up to you. I like them.

    See:

    • http://www.boost.org/doc/libs/1_41_0/libs/test/doc/html/execution-monitor/reference.html#boost.execution_exception

    • the execution-monitor user-guide.

    Also, thanks to Gennadiy Rozental (Author of Boost Test), if you happen to read this, Great Work!!

提交回复
热议问题