Google testのインストール、使用方法(Ubuntu 20.04)

参考

[ubuntu]Google Testの導入方法 - Qiita

業務効率化の道具箱(5)Google Testを使ってみよう【その1】:山浦恒央の“くみこみ”な話(158)(3/3 ページ) - MONOist

main関数をテストしたい基地外な人のためのメモ - ひでたそ覚書帳

インストール

$ sudo apt-get install libgtest-dev

検査対象

//テスト対象の関数
int sum(int a, int b){
    return a+b;
}
int sub(int a, int b){
    return a-b;
}

検査コード

カバレッジを見たいので、sum()のみ検査。

#include <main.c>
#include  <gtest/gtest.h>

//テストコード
TEST(TestCase, sum) {
    EXPECT_EQ(2, sum(1,1));        //OK
    EXPECT_EQ(1000, sum(123,877)); //OK
    EXPECT_EQ(-8, sum(-12,3));     //NG
}

ビルド

$ g++ test.c -lgtest_main -lgtest -lpthread -I. -o test

以下でテスト実行。

$ ./test
  • 注意点

gccでビルドすると、以下のようなエラーが出る。そのため、g++でビルドすること。

In file included from test.c:2:
/usr/include/gtest/gtest.h:55:10: fatal error: cstddef: No such file or directory
   55 | #include <cstddef>
      |          ^~~~~~~~~
compilation terminated.

ビルド(カバレッジも計測)

以下のように、-fprofile-arcs -ftest-coverageを付けて実行。

$ g++ test.c  -fprofile-arcs  -ftest-coverage -lgtest_main -lgtest -lpthread -I. -o test

$ ./test実行後、以下を実行すると、カバレッジが出る。期待値の50%が得られている。

$ gcov -b test.gcda 
...
File 'main.c'
Lines executed:50.00% of 4
Creating 'main.c.gcov'

後片付け

$ rm *.gcov *.gcda *.gcno

main()関数もテストする

検査対象

//テスト対象の関数
int sum(int a, int b){
    return a+b;
}

int sub(int a, int b){
    return a-b;
}

int main(){
    return sum(1, 2);
}

検査コード

// エントリーポイントをリネーム
#define main _old_main

// テストしたいコードを取り込み
#include "main.c"

// エントリーポイントを test_main に変更
#undef main
#define test_main main
#include  <gtest/gtest.h>

//テストコード
TEST(TestCase, sum) {
    EXPECT_EQ(2, sum(1,1));        //OK
    EXPECT_EQ(1000, sum(123,877)); //OK
    EXPECT_EQ(-8, sum(-12,3));     //NG
    EXPECT_EQ(3, _old_main());     //OK
}

// テストのエントリーポイント
int test_main(int argc, char* argv[])
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}