2
3

More than 5 years have passed since last update.

CTest でのテスト実行時にファイルを渡す

Posted at

ファイル内容を読み込む関数とか、まぁなんかファイルを必要とするテストケースがあると思うんだけどそれは次のようにすればいける。

読み込むファイルはテストケースを書いた cpp ファイルと同じ場所においておく。で、次のようなテストを書く。ポイントは main 関数の中で引数をグローバル変数に退避して、最後に RUN_ALL_TESTS を呼んでいるところ。

/*
 * ini.cpp
 * */

#include "gtest/gtest.h"

#include "filetype/ini.hpp"

char const * ini01;
char const * ini02;

int main (int argc, char * argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    assert(argc == 3);

    ini01 = argv[1];
    ini02 = argv[2];

    return RUN_ALL_TESTS();
}

TEST(Read, InSuccessWithValidFile) {
    auto settings = FileType::Ini::Read(ini01);
    // snip
}

TEST(Read, InFailureWithInvalidFile) {
    auto settings = FileType::Ini::Read(ini02);
    // snip
}

これを次のように設定してやる。何の事はない、 COMMAND に引数を追加しているだけなんだけど、 ${CMAKE_CURRENT_SOURCE_DIR} の下にあるファイルを指定することでテスト用ファイルが分散しないようにしてるのがちょっとした工夫。

cmake_minimum_required(VERSION 2.8)

add_executable(IniTest ini.cpp)
target_link_libraries(IniTest
    gtest
    gtest_main
    pthread
    gcov
    )

add_test(
    NAME Ini
    COMMAND $<TARGET_FILE:IniTest> "${CMAKE_CURRENT_SOURCE_DIR}/test01.ini" "${CMAKE_CURRENT_SOURCE_DIR}/test02.ini"
    )
2
3
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
2
3