Mr. Boy Mr. Boy - 1 year ago 82
C++ Question

Test a specific exception type is thrown AND the exception has the right properties

I want to test that

is thrown in a certain case.
is good here. But I also want to check the exception has a specific state e.g
e.msg() == "Cucumber overflow"

How is this best implemented in GTest?

Answer Source

I mostly second Lilshieste's answer but would add that you also should verify that the wrong exception type is not thrown:

#include <stdexcept>
#include "gtest/gtest.h"

struct foo
    int bar(int i) {
        if (i > 100) {
            throw std::out_of_range("Out of range");
        return i;

    foo f;
    try {;
        FAIL() << "Expected std::out_of_range";
    catch(std::out_of_range const & err) {
        EXPECT_EQ(err.what(),std::string("Out of range"));
    catch(...) {
        FAIL() << "Expected std::out_of_range";

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download