4

我开始了一个使用 Qt 的项目。我想为这个项目添加一些测试。我想将测试拆分为不同的类别。

  1. 导出数据的测试
  2. 计算数据的测试
  3. 用于操作数据的测试...

为此,我创建了这个简单的.pro文件:

QT += testlib
QT += gui
CONFIG += qt warn_on depend_includepath testcase

TEMPLATE = app

SOURCES +=  \
    export_test/tst_export_all_log.cpp \
    export_test/tst_export_last_log.cpp \
    main.cpp

HEADERS += \
    TestSuite.h \
    export_test/ExportTest.h

这是相关的主文件 这是一个简单的主文件,可以在所有测试中运行该功能 由于变量QTest::qExec,可以启用或禁用类别DEFINE

#include <QtTest>

#include "export_test/ExportTest.h"

#define EXPORT_TEST 1

int main(int argc, char *argv[]) {
    int status = 0;

    auto runTests = [&](const auto &tests) {
        for (auto test : tests) {
            status |= QTest::qExec(test, argc, argv);
        }
    };

#if EXPORT_TEST
    runTests(ExportTest::suite());
#endif
    return status;
}

这是ExportTest课程。这个想法是创建静态对象,该对象在suite()方法内静态初始化的向量内自动注册。

#pragma once

#include <QObject>

template <typename T>
class TestSuite : public QObject {
  public:
    TestSuite() { suite().push_back(this); }

    static std::vector<QObject *> &suite() {
        static std::vector<QObject *> vector;
        return vector;
    }
};


class ExportTest : public TestSuite<ExportTest> {
    Q_OBJECT
  public:
    using TestSuite<ExportTest>::TestSuite;
};

这是一项测试的“实施”

#include <QtTest>
#include <QCoreApplication>

#include "ExportTest.h"

class export_last_log : public ExportTest {
    Q_OBJECT

  public:
  private slots:

    void test_case1();
};

void export_last_log::test_case1() { QCOMPARE(1, 2); }

#include "tst_export_last_log.moc"

static export_last_log export_last_log;

一切似乎都有效,当我运行它时,我得到了这个:

********* Start testing of export_all_log *********
Config: Using QtTest library 5.9.9, Qt 5.9.9 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 5.3.1 20160406 (Red Hat 5.3.1-6))
PASS   : export_all_log::initTestCase()
PASS   : export_all_log::test_case1()
PASS   : export_all_log::cleanupTestCase()
Totals: 3 passed, 0 failed, 0 skipped, 0 blacklisted, 0ms
********* Finished testing of export_all_log *********
********* Start testing of export_last_log *********
Config: Using QtTest library 5.9.9, Qt 5.9.9 (x86_64-little_endian-lp64 shared (dynamic) release build; by GCC 5.3.1 20160406 (Red Hat 5.3.1-6))
PASS   : export_last_log::initTestCase()
FAIL!  : export_last_log::test_case1() Compared values are not the same
   Actual   (1): 1
   Expected (2): 2
   Loc: [../../src/core_tests/export_test/tst_export_last_log.cpp(15)]
PASS   : export_last_log::cleanupTestCase()
Totals: 2 passed, 1 failed, 0 skipped, 0 blacklisted, 0ms
********* Finished testing of export_last_log *********

但是,无法从 QtCreator 的“8. 测试结果”选项卡启动测试。按钮都是灰色的 无法查看哪个测试容易失败,视图是空的。

也许我还不太了解如何使用 Qt 进行测试?或者也许我忘记在.pro文件中做一些事情来强制 QtCreator 将其识别为测试?

4

0 回答 0