Creating Unit Test using Qt Test

Introduction

Hello readers, we discussed some basic introduction and concepts about Qt Test in my previous article. If you are new to the Qt Test, I recommend you to click the below link to go through my previous article before continuing this.

In this article, we are going to write an example application with unit test capabilities by using Qt Test Framework.

Creating a Qt Test Application

Creating an Qt application with testing capability is very simple as discussed in the previous article. Qt creator provides project template for creating the application that contains test classes in-turn test the classes of production code. For better understanding, we can discuss with a simple example below:

Create sample MathCalc class, which is a production code given below:

#ifndef MATHCALC_H
#define MATHCALC_H

class MathCalc
{
public:
    MathCalc(int a = 0, int b = 0) : m_nA(a), m_nB(b) { }


    void setData(int a, int b) {
        m_nA = a;
        m_nB = b;
    }

    int Sum() const { return m_nA + m_nB; }
    int Diff() const { return m_nA - m_nB; }
    int Mult() const { return m_nA * m_nB; }
    int Div() const { return m_nA / m_nB; }

private:
    int m_nA;
    int m_nB;
};

#endif // MATHCALC_H

The above MathCalc is the production code needs to be tested. For testing the MathCalc class, we are going to create the new test class called TestMathCalc class.

#include <QtTest>

#include "mathcalc.h"

class TestMathCalc : public QObject
{
    Q_OBJECT

public:
    TestMathCalc();
    ~TestMathCalc();

private slots:
    void test_sum();
    void test_mult();

private:
    MathCalc m_objMathCalc;
};

TestMathCalc::TestMathCalc()
{

}

TestMathCalc::~TestMathCalc()
{

}

void TestMathCalc::test_sum()
{
    // sum default
    QCOMPARE(m_objMathCalc.Sum(), 0 + 0);

    // sum after setting A and B
    const int A = 10;
    const int B = 20;
    m_objMathCalc.setData(A, B);

    QVERIFY2(m_objMathCalc.getA() == A, "Operand A doesn't match");
    QVERIFY2(m_objMathCalc.getB() == B, "Operand B doesn't match");

    QCOMPARE(m_objMathCalc.Sum(), A + B);
}

void TestMathCalc::test_mult()
{
    const int A = 5;
    const int B = 6;
    m_objMathCalc.setData(A, B);

    QCOMPARE(m_objMathCalc.Sum(), A + B);
}

QTEST_APPLESS_MAIN(TestMathCalc)

#include "tst_testmath.moc"

Run the above code & check the output and it will look like below:


Now Change the line number 41 like below to simulate the failure condition. 

    QVERIFY2(m_objMathCalc.getA() == 0, "Operand A doesn't match");

You will get the output like below:


Conclusion

We experimented with a small example unit test project by using Qt Test Framework. This will give an idea and more confidence to you for exploring more, by using Qt Test. 

You can download the complete source code from the GitHub.
Latest