QT Testing 0 – Creating Multiple Targets with CMake

At first, I was about to start 1st chapter and talk about QT’s Testing with QTest. My aim is to use CMake instead of QMake, so unimportant side of community has issues about CMake. This is why first I will talk about multiple targets and why do we need it for testing.

Sample code is available on GitHub

Unit tests are about testing the class, methods your code. but you cannot test it inside of your code. You need to test it in another target. Most of Open-Source project it’s quite possible to see separated source and tests folders. It’s time to do the same.

New File structure of project will be look like this

Each sub folder has it’s own CMakeLists.txt file and each of them has new project variables. Root CMakeLists.txt is look like this:

cmake_minimum_required(VERSION 3.5)

project(Main_Target LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_subdirectory(src)
add_subdirectory(test)

It adds src and test sub directories via their own CMakeLists.txt files. src’s CmakeLists.txt doesn’t need to specify any project name at all it’s already been declared at top level.

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

find_package(Qt5Core)

add_executable(${PROJECT_NAME}
  main.cpp
)

target_link_libraries(${PROJECT_NAME} Qt5::Core)

For test sub directory, we need a new target to achieve this it has to be a new project, a new target with a new executable binary file as an output. It’s CMakeLists.txt is like:

project(Test_Target LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Qt5Test)

set(TEST_SOURCE_FILES main.cpp
    )

add_executable(${PROJECT_NAME}
  ${TEST_SOURCE_FILES}
)

target_link_libraries(${PROJECT_NAME} Qt5::Core Qt5::Test)

After this configuration there will be two different targets called Main_Target and Test_Target. Main_Target will be about development and Test_Target will be about testing the Main_Target.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *