Search code examples
c++testinggoogletestthrow

GoogleTest: EXPECT_THROW catches different type?


I'm trying to test EXPECT_THROW, like below.

#include <gtest/gtest.h>
int Foo(int a, int b){
    if (a == 0 || b == 0){
        throw "don't do that";
    }
    int c = a % b;
    if (c == 0)
        return b;
    return Foo(b, c);
}
TEST(FooTest, Throw2){
    EXPECT_THROW(Foo(0,0), char*);
}
int main(int argc, char* argv[]){
    testing::InitGoogleTest(&argc,argv);
    return RUN_ALL_TESTS();
}

I expect that the 'Throw2' should succeed. But it gives this error information:

Expected: Foo(0,0) throws an exception of type char*.
Actual: it throws a different type.

So what is type being thrown here?


Solution

  • "don't do that" is a string literal, the type of which is const char[14]. As such it can only decay to a const char*, not a char* like you expect.

    So amending your test to EXPECT_THROW(Foo(0,0), const char*); should make it pass.

    As an aside, I wouldn't throw an exception in this case. It'd be better IMO to simply return std::optional (or boost::optional if C++17 is not available). Getting bad inputs is not something I'd deem exceptional enough to warrant an exception.

    And if I had to throw an exception, then throwing a standard exception type is loads better than a string literal. In this case std::domain_error seems appropriate.