Question

I am developing a GUI application in Qt Creator and want to write some unit tests for it.

I followed This guide to make some unit tests with QtTestlib and the program compiles fine. But how do I run them? I would like them to be run before the GUI app starts if debug buid and not run if release build.

Was it helpful?

Solution 3

Finally figured out how to run tests before starting the app.

I added one static method in the tests class to run the tests:

#include <QtTest/QtTest>

TestClass::runTests()
{
    TestClass * test = new TestClass();

    QTest::qExec(test);
    delete test;
}

In the main function, do:

int main(int argv, char *args[])
{
    ::TestsClas::runTests();

    QApplication app(argv, args);
    MainWindow mainWindow;
    mainWindow.setGeometry(100, 100, 800, 500);
    mainWindow.show();

    return app.exec();
}

The test results are printed in application output window.

OTHER TIPS

Do not put test code into your main project. You should create a separate project for your unit tests then build and run that. Do not modify your main project to run tests.

Ideally, you should have a build server set up that will automatically invoke your unit test project and build your releases. You can script this.

Never hack your main application to run your unit tests. If you need to do integration level testing (i.e. testing how the program works once it is fully compiled and integrated) you should use a different integration testing framework that allows you to test the program from an externally scripted source. FrogLogic's Squish is one such framework.

Use multiple targets and preprocessor flags to achieve this:

int main(int argv, char *args[])
{
#ifdef TEST
    ::TestsClas::runTests();
#endif
    QApplication app(argv, args);
    MainWindow mainWindow;
    mainWindow.setGeometry(100, 100, 800, 500);
    mainWindow.show();

    return app.exec();
}

Then go into the projects pane and add a new target "Test" by duplicating "Debug". Under Build Steps, add an argument to Make that is

CXXFLAGS+=-DTEST

That way the test is included in the Test target, but not the Debug or Release targets.

Qt creator does not yet explicitly support running unit tests at this time (up to Qt Creator 2.0beta). So for the time being you will need to start the tests manually.

If you are using a build system like cmake instead of qmake then you could try to run the unit tests automatically as part of the build process itself. Unfortunately I am not aware of any method to do this with qmake. CMake is supported by Qt creator, although not as well as qmake.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top