Screenplay: Unittest: GTest and CMake

Discussion

  • How to use external code like googletest?

Installed: to be found in Standard Paths

What happens when I say one of these for example?

  • #include <gtest/gtest.h>

  • -lgtest

$ dnf repoquery -l gtest-devel
...
/usr/include/gtest/gtest.h
...
/usr/lib64/libgtest.so
...
$ dpkg --listfiles libgtest-dev
... likewise ...

Discussion

Standard paths

  • Include path: /usr/include/

  • Library path: /usr/lib64/

CMake: “Find Modules”

  • CMake is a “declarative language” (nah, so to say)

  • User declares “I insist in gtest being there”

  • FIND_PACKAGE(GTest REQUIRED)

    • Usually in toplevel CMakeLists.txt

    • … but not necessarily so

# entry point for building C/C++ artifacts. has nothing to do with the
# website build itself; it builds the C/C++ code that is
# referenced/described from in the website.

cmake_minimum_required(VERSION 3.20)
project(JoergFaschingbauer)

enable_testing()

#FIND_PACKAGE(GTest REQUIRED)
find_package(Threads REQUIRED)
set(CMAKE_CXX_STANDARD 23)

# compiler options. (we only check for gcc)
if (${CMAKE_COMPILER_IS_GNUCC})
  set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -ggdb -Wall -Werror")
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -ggdb -Wall -Werror")
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++23")
endif()

add_subdirectory(googletest)
add_subdirectory(googlebenchmark)
add_subdirectory(trainings/material/soup)

add_subdirectory(trainings/log/detail/2020-03-30/code)
add_subdirectory(trainings/log/detail/2025-04-14--C++-2-Days/course-project)

add_subdirectory(about/site/work-in-progress/fh-joanneum/2020/code)
add_subdirectory(about/site/work-in-progress/fh-joanneum/2021)
add_subdirectory(about/site/work-in-progress/fh-joanneum/dtle/code)

Discussion

  • Hm. CMake find modules. Hm.

  • Google is your friend

  • Better yet: use the source, Luke

Show GTest find module; point to documentation,

less /usr/share/cmake/Modules/FindGTest.cmake
...

Consequentially, usage:

ADD_EXECUTABLE(assert assert.cc)
TARGET_LINK_LIBRARIES(assert GTest::GTest)

Executing Tests As Part of Build

ADD_TEST(assert assert)
  • 1st arg: test name (cmake reports failures as such)

  • 2nd arg: command (from ADD_EXECUTABLE())

Tests That Are Expected to Fail

SET_TESTS_PROPERTIES(
  assert ... (maybe more)
  PROPERTIES WILL_FAIL true)