Yesterday 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/tests.pro), 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:
/myproject/
myproject.h
myproject.cpp
main.cpp
myproject.pro/myproject/tests/
MyUnitTest.h
MyUnitTest.cpp
main.cpp
tests.pro
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:
tests.pri
TEMPLATE = app
DEPENDPATH += . ../
INCLUDEPATH += . ../
DESTDIR = ./
CONFIG += qtestlib
unix:QMAKE_POST_LINK=./$$TARGET
win32:QMAKE_POST_LINK=$${TARGET}.exe
Now the .pro file for our project specific unit test:
tests.pro
TARGET = MyUnitTest
HEADERS += MyUnitTest.h
SOURCES += MyUnitTest.cpp main.cpp
include(tests.pri)
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:
main.cpp:
#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.
Thanks! This article save me some time 🙂