Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run qtestlib unit tests from QtCreator

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.

like image 574
Viesturs Avatar asked May 11 '10 08:05

Viesturs


People also ask

How do I run a specific unit test in Visual Studio?

Tests can be run from Test Explorer by right-clicking in the code editor on a test and selecting Run test or by using the default Test Explorer shortcuts in Visual Studio.

Can I use Cypress for unit testing?

You can use Cypress for unit and integration testing. All tests are written in JavaScript and run in real browsers.


3 Answers

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.

like image 89
James Oltmans Avatar answered Oct 27 '22 18:10

James Oltmans


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.

like image 22
aqua Avatar answered Oct 27 '22 19:10

aqua


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.

like image 38
Viesturs Avatar answered Oct 27 '22 17:10

Viesturs