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

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

    Expanding on previous answers, a macro that verifies that an exception of a given type was thrown and the message of which starts with the provided string.

    The test fails if either no exception is thrown, the exception type is wrong or if the message doesn't start with the provided string.

    #define ASSERT_THROWS_STARTS_WITH(expr, exc, msg) \
        try\
        {\
                (expr);\
                FAIL() << "Exception not thrown";\
        }\
        catch (const exc& ex)\
        {\
                EXPECT_THAT(ex.what(), StartsWith(std::string(msg)));\
        }\
        catch(...)\
        {\
                FAIL() << "Unexpected exception";\
        } 
    

    Usage example:

    ASSERT_THROWS_STARTS_WITH(foo(-2), std::invalid_argument, "Bad argument: -2");
    

提交回复
热议问题