How we are using Qt Test - ProjectStow/ClassExamples GitHub Wiki
Tests are written as individual programs that compiled into their own standalone executables. The CMakeLists.txt will actually have separate entries to compile and build the test programs.
As a convention we are putting the source code for these programs into a sub-directory called test.
Generally each class to be tested should have a corresponding test class in that directory, generally named the the prefix "test" and then the name of the class to test.
For example in the ZoSupportLib project, the class ZoTable would have a test class called test/testZoTable.cpp. The following is basic example
#include <QTest>
class testZoTable: public QObject
{
Q_OBJECT
private slots:
[[maybe_unused]] void runTests();
};
[[maybe_unused]] void testZoTable::runTests()
{
ZO::ZoTable table;
QVariantList list = {"1",2,"3","Column 4"};
auto rows = table.addRow(list);
QVERIFY2(rows == 1,"addRow did not return the right number of rowCount");
rows = table.rows();
QVERIFY2(rows == 1,"rowCount did not return the right number of rowCount");
auto columns = table.columns() ;
QVERIFY2(columns == 4,"columnCount did not return the correct size");
table.addRow(list);
}
#include "testZoTable.moc"
QTEST_MAIN(testZoTable)
There are a number of requirements to the test code as outlined below:
- The class must be a child of Object
- The entire class should be in one .cpp file and not use a .h file (at least for now)
- The tests to be run should be declared in the private slots section
- QVERIFY2 is preferred on QVERIFY so a meaningful message can be given
- The class must near the very end include the MetaObject file (.moc) for itself
- The final line should be the QTEST_MAIN macro, passing in the name of the class