Verifying exception messages with GoogleTest

后端 未结 1 1810
情话喂你
情话喂你 2021-01-12 02:11

Is it possible to verify the message thrown by an exception? Currently one can do:

ASSERT_THROW(statement, exception_type)

which is all fin

相关标签:
1条回答
  • 2021-01-12 02:49

    Something like the following will work. Just catch the exception somehow and then do EXPECT_STREQ on the what() call:

    #include "gtest/gtest.h"
    
    #include <exception>
    
    class myexception: public std::exception
    {
      virtual const char* what() const throw()
      {
        return "My exception happened";
      }
    } myex;
    
    
    TEST(except, what)
    {
      try {
        throw myex;
      } catch (std::exception& ex) {
          EXPECT_STREQ("My exception happened", ex.what());
      }
    
    }
    
    int main(int argc, char **argv) {
      ::testing::InitGoogleTest(&argc, argv);
      return RUN_ALL_TESTS();
    }
    
    0 讨论(0)
提交回复
热议问题