Test a specific exception type is thrown AND the exception has the right properties

前端 未结 10 1695
梦如初夏
梦如初夏 2020-12-24 01:55

I want to test that MyException is thrown in a certain case. EXPECT_THROW is good here. But I also want to check the exception has a specific state

10条回答
  •  心在旅途
    2020-12-24 02:20

    I recommend defining a new macro based on Mike Kinghan's approach.

    #define ASSERT_EXCEPTION( TRY_BLOCK, EXCEPTION_TYPE, MESSAGE )        \
    try                                                                   \
    {                                                                     \
        TRY_BLOCK                                                         \
        FAIL() << "exception '" << MESSAGE << "' not thrown at all!";     \
    }                                                                     \
    catch( const EXCEPTION_TYPE& e )                                      \
    {                                                                     \
        EXPECT_EQ( MESSAGE, e.what() )                                    \
            << " exception message is incorrect. Expected the following " \
               "message:\n\n"                                             \
            << MESSAGE << "\n";                                           \
    }                                                                     \
    catch( ... )                                                          \
    {                                                                     \
        FAIL() << "exception '" << MESSAGE                                \
               << "' not thrown with expected type '" << #EXCEPTION_TYPE  \
               << "'!";                                                   \
    }
    

    Mike's TEST(foo_test,out_of_range) example would then be

    TEST(foo_test,out_of_range)
    {
        foo f;
        ASSERT_EXCEPTION( { f.bar(111); }, std::out_of_range, "Out of range" );
    }
    

    which I think ends up being much more readable.

提交回复
热议问题