How to use Qt Test module to test my own application?

971 views Asked by At

I have a simple console application as below and I want to learn how to use Qt Test to test its functionalities. Honestly, I am trying to learn how to use Qt Test module.

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

#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. But it tests on QString, a class in Qt itself.

   #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.

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.

Thanks in advance.

1

There are 1 answers

1
zziyaa On BEST ANSWER

First, create a Qt Test application(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:

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.

For proper project structure with tests, you can refer to accepted answer at this link.