Google Test の使い方 (Ubuntu)

 

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

 

 

 

1. Google Test をインストール

[概要]

Github から一式を取得後、cmake、make、make install します。

 

[環境]

OS : Ubunsu, 20.04 (WSL)

 

 

1-1. ソースをダウンロード

Google Test のリポジトリはこちらです。

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

 

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

Releases · google/googletest (github.com)

 

 

1-2. Google Test をビルド

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

 

$ mkdir temp
$ cd temp 
$ wget https://github.com/google/googletest/archive/release-1.12.0.tar.gz
$ tar zxvf release-1.12.0.tar.gz 
$ cd /usr/local/src/googletest-release-1.12.0 
$ 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. Google Test の使い方

 

2-1. 簡単に Google Test する

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

今回試すコードは以下のような感じです。

 

["test_gtest.cpp"]

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

 

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

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

 

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

Google Test 実行例

 

 

まず CMakeLists.txt を作成します。こんな感じ。これをベースに必要な修正を行っていきます。

["CMakeLists.txt"]

# 基本的な設定
cmake_minimum_required(VERSION 3.13)

project(test_project)

# Google Test ライブラリを探す
find_package(GTest)

# 今回作成する実行ファイル test_project, ソースファイルは main.cpp のみ
add_executabule(test_project main.cpp)

# gtest, pthread をリンクします
target_link_library(test_project ${GTEST_BOTH_LIBRARY} pthread)
target_include_directories(test_project PUBLIC ${GTEST_INCLUDE_DIRS})

 

GTEST_BOTH_LIBRARY については下記資料を参照。

https://cmake.org/cmake/help/v3.18/module/FindGTest.html

 

 

ライセンス

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

The MIT License (MIT)

Copyright © 2022 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.

 

 


参考

 


 

変更履歴

2022-06-30 - 新規作成