概要
Linux 上で gtest と lcov を用いて、テストパターンに対するカバレッジを計測してみる
ここでは、VSCode で WSL にリモート接続して作業を行う
前提
- WSL がインストールされていること(手順は下記参照)
- WSL に gtest がインストールされていること(手順は下記参照)
- VSCode がインストールされていること
実施手順
lcov をインストールする
WSL 上で下記のコマンドを実行し、lcov をインストールする
sudo apt install lcov
エラーメッセージが表示されなければインストール完了
サンプルコードを作成する
任意のディレクトリに、下記の3ファイルを作成する
#include "sample.h"
int is_equal_to_zero( int x ){
int ret;
if( x == 0 ){
ret = 1;
}
else{
ret = 0;
}
return ret;
}
#ifndef SAMPLE_H_
#define SAMPLE_H_
int is_equal_to_zero( int x );
#endif /* SAMPLE_H_ */
#include <gtest/gtest.h>
#include "sample.h"
TEST( test_is_equal_to_zero, case_zero ) {
int arg = 0;
int ret = 0;
// input
arg = 0;
// テスト対象関数をコール
ret = is_equal_to_zero( arg );
// アサーション
EXPECT_EQ( ret, 1 );
}
ビルドする
上記3ファイルを作成したディレクトリに移動し、以下のコマンドを実行してビルドする
g++ sample.c gtest_sample.cpp -o test -g -pthread -lgtest_main -lgtest -fprofile-arcs -ftest-coverage
test, test-gtest_sample.gcno, test-sample.gcno の3ファイルが生成されていれば OK
テストを実行する
以下のコマンドを実行して、テストを実行する
./test
テストログが表示され、test-gtest_sample.gcda, test-sample.gcda の2ファイルが生成されていれば OK
カバレッジを出力する
以下のコマンドを実行して、カバレッジを HTML 形式で出力する
lcov -c -d . -o sample.info
genhtml -o . sample.info
カバレッジレポートを見てみる
index.html を開くと、以下のようになっている
青の行は実行されている行、赤の行は実行されていない行を示す
今回のサンプルコードでは、sample.c の10行目が実行されていないとわかる
テストケースを追加してカバレッジを上げてみる
gtest_sample.cpp を、以下のように修正する
#include <gtest/gtest.h>
#include "sample.h"
TEST( test_is_equal_to_zero, case_zero ) {
int arg = 0;
int ret = 0;
// input
arg = 0;
// テスト対象関数をコール
ret = is_equal_to_zero( arg );
// アサーション
EXPECT_EQ( ret, 1 );
}
TEST( test_is_equal_to_zero, case_one ) {
int arg = 0;
int ret = 0;
// input
arg = 1;
// テスト対象関数をコール
ret = is_equal_to_zero( arg );
// アサーション
EXPECT_EQ( ret, 0 );
}
修正後、ビルドする ~ カバレッジレポートを見てみる の手順を再度実施する
先ほど実行されていなかった行が、実行されるようになったことが分かる