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

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

    My version; it produces the same output as EXPECT_THROW and just adds the string test:

    #define EXPECT_THROW_MSG(statement, expected_exception, expected_what)                    \
      try                                                                                     \
      {                                                                                       \
        statement;                                                                            \
        FAIL() << "Expected: " #statement " throws an exception of type " #expected_exception \
                  ".\n"                                                                       \
                  "  Actual: it throws nothing.";                                             \
      }                                                                                       \
      catch (const expected_exception& e)                                                     \
      {                                                                                       \
        EXPECT_EQ(expected_what, std::string{e.what()});                                      \
      }                                                                                       \
      catch (...)                                                                             \
      {                                                                                       \
        FAIL() << "Expected: " #statement " throws an exception of type " #expected_exception \
                  ".\n"                                                                       \
                  "  Actual: it throws a different type.";                                    \
      }
    

提交回复
热议问题