如何用QTest验证是否抛出了异常?

Kil*_*zor 9 qt qtestlib

我在QT C++世界中说过.我正在使用QTest类进行TDD.我想验证在某些情况下我的类正在测试中抛出异常.使用谷歌测试,我会使用类似的东西:

EXPECT_THROW(A(NULL), nullPointerException);
Run Code Online (Sandbox Code Playgroud)

QTest中是否存在类似此功能的内容?O至少有办法吗?

谢谢!

Sil*_*cer 12

由于Qt5.3 QTest提供了一个宏QVERIFY_EXCEPTION_THROWN,它提供了缺失的功能.


cma*_*t85 7

这个宏证明了原理.

typeid比较特殊用途的情况下,可能会或可能不会想用它-它允许宏为"失败",即使抛出的异常是从你对测试一个测试而得.通常你不会想要这个,但无论如何我扔了它!

#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;
}
Run Code Online (Sandbox Code Playgroud)

返回:

Caught
Derived exception caught
Nothing thrown
Run Code Online (Sandbox Code Playgroud)

要适应它,QTest你需要强制失败QFAIL.