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?
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.
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.
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.
ASSERT_NO_THROW( statement ) Verifies that statement does not throw any exception.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With