Unit Tests and CMake

Here’s an example CMakeLists.txt, where I set up a unit test target, using the GTest framework:

cmake_minimum_required(VERSION 3.19.0)
project(shorten_url VERSION 0.1.0)

# Not necessary for this example, but I use C11 and C++20
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 20)

# Test section
# This command attempts to find an installed copy of GoogleTest
find_package(GTest CONFIG REQUIRED)

# This will now include GoogleTest into the project
include(GoogleTest)

# Here, we create our GTest application, adding the files we need for compiling the tests
add_executable(url_shortener_tests source/url_shortener.cpp source/tests/url_shortener_tests.cpp)

# We have to add our header search folders, for the compile to work
target_include_directories(url_shortener_tests PRIVATE source)

# Now add the libraries we want to link to the GTest target
target_link_libraries(url_shortener_tests PRIVATE GTest::gmock GTest::gtest GTest::gmock_main GTest::gtest_main)

# Some GTest specfics
gtest_add_tests(TARGET      url_shortener_tests
                TEST_SUFFIX .noArgs
                TEST_LIST   noArgsTests
)

The above should get you going with unit testing, as long as CMake can find the GTest frameworks on your computer.

If you need to point CMake to another directory for the GoogleTest, GTest, stuff, you can add the following to your CMakeLists.txt file:

set (GTEST_ROOT ${CMAKE_SOURCE_DIR}/ExternalLibs/gTest)

The set command, followed by GTEST_ROOT will set that variable to the path you need. The above path is just an example and you can change it to anything.

Ref:
https://stackoverflow.com/questions/8507723/how-to-start-working-with-gtest-and-cmake

Leave a Reply

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