Qt comes with a built-in unit testing module, which we can use by adding the testlib keyword to our project file (.pro):
QT += core gui testlib
After that, add the following header to our source code:
#include <QtTest/QtTest>
Then, we can start testing our code. We must declare our test functions as private slots. Other than that, the class must also inherit from the QOBject class. For example, I created two text functions called testString() and testGui(), like so:
private slots: void testString(); void testGui();
The function definitions look something like this:
void MainWindow::testString() { QString text = "Testing"; QVERIFY(text.toUpper() == "TESTING"); } void MainWindow::testGui() { QTest::keyClicks(ui->lineEdit, "testing gui"); QCOMPARE(ui->lineEdit->text(), QString("testing gui")); }
We used some of the macros provided by the QTest class, such as QVERIFY, QCOMPARE, and so on, to evaluate the expression passed as its argument. If the expression evaluates to true, the execution of the test function continues. Otherwise, a message describing the failure is appended to the test log, and the test function stops executing.
We also used QTest::keyClicks() to simulate mouse clicking in our application. In the earlier example, we simulate clicking on the line edit widget on our main window widget. Then, we input a line of text to the line edit and use QCOMPARE macro to test if the text has been correctly inserting into the line edit widget. If anything wrong happened, Qt will show us the problem in the application output window.
After that, comment out our main() function and use the QTEST_MAIN() function instead to start testing our MainWindow class:
/*int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }*/ QTEST_MAIN(MainWindow)
If we build and run our project now, we should be getting similar results as follows:
********* Start testing of MainWindow ********* Config: Using QtTest library 5.9.1, Qt 5.9.1 (i386-little_endian-ilp32 shared (dynamic) debug build; by GCC 5.3.0) PASS : MainWindow::initTestCase() PASS : MainWindow::_q_showIfNotHidden() PASS : MainWindow::testString() PASS : MainWindow::testGui() PASS : MainWindow::cleanupTestCase() Totals: 5 passed, 0 failed, 0 skipped, 0 blacklisted, 880ms ********* Finished testing of MainWindow *********
There are many more macros that you can use to test your application.
http://doc.qt.io/qt-5/qtest.html#macros