Skip to content

Google Test

Junya Nakahodo edited this page May 26, 2022 · 2 revisions

Google Test導入

準備

Makefile

INCLUDE   := -I ./src/request -I ./src/response -I ./src/socket -I ./src/event -I(テストするhppファイルがあるディレクトリへのパス)
test_compile = clang++ -std=c++11 \
	$(testdir)/gtest.cpp $(gtestdir)/googletest-release-1.11.0/googletest/src/gtest_main.cc $(gtestdir)/gtest/gtest-all.cc (テストするcppファイル)\
	-I$(gtestdir) $(INCLUDE) -lpthread -o tester
  • INCLUDEにディレクトリ(テストするhppファイルを含む)へのパスを設定
  • テストするcppファイルをコンパイルする

テストの書き方

基本的にはtest/gtest.cpp内で自分のテスト.cppを展開する

test/gtest.cpp

#include <gtest/gtest.h>

/* Include all tests files */

#include "test_className.cpp" // 自作のテストケースが書かれたファイル(test_クラス名.cpp)
#include "test_hoge.cpp"
#include "test_var.cpp"

例) hogeクラスをテストする場合

hoge.hpp

class Hoge {
public:
    Hoge(){}
    Hoge(int num) { num_ = num; }
    ~Hoge(){}
    int getNum() { return num_; }
private:
    int num_;
};

test_hoge.cpp

#include <gtest/gtest.h> // TESTマクロなどが定義されているgtest.hをインクルード

#include <hoge.hpp> // テストするクラスが含まれるファイルをインクルード

TEST(Hoge, GetNum) // TESTマクロ 第一引数にクラス名、第二引数にメソッド、UpperCamelで書く
{
    {
        hoge h(42);

        EXPECT_EQ(42, h.getNum()); // EXPECT_EQマクロ 第一引数に期待する値、第二引数に実際の値、等しいときOK
    }
}
  • TESTマクロ以外にもTEST_Fなどのマクロが存在する
  • EXPECT_EQ以外にもEXPECT_NEやEXPECT_TRUEなどのマクロが存在する

詳しくは google test 入門

実行

$ make gtest

Clone this wiki locally