C++用のテストライブラリーGoogle TestをIntel C/C++と一緒に使う。
設定
CMakeをインストールする。
% sudo aptitude install cmake
Google Test本家からソースコードをダウンロードし、解凍する。
% unzip gtest-1.6.0.zip % cd gtest-1.6.0
CMakeでMakefileを生成する。その後、makeで静的ライブラリー libgtest.a と libgtest_main.a を作成する。
% cmake . % CC=icc CXX=icpc make |& tee make.log
うまく準備できたかを確認する。
cd make CC=icc CXX=icpc make ./sample1_unittest
ヘッダーと静的ライブラリーをおいておく場所を作る。
% sudo mkdir -p /usr/local/gtest-1.6.0/lib % sudo cp -r ./include /usr/local/gtest-1.6.0/ % sudo cp libgtest*.a /usr/local/gtest-1.6.0/lib % sudo ln -s /usr/local/gtest-1.6.0 /usr/local/gtest
以上で設定終了。
テストに使う
今日もスミマセン。:Google Test (GoogleのC++向けユニットテストフレームワーク) 使ってみたメモで使われているサンプルコードを用いてテストする。
//
// Test case for Google Test
//
#include <gtest/gtest.h>
int add(int x, int y)
{
  // do nothing.
}
// 1 + 1 の結果は 2 になるはず(..だけど、このコードは失敗する)
TEST(AddTest, Test1)
{
  ASSERT_EQ(2, add(1, 1));
}このファイルをtest.cppとするとき、以下のようにコンパイルする。libgtest_main.a はmain関数を自分で用意する場合には読み込まなくて良い。
% icpc -I/usr/local/gtest/include ./test.cpp /usr/local/gtest/lib/libgtest.a \\
        /usr/local/gtest/lib/libgtest_main.a -lpthread -o test_cpp実際に実行してみる。
% ./test_cpp Running main() from gtest_main.cc [==========] Running 1 test from 1 test case. [----------] Global test environment set-up. [----------] 1 test from AddTest [ RUN ] AddTest.Test1 ./test.cpp:15: Failure Value of: add(1, 1) Actual: 0 Expected: 2 [ FAILED ] AddTest.Test1 (1 ms) [----------] 1 test from AddTest (1 ms total) [----------] Global test environment tear-down [==========] 1 test from 1 test case ran. (1 ms total) [ PASSED ] 0 tests. [ FAILED ] 1 test, listed below: [ FAILED ] AddTest.Test1 1 FAILED TEST
test.cpp の add(int x, int y)の中身をちゃんと作る。
int add(int x, int y)
{
  // do nothing.
  return x+y;
}コンパイルして実行。
% icpc -I/usr/local/gtest/include ./test.cpp /usr/local/gtest/lib/libgtest.a \\
        /usr/local/gtest/lib/libgtest_main.a -lpthread -o test_cpp
% ./test_cpp
Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from AddTest
[ RUN      ] AddTest.Test1
[       OK ] AddTest.Test1 (0 ms)
[----------] 1 test from AddTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 1 test.