我想测试在某种情况下是否抛出了 MyException
。 EXPECT_THROW
在这里很好。但我也想检查异常是否有特定状态,例如 e.msg() == "Cucumber overflow"
。
如何在 GTest 中最好地实现这一点?
最佳答案
一位同事通过重新抛出异常想出了解决方案。
诀窍:不需要额外的 FAIL() 语句,只需两个 EXPECT... 调用来测试您真正想要的位:异常本身及其值。
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 );
}
关于c++ - 测试特定的异常类型被抛出并且异常具有正确的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23270078/