13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Google testを試してみた

Last updated at Posted at 2014-03-05

C++でもテストができるようにGoogle Testを試してみた。

インストール

参考にしたのはこのページ:
http://qiita.com/kuchida1981/items/9bb8fa4cc04635e7e909

以下のように標準的な手順でインストールできる

  • gtestをダウンロード
  • cmake, make でビルド

テストの実行方法

インクルードパスを通して、gtest.a, gtest_main.a とリンクすればテストを行う実行ファイルがビルドされる。

ビルド方法は以下のようになる。(gtestへのパスは各自の環境ごとに設定すること)

export GTEST_HEADER_PATH=/path/to/gtest-1.7.0/include
export GTEST_BUILD_PATH=/path/to/gtest-1.7.0/build
g++ MyLib.cc MyLibTest.cc -I#{GTEST_HEADER_PATH} -L#{GTEST_BUILD_PATH} -lgtest -lgtest_main
EXPECT_EQ( my_queue.pop(), 10 );
EXPECT_LT( my_queue.size(), 3 );

fixtureの書き方

  • 複数のテスト間で共通処理をするためにfixtureクラスを用意する。
    • rspecでいうところの before, after などのフック処理を定義できる。
  • ::testing::Test クラスを継承したクラスを作る。このクラスのメンバにはテストケースからアクセス可能になる。
    • SetUp(), TearDown() などテスト前後の共通処理を定義できる
    • 複数のテストで共通で使える変数を定義できる
    • 共通処理の関数を書くこともできる。その中でアサーションも使える。
  • TEST の代わりに TEST_F マクロを使って、先ほどのFixtureクラスを第一引数にする
class MyTest : public ::testing::Test {
protected:
  virtual void SetUp() {
    double p1 = 0.1;
    double p2 = 0.05;
    m_myclass = new MyClass(p1, p2);
  };
  virtual void TearDown() {
    delete m_myclass;
  };

  MyClass* m_myclass;

  void CommonProcUsedByTests() {
      // something ...
      EXPECT_NE(j, 3);  // you can also write assertion here
    }
  }
};

TEST_F(MyTest, TestCaseA) {
  CommonProcUsedByTests();
  EXPECT_EQ( m_myclass.foo(), 1 );
}

privateメンバーのテスト方法

概要は以下の通り。

  • fixtureクラスを用意する
  • ライブラリの側で、fixtureクラスをfriend指定する
  • fixtureクラスの関数内でassertionを呼ぶ。
  • TEST_F マクロ内でその関数を呼ぶ

詳細はここを参照。

13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?