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

前端 未结 10 1698
梦如初夏
梦如初夏 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:21

    A colleague came up with the solution by just re-throwing the exception.

    The knack: no need of extra FAIL() statements, just the two EXPECT... calls that test the bits you actually want: the exception as such and its value.

    TEST(Exception, HasCertainMessage )
    {
        // this tests _that_ the expected exception is thrown
        EXPECT_THROW({
            try
            {
                thisShallThrow();
            }
            catch( const MyException& e )
            {
                // and this tests that it has the correct message
                EXPECT_STREQ( "Cucumber overflow", e.what() );
                throw;
            }
        }, MyException );
    }
    

提交回复
热议问题