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!
To run an exception test case from the Unit Test toolbar In the AOT, right-click EmployeeTest, point to Add-Ins, and then click Run tests.
Qt Test is a framework for unit testing Qt based applications and libraries. Qt Test provides all the functionality commonly found in unit testing frameworks as well as extensions for testing graphical user interfaces.
Since Qt5.3 QTest provides a macro QVERIFY_EXCEPTION_THROWN that provides the missing feature.
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
.
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