我在QT C++世界中说过.我正在使用QTest类进行TDD.我想验证在某些情况下我的类正在测试中抛出异常.使用谷歌测试,我会使用类似的东西:
EXPECT_THROW(A(NULL), nullPointerException);
Run Code Online (Sandbox Code Playgroud)
QTest中是否存在类似此功能的内容?O至少有办法吗?
谢谢!
这个宏证明了原理.
该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)
返回:
Run Code Online (Sandbox Code Playgroud)Caught Derived exception caught Nothing thrown
要适应它,QTest你需要强制失败QFAIL.