首页 > 解决方案 > 使用测试套件,如何让测试显示在 Qt5 的“测试”窗格视图中?

问题描述

我基本上按照这里这里的说明在 Qt5 中设置了一个 TestSuite 。它按描述工作;然而; 当我从Projects视图切换到Tests视图时,它不会显示单个类测试,如下面的 TestsView 图像所示。我希望它能够显示我的测试类和各个函数槽。这对于我在调试或只想在测试类中执行单个测试函数时很有用。

我找到的解决方法:在 main.cpp 中,如果我实例化类并调用 qExec() 而不是对测试类实例使用 QOject*,那么它可以工作(在下面的 main.cpp 中显示);然而,这违背了测试套件类的目的。

测试视图

// testsuite.h
#pragma once

// Qt headers
#include <QObject>
#include <QtTest/QtTest>

class TestSuite : public QObject
{
    Q_OBJECT

public:
    explicit TestSuite();
    virtual ~TestSuite();

    static QVector<QObject*>& suite();
};

// testsuite.cpp
#include "testsuite.h"

#include <QDebug>

TestSuite::TestSuite()
{
    suite().push_back(this);
}

TestSuite::~TestSuite() {}

QVector<QObject*>& TestSuite::suite()
{
    static QVector<QObject*> instance;
    return instance;
}
// main.cpp
#include "testsuite.h"

#include <QtTest>

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

    int failedTestsCount = 0;

    for (auto &test : TestSuite::suite()) {
        int result = QTest::qExec(test);
        if (result != 0) {
            failedTestsCount++;
        }
    }

    // Work around w/ #include class file
    //TestExampleClass testExampleClass ;
    //QTest::qExec(&testExampleClass );

    return failedTestsCount;
}
// testexampleclass.h
#include <QtTest/QtTest>

#include "testsuite.h" 

class TestExampleClass : public TestSuite
{
      Q_OBJECT

   private slots:
      void  test_addSomeStuff();
};
// testexampleclass.cpp
#include "testexampleclass.h"

static TestExampleClass  sInstance;

// test adding list of numbers
void  TestExampleClass::test_addSomeStuff()
{
   QVERIFY( true );
}

编辑:我正在使用 Qt Creator 4.1.2 和 Qt 5.13.2 (MSVC 2017)

标签: c++qt5qtest

解决方案


我有同样的问题。在“重新扫描 Sest”期间,QC 搜索以下条目:{“QTEST_MAIN”、“QTEST_APPLESS_MAIN”、“QTEST_GUILESS_MAIN”} 以下虚拟宏代码有帮助:

#ifdef QTEST_MAIN
#undef QTEST_MAIN
#endif
#define QTEST_MAIN(TestObject)

QTEST_MAIN(TestClassName)比你在你的测试类声明中放置一个。之后我的测试在 Treeview 中可见: Qt Creator Tests

但是 QTEST_MAIN 将不再起作用。


推荐阅读