Verifying exception messages with GoogleTest

2019-02-16 23:44发布

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

ASSERT_THROW(statement, exception_type)

which is all fine and good but no where can I find a way to test e.what() is really what I am looking for. Is this not possible via google test?

1条回答
Summer. ? 凉城
2楼-- · 2019-02-17 00:00

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();
}
查看更多
登录 后发表回答