简体   繁体   English

如何使用 Qt Test 模块来测试我自己的应用程序?

[英]How to use Qt Test module to test my own application?

I have a simple console application as below and I want to learn how to use Qt Test to test its functionalities.我有一个简单的控制台应用程序,如下所示,我想学习如何使用 Qt Test 来测试其功能。 Honestly, I am trying to learn how to use Qt Test module.老实说,我正在尝试学习如何使用 Qt 测试模块。

MyApplication.pro我的应用程序

QT -= gui
CONFIG += c++11 console
CONFIG -= app_bundle

DEFINES += QT_DEPRECATED_WARNINGS

SOURCES += \
        main.cpp \
    pen.cpp \

HEADERS += \
    pen.h

main.cpp主程序

#include <QCoreApplication>
#include <QDebug>

#include "pen.h"

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

    Pen* p = new Pen();
    p->setValue(5);

    qDebug() << "Value of the pen is" << p->getValue();

    return a.exec();
}

pen.h

#ifndef PEN_H
#define PEN_H
    
class Pen
{
public:
    Pen();
    void setValue(int value);
    int getValue();

private:
    int value;
};

#endif // PEN_H

pen.cpp cpp文件

#include "pen.h"

Pen::Pen()
{
    value = 0;
}

void Pen::setValue(int value)
{
    this->value = value;
}

int Pen::getValue()
{
   return value;
}

Simply, it's just a simple application.简单地说,它只是一个简单的应用程序。

I went through Qt documentation about Qt Test module and find a following sample code to run tests.我浏览了有关 Qt 测试模块的 Qt 文档,并找到了以下示例代码来运行测试。 But it tests on QString, a class in Qt itself.但它测试 QString,Qt 本身的一个类。

   #include <QtTest/QtTest>

class TestQString: public QObject
{
    Q_OBJECT
private slots:
    void toUpper();
};

void TestQString::toUpper()
{
    QString str = "Hello";
    QCOMPARE(str.toUpper(), QString("HELLO"));
}

QTEST_MAIN(TestQString)
#include "testqstring.moc"

My question is how I should use Qt Test to test my own application.我的问题是我应该如何使用 Qt Test 来测试我自己的应用程序。

I know I can add a testing module in QtCreator as Other Projects -> Qt Unit Test but I have no idea how to link it with my own application.我知道我可以在 QtCreator 中添加一个测试模块作为其他项目 - > Qt 单元测试,但我不知道如何将它与我自己的应用程序链接。

Thanks in advance.提前致谢。

First, create a Qt Test application(TestPen).首先,创建一个 Qt 测试应用程序(TestPen)。 Since you want to test functionality of Pen class, you should add required header and source files to test project's .pro file(TestPen.pro) like:由于您要测试 Pen 类的功能,您应该将所需的头文件和源文件添加到测试项目的 .pro 文件(TestPen.pro)中,例如:

SOURCES += ../pen.cpp
HEADERS += ../pen.h

Then you can include pen.h in your tst_testpen.cpp and test your Pen class' functionality like shown in the TestQString example.然后你可以在你的 tst_testpen.cpp 中包含 pen.h 并测试你的 Pen 类的功能,如 TestQString 示例中所示。

For proper project structure with tests, you can refer to accepted answer at this link .对于带有测试的正确项目结构,您可以参考此链接中接受的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM