Stoppt die Vorratsdatenspeicherung! Jetzt klicken & handeln!Willst du auch bei der Aktion teilnehmen? Hier findest du alle relevanten Infos und Materialien:

Qt: Automated Unit Tests with QMAKE

QtYesterday I solved a little problem under Trolltech‘s Qt 4 (a platform independant C++ framework for realizing GUIs, network, fileIO very convenient with less code).

My target was to find a solution to easily setup .pro files for the unit test (/tests/, which automatically run the unit test app after linking. So that the compilation run will be aborted, if a unit test fails.

Formerly I had to execute all unit tests manually – this was very time consuming :(

Further the Q_TEST_MAIN(…) limited the unit test to only one test class.

First of all here my project structure, on which the following examples are based on:





How to use QMake to automatically run unit tests on build / compile??

Here the solution:

A QMake target QMAKE_POST_LINK allows us to run a user defined command after finished linking. After some hours of trying and testing I got following templates for QMake .pro files:

First the common file with project independent settings:

CONFIG += qtestlib

Now the .pro file for our project specific unit test:
TARGET = MyUnitTest
HEADERS += MyUnitTest.h
SOURCES += MyUnitTest.cpp main.cpp

Next problem: How to run multiple unit tests in only one main()?

Normally a test file ends up with Q_TEST_MAIN(…), but this allows only running one test.

Here the solution:

#include “MyUnitTest1.h”
#include “MyUnitTest2.h”

int main(int argc, char** argv) {

QApplication app(argc, argv);

int retval(0);
retval +=QTest::qExec(&MyTest1(), argc, argv);
retval +=QTest::qExec(&MyTest2(), argc, argv);

return (retval ? 1 : 0);


This would produce a test run on each compile / build and will abort the compilation with an error, if one ore more tests fail.

If you got linker errors like (under VS2005) “LNK2005: xxx already defined….” then you can add a new .cpp file for each test class header (e.g. MyTest1.cpp) and move some test method implementations there (like shown above).

Summing up:

So here the steps to write your own unit tests with Qt and the QTestLib:

  • write a unit test class like shown in the QTestLib tutorial
  • write a main() like shown above (just copy and paste)
  • write a .pro file for QMake like shown above

If you’ve questions, just add a comment and I’ll try to help you.

One Response to “Qt: Automated Unit Tests with QMAKE”

  1. Andriy
    June 14th, 2013 14:18

    Thanks! This article save me some time :)

Leave a Reply