GoogleTest の使い方 (Ubuntu)

 

GoogleTest の使い方についてメモしていきます。

 

 

 

1. GoogleTest をインストール

1-1. パッケージマネージャーでインストールする

Ubuntuでは以下のコマンドでインストールできます。使用するディストリビューションによって適宜コマンドは変更してください。

sudo apt-get install libgtest-dev

 

注意

GoogleTest 用のパッケージ libgtest-dev は古いバージョンだと "google mock" が同梱されていません。その場合は最新のソースコードをレポジトリから取得し、それをビルドして使用します。

 

 

1-2. ソースコードをビルドしてインストールする

[概要]

Github からソースコード一式を取得後、cmake、make、make install します。

 

[環境]

OS : Ubunsu, 20.04 (WSL)
Tool: googletest, 1.15.2

 

 

Step1.

ソースをダウンロードします。Google Test のリポジトリはこちらです。

google/googletest: GoogleTest - Google Testing and Mocking Framework (github.com)

 

Release はこちら。こちらをお勧め、という記事があったので私もこちらから取得します。

Releases · google/googletest (github.com)

 

Step2.

事前に必要なパッケージをインストールします。

[table.] simple table のサンプル1
パッケージ名 説明
build-essential c/c++ ビルド環境
cmake プロジェクトのビルドに使用

 

sudo apt install build-essential cmake lcov

 

Step3. Google Test をビルド

普通に cmake でビルドします。

$ mkdir temp
$ cd temp 
$ wget https://github.com/google/googletest/releases/download/v1.15.2/googletest-1.15.2.tar.gz
$ tar zxvf googletest-1.15.2.tar.gz
$ cd googletest-1.15.2
$ mkdir build 
$ cd build 
$ cmake .. 
$ make 
$ sudo make install 

 

以上でインストール完了です。

 

インストール先を変更したい場合は、cmake するときに  CMAKE_INSTALL_PREFIX を設定します。

・・・
$ mkdir build
$ cd build
$ cmake -DCMAKE_INSTALL_PREFIX=path/to/install/dir ../
$ make
$ sudo make install

 

 

2. GoogleTest の使い方

2-1. 簡単に GoogleTest する

まずは簡単にちゃんと Google Test をインストールできたかを確認したいと思います。

 

1. 今回試すコードは以下のような感じです。これを入力します。

 

["test_gtest.cpp"]

#include <gtest/gtest.h>
TEST(TestCaseName, TestName){
     EXPECT_EQ(1, 1); 
}

 

2. 下記コマンドを入力してビルドします。

$ g++ test_gtest.cpp -o test_gtest -lgtest_main -lgtest

NOTE

インストールした Google Test から gtest_main, gtest をリンクします

 

3. 下記コマンドを入力してテストを実行します

 ./test_gtest

 

実行結果を下図に示します。

Google Test 実行例

 

以上、基本の Google Test 使用方法でした。

 

 

2-2. cmake を使ってみる

2-1._簡単に_Google_Test_する の内容を cmake を使ってビルドしてみます。cmakeを使ったビルドの設定は CMakeLists.txt というテキストファイルに記述します。ディレクトリの中身は次のようになります。

 

./
 ├ CMakeLists.txt
 └ test_gtest.cpp 

 

CMakeLists.txt の内容は次のようになります。

["CMakeLists.txt"]

# CMake のバージョンを設定
cmake_minimum_required(VERSION 3.13)

# プロジェクト名と使用する言語を設定
project(test_gtest CXX)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)

# test_gtest という実行ファイルを test_gtest.cpp から作成
add_executable(test_gtest test_gtest.cpp)

# gtest_main, gtest をリンクします
target_link_libraries(
    test_gtest
    gtest_main
    gtest
)

 

この状態で以下のようにコマンドを入力します。

$ mkdir build
$ cd build
$ cmake ..
$ make
$ ./test_gtest

 

実行結果の画面です。

実行結果

 

 

2-3. GoogleTest を最小限の手間で導入

記事 cmakeプロジェクトにGoogleTestを最小限の手間で導入する #C++ - Qiita による手順に従うと、GoogleTest を事前にインストールしておかなくても cmake できるらしい。試してみます。

 

構成は図の通りで前節と同じです。

./
 ├ CMakeLists.txt
 └ test_gtest.cpp 

 

CMakeLists.txt の内容は次のようになります。

["CMakeLists.txt"]

# CMake のバージョンを設定
cmake_minimum_required(VERSION 3.13)

# プロジェクト名と使用する言語を設定
project(test_gtest CXX)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)

include(FetchContent)
FetchContent_Declare(
  googletest
  DOWNLOAD_EXTRACT_TIMESTAMP ON   # 追加
  URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)

# test_gtest という実行ファイルを test_gtest.cpp から作成
add_executable(test_gtest test_gtest.cpp)

# gtest_main をリンクします
target_link_libraries(
    test_gtest
    GTest::gtest_main
)

 

NOTE

CMake3.24以降では、上記「DOWNLOAD_EXTRACT_TIMESTAMP ON」を記載することが推奨になったようです。これを行わないと "The DOWNLOAD_EXTRACT_TIMESTAMP option was not given and policy CMP0135 is not set." という警告を出力します。

他の対応方法として CMakeLists.txt に "cmake_policy(SET CMP0135 NEW)" を追加するという方法もあるそうです。

 

この状態で以下のようにコマンドを入力します。

$ mkdir build
$ cd build
$ cmake ..
$ make
$ ./test_gtest

 

実行結果の画面です。今回は処理末尾だけ表示します。様子が若干違うけれどもちゃんと期待の動作をしました。

実行結果

 

 

3. libcalcurator.so をテストする

もう少しプログラムらしい内容で紹介します。

本章では、四則演算(足し算、引き算、掛け算、割り算)を行う関数ライブラリ libcalcurator.so を作成して、これを Google Test を使って単体テストしてみます。

 

3-1. build.sh でビルド

 

ファイル構成

./
 ├ calcurator.h
 ├ calcurator.cpp
 ├ build.sh
 └ test
     ├ test_add.cpp
     ├ test_sub.cpp
     ├ test_mul.cpp
     └ test_div.cpp

 

ソースコード

"calcurator.h"

namespace ipro {
    int add(int a, int b);
    int sub(int a, int b);
    int mul(int a, int b);
    int div(int a, int b);
}

 

"calcurator.cpp"

#include <iostream>
#include "calcurator.h"

namespace ipro {
    int add(int a, int b){
        return a + b;
    }
    int sub(int a, int b){
        return a - b;
    }
    int mul(int a, int b){
        return a * b;
    }
    int div(int a, int b){
        if (b == 0) {
            throw std::runtime_error("Division by zero.");
        }
        return a / b;
    }
}

 

テストコード

"test_add.cpp"

#include <iostream>
#include <gtest/gtest.h>
#include "calcurator.h"

class calcurator_add_test : public ::testing::Test {
    protected:
        virtual void SetUp() {
        }
        virtual void TearDown() {
        }
};

TEST_F(calcurator_add_test, add_1) {
    EXPECT_EQ(ipro::add(1, 2), 3);
}

TEST_F(calcurator_add_test, add_2) {
    EXPECT_EQ(ipro::add(-1, -2), -3);
}

TEST_F(calcurator_add_test, add_3) {
    EXPECT_EQ(ipro::add(0, 0), 0);
}

TEST_F(calcurator_add_test, add_4) {
    EXPECT_EQ(ipro::add(1000000, 2000000), 3000000);
}

 

"test_sub.cpp"

#include <iostream>
#include <gtest/gtest.h>
#include "calcurator.h"

class calcurator_sub_test : public ::testing::Test {
    protected:
        virtual void SetUp() {
        }
        virtual void TearDown() {
        }
};

TEST_F(calcurator_sub_test, sub) {
    EXPECT_EQ(ipro::sub(1, 2), -1);
    EXPECT_EQ(ipro::sub(-1, -2), 1);
    EXPECT_EQ(ipro::sub(0, 0), 0);
    EXPECT_EQ(ipro::sub(1000000, 2000000), -1000000);
}

 

"test_mul.cpp"

#include <iostream>
#include <gtest/gtest.h>
#include "calcurator.h"

class calcurator_mul_test : public ::testing::Test {
    protected:
        virtual void SetUp() {
        }
        virtual void TearDown() {
        }
};

TEST_F(calcurator_mul_test, mul) {
    EXPECT_EQ(ipro::mul(1, 2), 2);
    EXPECT_EQ(ipro::mul(-1, -2), 2);
    EXPECT_EQ(ipro::mul(0, 0), 0);
    EXPECT_EQ(ipro::mul(10000, 20000), 200000000);
}

 

"test_div.cpp"

#include <iostream>
#include <gtest/gtest.h>
#include "calcurator.h"

class calcurator_div_test : public ::testing::Test {
    protected:
        virtual void SetUp() {
        }
        virtual void TearDown() {
        }
};

TEST_F(calcurator_div_test, div) {
    EXPECT_EQ(ipro::div(1, 2), 0);
    EXPECT_EQ(ipro::div(-1, -2), 0);
    EXPECT_EQ(ipro::div(0, 1), 0);
    EXPECT_EQ(ipro::div(1000000, 2000000), 0);
    EXPECT_THROW(ipro::div(1, 0), std::runtime_error);
}

 

ビルドスクリプト

"build.sh"

#!/bin/bash

# スクリプトの冒頭に set -e を追加すると、エラーが発生した時点でスクリプトの実行を停止します
# スクリプトの冒頭に set -x を追加すると、実行するコマンドを自動的に出力します
set -ex

# 削除
rm -f *.o *.so *.out ./test/*.o ./*.so test/*.out

# libcalcurator.so をビルド
g++ -fPIC -Wall -g -c calcurator.cpp
g++ -shared calcurator.o -o libcalcurator.so

# テストプログラム(unit_test.out) をビルド
cd test
g++ -Wall -g -c test_add.cpp test_sub.cpp test_mul.cpp test_div.cpp -I../
g++ -o unit_test.out test_add.o test_sub.o test_mul.o test_div.o -lcalcurator -lgtest_main -lgtest -L../ -Xlinker -rpath -Xlinker ..

# 実行
./unit_test.out

 

./build.sh 実行結果

実行の様子

 

 

3-2. make でビルド

make によるビルド実現方法について記載しておきます。

 

(例1) 1つの makefile によるビルド

ファイル構成

./
 ├ calcurator.h
 ├ calcurator.cpp
 ├ makefile
 └ test
     ├ test_add.cpp
     ├ test_sub.cpp
     ├ test_mul.cpp
     └ test_div.cpp

 

makefile

# コンパイラ
CC = g++

# ソースファイルとオブジェクトファイル (ライブラリ)
TARGET = libcalcurator.so
SRCS = calcurator.cpp
OBJS = $(SRCS:.cpp=.o)

# ソースファイルとオブジェクトファイル (テスト用)
TEST_TARGET = unit_test.out
TEST_SRCS = $(addprefix test/, test_add.cpp test_sub.cpp test_mul.cpp test_div.cpp)
TEST_OBJS = $(TEST_SRCS:.cpp=.o)

# コンパイルフラグ
CFLAGS = -Wall -g -fPIC
LDFLAGS = -shared

# テスト用コンパイルフラグ
TEST_CFLAGS = -Wall -g -I./
TEST_LDFLAGS = -lgtest_main -lgtest -lcalcurator -L. -Xlinker -rpath -Xlinker .

# テスト実行ファイルのビルドルール
test/$(TEST_TARGET): $(TEST_OBJS) $(TARGET)
    $(CC) $(TEST_CFLAGS) -o $@ $(TEST_OBJS) $(TEST_LDFLAGS)

# 共有ライブラリのビルドルール
$(TARGET): $(OBJS)
    $(CC) $(LDFLAGS) -o $@ $^

# オブジェクトファイルのビルドルール
%.o: %.cpp
    $(CC) $(CFLAGS) -c $< -o $@
	
# テスト用オブジェクトファイルのビルドルール
test/%.o: test/%.cpp
    $(CC) $(TEST_CFLAGS) -c $< -o $@

# 全ビルド
.PHONY: all
all: clean $(TARGET) test/$(TEST_TARGET)
    @echo "Build all targets."

# クリーンアップ
.PHONY: clean
clean:
    rm -f $(OBJS) $(TARGET) $(TEST_OBJS) test/$(TEST_TARGET)
    @echo "Clean up all targets."

 

build.sh

#!/bin/bash

# スクリプトの冒頭に set -e を追加すると、エラーが発生した時点でスクリプトの実行を停止します
# スクリプトの冒頭に set -x を追加すると、実行するコマンドを自動的に出力します
set -ex

# 削除
make clean

# ビルド
make

# 実行
./test/unit_test.out

 

 

(例2) 2つの makefile によるビルド

makefile を libcalcurator.so 用とテストプログラムを分離する例です。

makefile(1) から makefile(2) を呼んでいます。

 

ファイル構成

./
 ├ calcurator.h
 ├ calcurator.cpp
 ├ makefile (1)
 └ test
     ├ test_add.cpp
     ├ test_sub.cpp
     ├ test_mul.cpp
     ├ test_div.cpp
     └ makefile (2)

 

makefile (1)

# コンパイラ
CC = g++

# ソースファイルとオブジェクトファイル (ライブラリ)
TARGET = libcalcurator.so
SRCS = calcurator.cpp
OBJS = $(SRCS:.cpp=.o)

# ターゲット
.PHONY: target
target: $(TARGET) test_build

# テスト用のビルド
test_build:
    $(MAKE) -C test

# コンパイルフラグ
CFLAGS = -Wall -g -fPIC
LDFLAGS = -shared

# 共有ライブラリのビルドルール
$(TARGET): $(OBJS)
    $(CC) $(LDFLAGS) -o $@ $^

# オブジェクトファイルのビルドルール
%.o: %.cpp
    $(CC) $(CFLAGS) -c $< -o $@

# 全ビルド
.PHONY: all
all: clean $(TARGET)
    @echo "Build all targets."

# クリーンアップ
.PHONY: clean
clean:
    rm -f $(OBJS) $(TARGET)
    $(MAKE) -C test clean
    @echo "Clean up all targets."

 

makefile (2)

# コンパイラ
CC = g++

# テスト用ターゲット
TEST_TARGET = unit_test.out
TEST_SRCS = $(wildcard *.cpp)
TEST_OBJS = $(TEST_SRCS:.cpp=.o)
LIBCALCURATOR = ../libcalcurator.so

# テスト用コンパイルフラグ
TEST_CFLAGS = -Wall -g -I../
TEST_LDFLAGS = -lgtest_main -lgtest -lcalcurator -L.. -Xlinker -rpath -Xlinker .. -Xlinker -rpath -Xlinker .

# テスト実行ファイルのビルドルール
$(TEST_TARGET): $(TEST_OBJS)
    $(CC) $(TEST_CFLAGS) -o $@ $(TEST_OBJS) $(TEST_LDFLAGS)

# テスト用オブジェクトファイルのビルドルール
%.o: %.cpp
    $(CC) $(TEST_CFLAGS) -c $< -o $@

# 全ビルド
.PHONY: all
all: clean $(TEST_TARGET)
    @echo "Build all test targets."

# クリーンアップ
.PHONY: clean
clean:
    rm -f $(TEST_OBJS) $(TEST_TARGET)
    @echo "Clean up all test targets."

 

build.sh

#!/bin/bash

# スクリプトの冒頭に set -e を追加すると、エラーが発生した時点でスクリプトの実行を停止します
# スクリプトの冒頭に set -x を追加すると、実行するコマンドを自動的に出力します
set -ex

# 削除
make clean

# ビルド
make

# 実行
./test/unit_test.out

 

./build.sh 実行結果

実行結果

 

 

3-3. cmake でビルド

cmake によるビルド実現方法について記載しておきます。

 

ファイル構成

./
 ├ calcurator.h
 ├ calcurator.cpp
 ├ CMakeLists.txt  (1)
 └ test
     ├ test_add.cpp
     ├ test_sub.cpp
     ├ test_mul.cpp
     ├ test_div.cpp
     └ CMakeLists.txt  (2)

 

CMakeLists.txt (1)

cmake_minimum_required(VERSION 3.13)
project(calcurator CXX)

# ライブラリ作成
add_library(calcurator SHARED calcurator.cpp)

# ヘッダーファイルのインクルードディレクトリ
target_include_directories(calcurator PUBLIC ${PROJECT_SOURCE_DIR})

# 最適化・警告等のオプション
target_compile_options(calcurator PUBLIC -Wall -g -fPIC)

# testサブディレクトリも追加
add_subdirectory(test)

 

CMakeLists.txt (2)

# テスト用ソースを自動取得
file(GLOB TEST_SRCS "test_*.cpp")

# テストプログラム作成
add_executable(unit_test.out ${TEST_SRCS})

# ライブラリのリンク
target_link_libraries(unit_test.out PRIVATE calcurator gtest_main gtest)

# インクルードパス
include_directories("${CMAKE_SOURCE_DIR}/..")

# 最適化・警告等のオプション
target_compile_options(unit_test.out PRIVATE -Wall -g)

 

build.sh

#!/bin/bash

# スクリプトの冒頭に set -e を追加すると、エラーが発生した時点でスクリプトの実行を停止します
# スクリプトの冒頭に set -x を追加すると、実行するコマンドを自動的に出力します
set -ex

# 削除
rm -rf build

# ビルド
mkdir build
cd build
cmake ..
make

# 実行
./test/unit_test.out

 

 

ライセンス

本ページの情報は、特記無い限り下記 MIT ライセンスで提供されます。

The MIT License (MIT)

  Copyright 2025 Kinoshita Hidetoshi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

 

参考

 


 

変更履歴

2025-11-15 - 3. libcalcurator.so をテストする」を追加
2025-03-04 - 2-3._GoogleTest_を最小限の手間で導入」へ「DOWNLOAD_EXTRACT_TIMESTAMP ON」に関する情報を追記
2024-10-14 - "google test" を "1.15.2" へ更新
  - 2-2._cmake_を使ってみる, 2-3._GoogleTest_を最小限の手間で導入 を追加
2022-06-30 - 新規作成