How to check with QTest that an exception is thrown?

I talk about the world of QT C ++. I am doing TDD using the QTest class. I want to check that under certain conditions an exception is thrown by my tested class. Using google test, I would use something like:

EXPECT_THROW(A(NULL), nullPointerException); 

Is there something similar in QTest? O at least a way to do this?

Thanks!

+7
source share
2 answers

Since Qt5.3 QTest provides the macro QVERIFY_EXCEPTION_THROWN , which provides the missing function.

+10
source

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 .

+5
source

All Articles