qtqttest

Real world code examples about usage of four special slots of Qt Test


I am studying about Qt Test and got to know there are four special slots which are executed before and after test cases.

  1. initTestCase() will be called before the first testfunction is executed.
  2. cleanupTestCase() will be called after the last testfunction was executed.
  3. init() will be called before each testfunction is executed.
  4. cleanup() will be called after every testfunction.

I know how to use them as a clear example is there in Qt Documentation.

But my problem here is I want to see real world usage, not printing an example qDebug, of those slots. What can be changed within those slots?


Solution

  • I found an answer for my own question here.

    Try to always do the initTestCase() and cleanupTestCase() methods, so they can be executed at the startup and at the end of the test. Those methods usually are to create and delete objects, as you can see in the example. If you don't create them, they will be “executed” anyway but will do nothing.

    #ifndef CIRCLETEST_H
    
    #define CIRCLETEST_H
    
    #include <QObject>
    
    #include <QtTest/QtTest>
    
    #include "../Geometry/circle.h"
    
    class CircleTest : public QObject
    
    {
    
      Q_OBJECT
    
    public:
    
      explicit CircleTest(QObject *parent = 0);
    
    private:
    
      Circle *c1;
    
      Circle *c2;
    
    private slots:
    
      void initTestCase();
    
      void testRadius();
    
      void testArea();
    
      void cleanupTestCase();
    
    };
    
    #endif // CIRCLETEST_H
    

    circle.h

    #include "circletest.h"
    
    CircleTest::CircleTest(QObject *parent) :
    
      QObject(parent)
    
    {
    
    }
    
    void CircleTest::initTestCase()
    
    {
    
      c1 = new Circle();
    
      c2 = new Circle(10);
    
    }
    
    void CircleTest::testArea()
    
    {
    
      QCOMPARE(c1->getArea(), 3.14);
    
      QCOMPARE(c2->getArea(), 314.0);
    
    }
    
    void CircleTest::testRadius()
    
    {
    
      QCOMPARE(c1->getRadius(), 1.0);
    
      QCOMPARE(c2->getRadius(), 10.0);
    
    }
    
    void CircleTest::cleanupTestCase()
    
    {
    
      delete c1;
    
      delete c2;
    
    }