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

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

    I like most of the answers. However, since it seems that GoogleTest provides EXPECT_PRED_FORMAT that helps facilitating this, I'd like to add this option to the list of answers:

    MyExceptionCreatingClass testObject; // implements TriggerMyException()
    
    EXPECT_PRED_FORMAT2(ExceptionChecker, testObject, "My_Expected_Exception_Text");
    

    where ExceptionChecker is defined as:

    testing::AssertionResult ExceptionChecker(const char* aExpr1,
                                              const char* aExpr2,
                                              MyExceptionCreatingClass& aExceptionCreatingObject,
                                              const char* aExceptionText)
    {
      try
      {
        aExceptionCreatingObject.TriggerMyException();
        // we should not get here since we expect an exception
        return testing::AssertionFailure() << "Exception '" << aExceptionText << "' is not thrown.";
      }
      catch (const MyExpectedExceptionType& e)
      {
        // expected this, but verify the exception contains the correct text
        if (strstr(e.what(), aExceptionText) == static_cast(NULL))
        {
          return testing::AssertionFailure()
              << "Exception message is incorrect. Expected it to contain '"
              << aExceptionText << "', whereas the text is '" << e.what() << "'.\n";
        }
      }
      catch ( ... )
      {
        // we got an exception alright, but the wrong one...
        return testing::AssertionFailure() << "Exception '" << aExceptionText
        << "' not thrown with expected type 'MyExpectedExceptionType'.";
      }
      return testing::AssertionSuccess();
    }
    

提交回复
热议问题