How to structure project while unit-testing Qt app by QTestLib

后端 未结 4 1856
闹比i
闹比i 2020-12-23 16:28

I got my Qt project and I\'m using Qt Creator. I want to unit-test all my code.
However I\'m quite new at QTestLib framework but everyone recommended it for testing Qt-b

4条回答
  •  暖寄归人
    2020-12-23 17:35

    I use Qt Creator by CMake instead of qmake to build my Qt project.

    Basically I have to folders:

    src
    tests
    

    Each test is a program in itself testing a class. The app to be tested is compiled as a library.. You compile all your sources in the folder src as a library.

    // ClassTest.cpp
    #include "ClassTest.h"
    #include "Class2Test.h" // Class of the app
    
    #include 
    
    ClassTest::ClassTest( QObject* parent )
        : QObject(parent)
    { 
    }
    
    QTEST_MAIN( ClassTest )
    #include "ClassTest.moc"
    

    You just have to link your lib to your test executable.

    Example:

    in the src folder CMakeLists.txt example

    add_library( MyAPP
        SHARED
        Class2Test.cpp
    )
    target_link_libraries( MyAPP
        ${QT_LIBRARIES}
    )
    

    in the tests folder CMakeLists.txt example, for each test.

    qt4_automoc( ${test_src} )
    add_executable( ${test_name} ${test_src} )
    target_link_libraries( ${test_name}
        MyAPP
        ${QT_LIBRARIES}
        ${QT_QTTEST_LIBRARY}
    )
    

    It is still in the same project but you can add a flag to let the user compile the test or not. It is clean because the app stays untouched and it allows you to test each class of your app.

提交回复
热议问题