Home > database >  How to write Qt test for a Qt project
How to write Qt test for a Qt project

Time:01-25

I have read the 5 tutorial from QT-test website. But they are not what I want. I want to build a project and its unit test part is detached from the main program.

For example: In main program has a push-botton on widgets and if it was clicked then a Qlabel will show a number. If I run the test programm, It would mock MouseClicked Event on that button, then verify if the value which shows up on Qlabel is our expectations.

My question is how can I get my test program linked to the main program so that I can access its members? Besides that I want to build the project using CMake, how should I write the CMakeLists for the test project?

---root 
|---test
  |----CmakeLists.txt
  |----test.cpp
  |----test.h
|---build
|----main.cpp // only int main function 
|----QMainwindows.cpp 
|----QMainwindows.h
|----QMainwindows.ui
|----CmakeLists.txt

And the CMakeLists.txt in root

cmake_minimum_required(VERSION 3.5)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
project(myproject VERSION 0.1 LANGUAGES CXX)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets)
set(PROJECT_SOURCES
        main.cpp
QMainwindows.cpp 
QMainwindows.h
QMainwindows.ui
)
add_executable(myproject ${PROJECT_SOURCES})
target_link_libraries(myprojectPRIVATE Qt${QT_VERSION_MAJOR}::Widgets)

I am also confused how to access the members from mainwindow in our test. I mean I cant include the ui_mainwindow.h and create an UI_Mainwindow Instance

CodePudding user response:

I found an approach that could answer my question.

In test part I can use findchild<T>("WidgetsName") to get access to ui members of any class.

reference : How do you get a widget's children in Qt?

This may not be a universal solution and if anyone has a better idea, I would be grateful.

  • Related