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
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");