Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

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
    ├── 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.


    main.cpp

    #include "my-app-tests.hpp"
    
    QTEST_GUILESS_MAIN(MyAppTests)
    
    #include "main.moc"
    

    my-app-tests.hpp

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

    tests.pro

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

    my-app-tests-test1.cpp

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

  • Lifetime Qt Champion

    Hi,

    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