Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify with QTest that an exception is thrown?

Tags:

qt

qtestlib

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!

like image 546
Killrazor Avatar asked Feb 20 '13 11:02

Killrazor


People also ask

How do you test exceptions?

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.

What is QT test?

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.


2 Answers

Since Qt5.3 QTest provides a macro QVERIFY_EXCEPTION_THROWN that provides the missing feature.

like image 143
Silicomancer Avatar answered Sep 16 '22 20:09

Silicomancer


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.

like image 22
cmannett85 Avatar answered Sep 17 '22 20:09

cmannett85