Qt Gui单元测试:必须在QPaintDevice之前构造QApplication

时间:2013-05-23 10:00:02

标签: c++ qt unit-testing qt-creator

我设法用this tutorial写了一个“Gui单元测试”。但是,当我编译我的代码时,我得到了这个:

PASS   : testUnits::initTestCase()
PASS   : testUnits::toUpper()
QFATAL : testUnits::testGui() QWidget: Must construct a QApplication before a QPaintDevice
FAIL!  : testUnits::testGui() Received a fatal error.
Unknown file(0) : failure location
Totals: 2 passed, 1 failed, 0 skipped
********* Finished testing of testUnits *********

为什么它给了我:必须在QPaintDevice之前构建一个QApplication?

2 个答案:

答案 0 :(得分:3)

现在可以使用,这是我的Gui单元测试功能定义:

void testUnits::testGui(){
    QLineEdit lineEdit;
    QTest::keyClicks(&lineEdit,"hellow world");
    QCOMPARE(lineEdit.text(), QString("hello world"));
}

以下是修复问题之前我的main()的样子:

int main(int argc, char *argv[])
{

    testUnits testString;
    QTest::qExec(&testString, argc, argv);

    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

因此,当我编译代码时,它会在构造QApplication之前执行单元测试。

因此我在QApplication之后放了我的QTest :: qExec(),现在它可以工作了,main()看起来像这样:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    testUnits testString;
    QTest::qExec(&testString, argc, argv);

    return a.exec();
}

答案 1 :(得分:2)

最好不要手动定义自己的main。所有测试逻辑,包括所需的前提条件,都应在测试对象(QObject子类,test*槽)本身内进行。有关详细信息,请参阅QTestLib manual

如果您这样做,那么只需使用QTEST_MAIN就可以做正确的事情,并为您节省一些时间。

相关问题