LoginSignup
0
0

【Linux】gtest + lcov でカバレッジを計測する

Posted at

概要

Linux 上で gtest と lcov を用いて、テストパターンに対するカバレッジを計測してみる
ここでは、VSCode で WSL にリモート接続して作業を行う

前提

  • WSL がインストールされていること(手順は下記参照)

  • WSL に gtest がインストールされていること(手順は下記参照)

  • VSCode がインストールされていること

実施手順

lcov をインストールする

WSL 上で下記のコマンドを実行し、lcov をインストールする

sudo apt install lcov

エラーメッセージが表示されなければインストール完了

サンプルコードを作成する

任意のディレクトリに、下記の3ファイルを作成する

sample.c
#include "sample.h"

int is_equal_to_zero( int x ){
    int ret;

    if( x == 0 ){
        ret = 1;
    }
    else{
        ret = 0;
    }
    
    return ret;
}
sample.h
#ifndef SAMPLE_H_
#define SAMPLE_H_

int is_equal_to_zero( int x );

#endif /* SAMPLE_H_ */
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 );
}

ビルドする

上記3ファイルを作成したディレクトリに移動し、以下のコマンドを実行してビルドする

g++ sample.c gtest_sample.cpp -o test -g -pthread -lgtest_main -lgtest -fprofile-arcs -ftest-coverage

image.png
test, test-gtest_sample.gcno, test-sample.gcno の3ファイルが生成されていれば OK

テストを実行する

以下のコマンドを実行して、テストを実行する

./test

image.png
テストログが表示され、test-gtest_sample.gcda, test-sample.gcda の2ファイルが生成されていれば OK

カバレッジを出力する

以下のコマンドを実行して、カバレッジを HTML 形式で出力する

lcov -c -d . -o sample.info
genhtml -o . sample.info

image.png
.html ファイルが出力されていれば OK

カバレッジレポートを見てみる

index.html を開くと、以下のようになっている
image.png
image.png
青の行は実行されている行、赤の行は実行されていない行を示す
今回のサンプルコードでは、sample.c の10行目が実行されていないとわかる

テストケースを追加してカバレッジを上げてみる

gtest_sample.cpp を、以下のように修正する

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 );
}

修正後、ビルドする ~ カバレッジレポートを見てみる の手順を再度実施する
image.png
image.png
先ほど実行されていなかった行が、実行されるようになったことが分かる

0
0
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
0
0