9

是否可以验证异常抛出的消息?目前可以这样做:

ASSERT_THROW(statement, exception_type)

这一切都很好,但是我在哪里可以找到一种方法来测试 e.what() 真的是我想要的。这不能通过谷歌测试吗?

4

1 回答 1

2

像下面这样的东西会起作用。只需以某种方式捕获异常,然后EXPECT_STREQwhat()通话中执行:

#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();
}
于 2013-09-12T21:59:04.867 回答