Split the implementation of a single Qt Test class into multiple .cpp files

  • Hello!

    I understand that dividing a Qt Test into multiple classes is a bit tedious and ways of doing it have been discussed before.

    I'm OK with a single Qt Test class, but I would like to split the implementation into multiple .cpp files, like this:

    ├── tests.pro
    ├── main.cpp <-- main imports the header and has QTEST_GUILESS_MAIN(MyAppTests)
    ├── my-app-tests.hpp <-- a single class MyAppTest is declared here
    ├── my-app-tests-test1.cpp <-- here is the implementation of MyAppTest.test1()
    └── my-app-tests-test1.cpp <-- here is the implementation of MyAppTest.test2()

    However, when I do this, building the project with make breaks:

    No rule to make target 'main.moc', needed by 'main.o'. Stop.

    Indeed, when I look into Makefile, I don't see any moc targets created.

    How can I fix this?

    Note that everything works well if the declarations and definitions are in main.cpp.


    #include "my-app-tests.hpp"
    #include "main.moc"


    #include <QtTest>
    class MyAppTests : public QObject
    private slots:
        void test1();
        void test2();


    TARGET = my-app-tests
    TEMPLATE = app
    CONFIG += testcase
    QT     += testlib
    HEADERS += \
    SOURCES += \
        main.cpp \
        my-app-tests-test1.cpp \


    #include "my-app-tests.hpp"
    void MyAppTests::test1()
          QCOMPARE(1, 1);

  • Lifetime Qt Champion


    There's not QObject defined any your main.cpp file anymore, therefore the #include "main.moc" line won't work anymore.

  • @SGaist Thanks! Right, so it seems to be better to live with the limitation and keep the implementation in main.cpp.

Log in to reply