🔖

GoogleTestでC++のクラスのユニットテストを行う手順

2025/03/15に公開

概要

GoogleTestでC++のクラスのユニットテストを行う手順を記載します。

手順

まず、テスト対象のクラスを定義します。今回はPointクラスという座標を扱うクラスを定義します。

Point.cpp
class Point
{
public:
    int x;
    int y;

    Point(int x, int y)
    {
        this->x = x;
        this->y = y;
    }
};

次にCMakeの設定ファイルを追加します。

CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(app)

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

set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

enable_testing()

add_executable(
  PointTest
  PointTest.cpp
)
target_link_libraries(
  PointTest
  GTest::gtest_main
)

include(GoogleTest)
gtest_discover_tests(PointTest)

最後に、ユニットテストを追加します。

PointTest.cpp
#include <gtest/gtest.h>

#include "Point.cpp"

TEST(PointTest, BasicAssertions)
{
    Point point(1, 2);

    EXPECT_EQ(point.x, 1);
    EXPECT_EQ(point.y, 2);
}

ユニットテスト実行方法

次のコマンドを実行します。

$ cmake -S . -B build
$ cmake --build build
$ cd build && ctest

Discussion