【问题标题】:How to verify with QTest that an exception is thrown?如何使用 QTest 验证是否引发了异常?
【发布时间】:2013-02-05 09:42:44
【问题描述】:

我说的是 QT C++ 世界。我正在使用 QTest 类进行 TDD。我想验证在某些情况下,我的测试类是否引发了异常。使用谷歌测试,我会使用类似的东西:

EXPECT_THROW(A(NULL), nullPointerException);

QTest 中是否存在类似此功能的功能? O 至少有办法做到这一点?

谢谢!

【问题讨论】:

  • 异常在 qt 世界中并不常见。 QTest 中没有针对此的特定宏,但您可以使用 QVERIFY 进行 try catch 块测试。或者,您也可以将 google test 与 qt 一起使用(出于多种原因,这比 qtest imho 好得多)
  • 是的,此时我意识到 gtest 比 QTest 好得多。谢谢!
  • 此外,gtest 支持 gmock,而 QTest 没有这样的功能。 QTest 真的只是用于休闲用途,而不是用于良好的 UT。如果您使用 gtest,您需要从 QTest 获得的唯一东西就是 QSignalSpy。在 gtest 中,所有其他方面都好得多。
  • 第二个答案现在应该是正确的了!

标签: qt qtestlib


【解决方案1】:

这个宏演示了原理。

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;
}

返回:

Caught
Derived exception caught
Nothing thrown

要使其适应QTest,您需要使用QFAIL 强制失败。

【讨论】:

  • 为什么不使用catch (const exceptionClass&amp; e ) { \ if ( typeid( e ) == typeid( exceptionClass ) ) {独立于std::exception?
  • 因为如果异常不是或不是源自exceptionClass,则将跳过catch块。
  • 我明白了,那么添加catch(...)并算作未处理就足够了
  • 是的,你的权利,所以如果它不是 std::exception 或派生的,它不会导致 QTest 应用程序中止。
  • 我的意思有点不同,不只是添加catch(...),还要将catch ( std::exception&amp; e ) 替换为catch (const exceptionClass&amp; e ),这将是一个完整的解决方案。
【解决方案2】:

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

【讨论】:

  • 唯一的问题是If not-substitutable type of exception is thrown or the expression doesn't throw an exception at all, then a failure will be recorded in the test log and the test won't be executed further.。这意味着实际上没有开箱即用的解决方案可以让您检查是否不抛出给定的异常类型(或派生的异常类型)。
  • 如何验证标准构造函数是否被删除?使用宏对其进行测试会引发异常并中止执行。
猜你喜欢
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 2020-11-05
  • 2013-03-27
  • 1970-01-01
相关资源
最近更新 更多