This macro demonstrates the principle.
Comparison of typeid is a special precedent, so it may or may not want to use it - it allows the macro to βfailβ the test, even if an exception is selected from the one with which you are testing. Often you donβt need it, but I left it anyway!
#define EXPECT_THROW( func, exceptionClass ) \ { \ bool caught = false; \ try { \ (func); \ } catch ( exceptionClass& e ) { \ if ( typeid( e ) == typeid( exceptionClass ) ) { \ cout << "Caught" << endl; \ } else { \ cout << "Derived exception caught" << endl; \ } \ caught = true; \ } catch ( ... ) {} \ if ( !caught ) { cout << "Nothing thrown" << endl; } \ }; void throwBad() { throw std::bad_exception(); } void throwNothing() { } int main() { EXPECT_THROW( throwBad(), std::bad_exception ) EXPECT_THROW( throwBad(), std::exception ) EXPECT_THROW( throwNothing(), std::exception ) return EXIT_SUCCESS; }
Return:
Caught Derived exception caught Nothing thrown
To adapt it for QTest , you need to force a failure with QFAIL .
cmannett85
source share