从ASSERT_THROW获取异常消息

Getting exception message from ASSERT_THROW

本文关键字:异常 消息 获取 THROW ASSERT      更新时间:2023-10-16

我正在使用googletest,在我的许多测试中,我都使用ASSERT_THROW命令。问题是,例如,如果它抛出的异常与我预期的异常不同,我得到的只是:

实际:它抛出了一个不同的类型。

有没有办法让它吐出what()什么的返回值?

你可能通过指针抛出(使用new关键字)

throw new MyDerivedException();

并预期会收到非指针类型的异常:

EXPECT_THROW(blah, MyDerivedException);

你应该按抛出。

throw MyDerivedException(); // notice lack of 'new'
此功能

在 1.11 版googletest中可用。( https://github.com/google/googletest/pull/2903 )

对我有用的(也许是幼稚的)解决方案是定义以下宏:

#define ASSERT_THROW_WITH_MESSAGE(code, expected_exception, expected_message) do { 
    try {                                                   
      { code; }                                             
      FAIL() << "no exception occured" << endl;             
    }                                                       
    catch (const expected_exception &e) {                   
      EXPECT_THAT(e.what(), testing::HasSubstr(expected_message));   
    }                                                       
    catch (const std::exception &e) {                       
      FAIL() << "an unexpected exception occured: " << e.what() << endl; 
    }                                                       
    catch (...) {                                           
      FAIL() << "an unknown exception occured" << endl;     
    }                                                       
  } while(0);

抛出新的MyDerivedException() ...EXPECT_THROW(废话,我的衍生例外*);