Введение в ООП

GoogleTest

Будем использовать фреймворк GoogleTest для работы с тестированием. Подробнее о её возможностях можете прочитать в документации. В этой главе мы рассмотрим небольшой практический пример.

Продолжим разбирать пример из главы про CMake. У нас есть библиотека factorial с соответсвующей функцией. Напишем к ней тесты в файле tests/test_factorial.cpp. Теперь структура нашего проекта:
-- main.cpp
-- CMakeLists.txt
-- factorial
. . . .| -- CMakeLists.txt
. . . .| -- factorial.h
. . . .| -- factorial.cpp
-- tests
. . . .| -- CMakeLists.txt
. . . .| -- test_factorial.cpp

// test_factorial.cpp
#include <gtest/gtest.h>
#include <factorial.h>

TEST(factorialTest, SimpleTest) {
    EXPECT_EQ(factorial(5), 120);
    EXPECT_EQ(factorial(0), 1);
}

TEST(factorialTest, HardTest) {
    const int n = 100;
    for (int i = 0; i < n; ++i) {
        EXPECT_EQ(factorial(i), i == 0 ? 1 : i * factorial(i - 1));
    }
}

Дополним CMakeLists.txt в корне проекта:

cmake_minimum_required(VERSION 3.2)
project(ExampleProg LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20) 
set(SOURCE_EXE main.cpp)
include_directories(./factorial)
add_executable(Example ${SOURCE_EXE})
add_subdirectory(./factorial)

enable_testing() # включаем тестирование
add_subdirectory(./tests) # подключаем CMakeLists.txt в директории с тестами

target_link_libraries(Example Factorial)

CMakeLists.txt в директории tests:

include(FetchContent)
FetchContent_Declare(
  googletest
  URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
FetchContent_MakeAvailable(googletest)

add_executable(
  test_factorial
  test_factorial.cpp
)
target_link_libraries(
  test_factorial
  Factorial
  GTest::gtest_main
)

include(GoogleTest)
gtest_discover_tests(test_factorial)

Теперь мы можем подготовить проект к сборке:

cmake -S . -B build/ -D CMAKE_BUILD_TYPE=Release -G "MinGW Makefiles"

Собрать проект:

cmake --build .\build\

И запустить тесты:

cd build
ctest -V