Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying exception messages with GoogleTest

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?

like image 327
ForeverLearning Avatar asked Sep 12 '13 21:09

ForeverLearning


People also ask

How do I catch exceptions in Gtest?

Handling exceptions Because Google doesn't use exceptions, gtest doesn't handle them. If you're testing code that can throw exceptions, then you need to try/catch them yourself, and then use the ADD_FAILURE and/or FAIL macros as appropriate. ADD_FAILURE records a non-fatal failure, while FAIL records a fatal failure.

What are exceptions C++?

An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another.

What is Expect_eq?

EXPECT_EQ and ASSERT_EQ are also macros—in the former case test execution continues even if there is a failure while in the latter case test execution aborts. Clearly, if the square root of 0 is anything but 0, there isn't much left to test anyway.

What is Assert_no_throw?

ASSERT_NO_THROW( statement ) Verifies that statement does not throw any exception.


1 Answers

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();
}
like image 162
A.E. Drew Avatar answered Sep 24 '22 09:09

A.E. Drew