c++ - 测试特定的异常类型被抛出并且异常具有正确的属性

标签 c++ unit-testing exception googletest

我想测试在某种情况下是否抛出了 MyExceptionEXPECT_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/

相关文章:

c++ - qtCreator 和 docker 最佳实践

c# - Moq 和 Equals() 的组合使 MS 测试框架崩溃

unit-testing - SPRING Roo 项目 - 版本控制中应该保留什么

exception - JFreechart 系列异常

c++ - 在 Visual Studio 中添加对 C++ 项目的引用会产生什么后果?

c++ - 使用 gets(a) 而不是 cin.getline(a,20) 有什么好处?

c# - TDD:测试构造函数设置属性是否有意义?

c++ - 默认析构函数的 gcc 异常规范

python - 如果出现异常

c++ - 当我想发送 "num8"时,SendInput 发送 "vk_up"?怎么会?