【C++ユニットテスト】Google TestをLinux上のプロジェクトに組み込む方法

C++ユニットテストフレームワークGoogle Test。
以前LinuxへのGoogle Testビルド方法の記事を書いたのですが、Googleのドキュメントによると/usr/localなどへのインストールは本来推奨されていないようです。
よくある質問 — Google Test ドキュメント日本語訳

そこで、プロジェクト内にGoogle Testのソースコードを配置して使用する手順をまとめました。

準備

まずはGoogle Testのダウンロードと展開を済ませておきます。

wget https://googletest.googlecode.com/files/gtest-1.7.0.zip
unzip gtest-1.7.0.zip

Google Test ソースコードのコピー

続いて、Google Testのソースコードをコピーしておきます。 ディレクトリは下記のようにしておきます。環境に合わせて適宜読み替えてください。

  • gtest-1.7.0.zip 展開先:${GTEST_ROOT_DIR}
  • プロジェクトルートディレクトリ:${PROJECT_ROOT_DIR}
  • プロジェクトテストディレクトリ:${PROJECT_ROOT_DIR}/test
cd ${GTEST_ROOT_DIR}
python ./scripts/fuse_gtest_files.py ${PROJECT_ROOT_DIR}/test 

※2番目のPythonスクリプトGoogle Testのソースコードがコピーされます。

テストコードの作成

今回は、mathライブラリのmin, max関数をテストするコードを書いていきます。
プロジェクトのディレクトリ構成は下記のイメージです。

ディレクトリ構成
${PROJECT_ROOT_DIR}
|-- include/
|-- src/
`-- test/
    |-- gtest/
    |   |-- gtest-all.cc
    |   `-- gtest.h
    |-- Makefile
    |-- math_test.cpp    mathライブラリのテストコード
    `-- test.cpp         テストのメイン関数

mathライブラリのテストコードと、それを呼び出すメイン関数を以下のように記述します。

math_test.cpp(mathライブラリのテストコード)
#include <cmath>
#include "gtest/gtest.h"

TEST(MathTest, MinTest) {
    EXPECT_EQ(0, std::min(0,1));
}
TEST(MathTest, MaxTest) {
    EXPECT_EQ(1, std::max(0,1));
}
test.cpp(テストのメイン関数)
#include <stdio.h>
#include "gtest/gtest.h"

GTEST_API_ int main(int argc, char **argv) {
    printf("Running main() from gtest_main.cc\n");
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

最後に、Makefileを以下のように記述します。

Makefile
.PHONY: all clean

.SUFFIXES:
.SUFFIXES: .o .cpp .cc

CXX      =g++
CFLAGS   =-Wall
TARGET   =test
OBJS     =test.o math_test.o gtest/gtest-all.o
HEADERS  =gtest/gtest.h
INCLUDES =
LDFLAGS  =-pthread
LIBS     =

all: $(TARGET)

$(TARGET): $(OBJS)
  $(CXX) -o $@ $(CFLAGS) $(INCLUDES) $(LDFLAGS) $(LIBS) $^

%.o: %.cpp
  $(CXX) -o $(@D)/$(@F) -c $(CFLAGS) $(INCLUDES) $(<D)/$(<F)
%.o: %.cc                                                     
  $(CXX) -o $(@D)/$(@F) -c $(CFLAGS) $(INCLUDES) $(<D)/$(<F)

test.o: test.cpp $(HEADERS) Makefile
math_test.o: math_test.cpp $(HEADERS) Makefile

gtest/gtest-all.o: gtest/gtest-all.cc $(HEADERS) Makefile

clean:
  rm -f $(TARGET) $(OBJS)

テストの実行

あとは以下のコマンドでテストをコンパイルして実行します。

テスト実行
cd ${PROJECT_ROOT_DIR}/test
make
./test
実行結果
[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from MathTest
[ RUN      ] MathTest.MinTest
[       OK ] MathTest.MinTest (0 ms)
[ RUN      ] MathTest.MaxTest
[       OK ] MathTest.MaxTest (0 ms)
[----------] 2 tests from MathTest (0 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran. (0 ms total)
[  PASSED  ] 2 tests.

以上。


参考にしたサイト