Reputation: 7184
I'm stating in QT C++ world. I'm doing TDD using QTest class. I want to verify that in certain conditions an exception is thrown by my class under test. Using google test, I would use something like:
EXPECT_THROW(A(NULL), nullPointerException);
Does it exists something like this feature in QTest? O at least a way to do it?
Thanks!
Upvotes: 12
Views: 7733
Reputation: 9196
Since Qt5.3 QTest provides a macro QVERIFY_EXCEPTION_THROWN that provides the missing feature.
Upvotes: 16
Reputation: 22366
This macro demonstrates the principle.
The typeid
comparison is a special use case, so may or may not want to use it - it allows the macro to 'fail' the test even when the thrown exception is derived from the one you are testing against. Often you won't want this, but I threw it in 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;
}
Returns:
Caught Derived exception caught Nothing thrown
To adapt it for QTest
you will need to force a fail with QFAIL
.
Upvotes: 7