.. _primer: ======= 入門ガイド ======= .. Getting started with Google C++ Testing Framework *Google C++ Testing Frameworkをはじめよう* .. Introduction: Why Google C++ Testing Framework? .. Setting up a New Test Project .. Basic Concepts .. Assertions .. Basic Assertions .. Binary Comparison .. String Comparison .. Simple Tests .. Test Fixtures: Using the Same Data Configuration for Multiple Tests .. Invoking the Tests .. Writing the main() Function .. Important note for Visual C++ users .. Where to Go from Here .. Known Limitations * :ref:`primer_introduction` * :ref:`primer_settingup` * :ref:`primer_basic_concepts` * :ref:`primer_assertions` * :ref:`primer_basic_assertions` * :ref:`primer_binary_comparison` * :ref:`primer_string_comparison` * :ref:`primer_simple_tests` * :ref:`primer_test_fixtures` * :ref:`primer_invoking_the_tests` * :ref:`primer_writing_the_main` * :ref:`primer_important_note_4vc` * :ref:`primer_where_to_go` * :ref:`primer_known_limitations` .. Introduction: Why Google C++ Testing Framework? .. _primer_introduction: はじめに:なぜ Google C++ Testing Frameworkを使うのか ===================================== .. Google C++ Testing Framework helps you write better C++ tests. *Google C++ Testing Framework* を上手に活用すれば,より良い C++ のテストを書くことができます. .. No matter whether you work on Linux, Windows, or a Mac, if you write C++ code, Google Test can help you. Linux,Windows,そして Mac,あなたが C++ のコードを書いているこれらの環境に関係なく Google Test を利用できます. .. So what makes a good test, and how does Google C++ Testing Framework fit in? We believe: では,優れたテストを書くにはどうすればよいのでしょうか?Google C++ Testing Framework は,どのように役立つのでしょうか?我々は次のように考えています: .. Tests should be independent and repeatable. It's a pain to debug a test that succeeds or fails as a result of other tests. Google C++ Testing Framework isolates the tests by running each of them on a different object. When a test fails, Google C++ Testing Framework allows you to run it in isolation for quick debugging. .. Tests should be well organized and reflect the structure of the tested code. Google C++ Testing Framework groups related tests into test cases that can share data and subroutines. This common pattern is easy to recognize and makes tests easy to maintain. Such consistency is especially helpful when people switch projects and start to work on a new code base. .. Tests should be portable and reusable. The open-source community has a lot of code that is platform-neutral, its tests should also be platform-neutral. Google C++ Testing Framework works on different OSes, with different compilers (gcc, MSVC, and others), with or without exceptions, so Google C++ Testing Framework tests can easily work with a variety of configurations. (Note that the current release only contains build scripts for Linux - we are actively working on scripts for other platforms.) .. When tests fail, they should provide as much information about the problem as possible. Google C++ Testing Framework doesn't stop at the first test failure. Instead, it only stops the current test and continues with the next. You can also set up tests that report non-fatal failures after which the current test continues. Thus, you can detect and fix multiple bugs in a single run-edit-compile cycle. .. The testing framework should liberate test writers from housekeeping chores and let them focus on the test content. Google C++ Testing Framework automatically keeps track of all tests defined, and doesn't require the user to enumerate them in order to run them. .. Tests should be fast. With Google C++ Testing Framework, you can reuse shared resources across tests and pay for the set-up/tear-down only once, without making tests depend on each other. #. テストには, *独立性* と *再現性* が必要です.別のテストの結果に依存して成功したり失敗したりするテスト,をデバッグするのは非常に面倒な作業です.Google C++ Testing Framework は,各テストを異なるオブジェクト上で実行することによって,テストの独立性を保ちます.Google C++ Testing Framework は,これらを独立に実行するので,テストが失敗したときに迅速なデバッグが行えます. #. テストは,よく *整理され* ,かつテストコードの構造を反映したものであるべきです.Google C++ Testing Framework は,関連するテスト同士を,データとサブルーチンを共有するテストケースとしてグループ化します.これにより,テストを理解しやすくなり,メンテナンスが簡単になります.このような一貫性は,プロジェクトが変わって新たなコードを扱い始める人にとっては,特に役立ちます. #. テストは, *移植性* があり再利用できるものであるべきです.オープンソースのコミュニティには,プラットフォームに依存しないコードが多くあり,それらのテストもプラットフォーム非依存であるべきです.Google C++ Testing Framework は,様々な OS やコンパイラ(gcc,MSVC など)上で,例外を使用するかしないかに関係なく動作します.よって,Google C++ Testing Framework のテストでは,様々な動作条件を簡単に試すことができます.(ただし,現在のリリースでは,Linux用のビルドスクリプトのみが付属します.ほかのプラットフォーム用のスクリプトも鋭意開発中です.) #. テストが失敗した場合,その問題に関する *情報* をできるだけ多く出力するべきです.Google C++ Testing Framework は,最初にテストが失敗した箇所では停止しません.代わりに,現在のテストを停止して,次のテストに移ります.また,致命的ではない失敗をレポートして,そのまま現在のテストを続けるように設定することもできます.したがって,1回の「実行-編集-コンパイル」サイクルで複数のバグを検出して修正することができます. #. Testing Framework は,テストを書くユーザがテスト内容に集中できるようにするものです.つまり,それ以外の雑多な作業をユーザにさせてはいけません.Google C++ Testing Framework は,定義されたすべてのテストを自動的に追跡するので,ユーザがそれらを実行順に並べたりする必要はありません. #. テストは *高速* に動作するべきです.Google C++ Testing Framework を使えば,共有リソースを再利用することができ,互いに依存しあうようなテストを作らずに,開始/終了のための処理は1度行うだけで済みます. .. Since Google C++ Testing Framework is based on the popular xUnit architecture, you'll feel right at home if you've used JUnit or PyUnit before. If not, it will take you about 10 minutes to learn the basics and get started. So let's go! Google C++ Testing Framework は,有名な xUnit アーキテクチャに基づいているので,以前に JUnit や PyUnit を使ったことがあれば,すぐに馴染むことができるでしょう.もし使ったことがなくても,10分もあれば基本を学んで使い始めることができるようになります.さぁ,では始めましょう. .. Note: We sometimes refer to Google C++ Testing Framework informally as Google Test. *注意* : Google C++ Testing Framework を,Google Test と呼ぶ場合もあります. .. Setting up a New Test Project .. _primer_settingup: 新しいテストプロジェクトを開始する ====================== .. To write a test program using Google Test, you need to compile Google Test into a library and link your test with it. We provide build files for some popular build systems: (msvc/ for Visual Studio, xcode/ for Mac Xcode, make/ for GNU make, codegear/ for Borland C++ Builder, scons/ for Scons, and the autotools script in the Google Test root directory). If your build system is not on this list, you can take a look at make/Makefile to learn how Google Test should be compiled (basically you want to compile src/gtest-all.cc with GTEST_ROOT and GTEST_ROOT/include in the header search path, where GTEST_ROOT is the Google Test root directory). Google Test を使ったテストプログラムを書くには,Google Test をライブラリとしてコンパイルし,それをテストにリンクする必要があります.有名なビルドシステム用のビルドファイルが用意されています:(Visual Studio 用の msvc/,Mac XCode 用の xcode/,GNU make 用の make/,Borland C++ Builder 用の codegear/,Scons 用の scons/,そして Google Test ルートディレクトリにある autotools スクリプト).あなたのビルドシステムがリストない場合,make/Makefile を見て,Google Test がどのようにコンパイルされるかを調べることができます. (通常,GTEST_ROOT および GTEST_ROOT/include をインクルードパスに入れて,src/gtest-all.cc をコンパイルします.ここで,GTEST_ROOT は Google Test のルートディレクトリです). .. Once you are able to compile the Google Test library, you should create a project or build target for your test program. Make sure you have GTEST_ROOT/include in the header search path so that the compiler can find "gtest/gtest.h" when compiling your test. Set up your test project to link with the Google Test library (for example, in Visual Studio, this is done by adding a dependency on gtest.vcproj). Google Test ライブラリをコンパイルできれば,後はプロジェクトを作成したり,テストプログラム用のターゲットをビルドしたりできるでしょう.コンパイル時にコンパイラが "gtest/gtest.h" を見つけられるように,GTEST_ROOT/include がインクルードパスに含まれていることを確認してください.また,Google Test ライブラリをリンクするようにプロジェクトを設定してください(例えば,Visual Studio の場合,gtest.vcproj への依存を追加することで実現できます). .. If you still have questions, take a look at how Google Test's own tests are built and use them as examples. まだ分からないことがあれば,Google Test 自身のテストがどのようにビルドされ,どのように使われているかを調べてみてください. .. Basic Concepts .. _primer_basic_concepts: 基本コンセプト ========= .. When using Google Test, you start by writing assertions, which are statements that check whether a condition is true. An assertion's result can be success, nonfatal failure, or fatal failure. If a fatal failure occurs, it aborts the current function; otherwise the program continues normally. Google Test を利用する場合,アサーション,つまり,ある条件が真かどうかを調べる文,を書くところから始まります.アサーションの結果には,成功,致命的ではない失敗,致命的な失敗,があります.致命的な失敗が起きた場合は,現在実行中の関数が中断され,それ以外の場合は,通常通りプログラムが続行されます. .. Tests use assertions to verify the tested code's behavior. If a test crashes or has a failed assertion, then it fails; otherwise it succeeds. *テスト* は,アサーションを利用してテスト対象コードの動作を検証します.テストがクラッシュしたり,アサーションが失敗したりした場合,テスト自体が *失敗* となります.それ以外の場合は,テスト成功となります. .. A test case contains one or many tests. You should group your tests into test cases that reflect the structure of the tested code. When multiple tests in a test case need to share common objects and subroutines, you can put them into a test fixture class. 1つの *テストケース* には,1つまたは複数のテストが含まれます.テスト対象コードの構造を反映するように,テストをテストケースとしてグループ化してください.1つのテストケースに複数のテストが含まれており,共通のオブジェクトやサブルーチンを共有する必要がある場合,それをテストフィクスチャクラスに書くことができます. .. A test program can contain multiple test cases. 1つの *テストプログラム* は,複数のテストケースを含むことができます. .. We'll now explain how to write a test program, starting at the individual assertion level and building up to tests and test cases. では,個々のアサーションレベルから始めて,テスト,テストケースと段階的に進むことで,テストプログラムの書き方を説明していきます. .. Assertions .. _primer_assertions: アサーション ======== .. Google Test assertions are macros that resemble function calls. You test a class or function by making assertions about its behavior. When an assertion fails, Google Test prints the assertion's source file and line number location, along with a failure message. You may also supply a custom failure message which will be appended to Google Test's message. Google Test のアサーションはマクロであり,関数呼び出しと似たようなものです.クラスや関数のテストを行うには,それの動作を調べるアサーションを定義します.アサーションが失敗すると,Google Test は失敗を知らせるメッセージと共に,アサーションのソースファイルと失敗した箇所の行番号を出力します.また,Google Test のメッセージに追加する形で,ユーザ定義の失敗メッセージを出力することもできます. .. The assertions come in pairs that test the same thing but have different effects on the current function. ASSERT_* versions generate fatal Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails. 現在実行中の関数で同じテストを行っても,その挙動が異なるアサーションが存在します.ASSERT_* バージョンが失敗した場合,致命的な失敗となり, **現在実行中の関数を中断します.** EXPECT_* バージョンでは,致命的ではない失敗となり,関数を中断することはありません.1度のテストで複数の失敗を報告できるので,通常はEXPECT_* が好まれます.しかし,問題のアサーションが失敗した後にプログラムを続行しても意味がない場合は,ASSERT_* を利用してください. .. Since a failed ASSERT_* returns from the current function immediately, possibly skipping clean-up code that comes after it, it may cause a space leak. Depending on the nature of the leak, it may or may not be worth fixing - so keep this in mind if you get a heap checker error in addition to assertion errors. ASSERT_*が失敗すると,その関数から直ちに戻るので,その後に実行されるはずだった後処理のコードをスキップしてしまう可能性があります.これは,メモリリークの原因になる可能性があります.これを修正する価値があるか否かは,リークの種類に依存します.アサーションエラーに加えてヒープエラーも調べる場合は,このことを覚えておいてください. .. To provide a custom failure message, simply stream it into the macro using the << operator, or a sequence of such operators. An example: ユーザ定義の失敗メッセージを出力するには,単に<<演算子を用いて,そのメッセージをストリームに出力するだけです.以下に例を示します: .. code-block:: c ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length"; for (int i = 0; i < x.size(); ++i) { EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i; } .. Anything that can be streamed to an ostream can be streamed to an assertion macro--in particular, C strings and string objects. If a wide string (wchar_t*, TCHAR* in UNICODE mode on Windows, or std::wstring) is streamed to an assertion, it will be translated to UTF-8 when printed. ostreamに出力できるものは,アサーションマクロにも出力できます.具体的には,Cの文字列やstringオブジェクトなどです.ワイド文字列(Windows環境のUNICODEのwchar_t*, TCHAR*,あるいはstd::wstring)をアサーション文字列として利用する場合,出力時にUTF-8に変換されます .. Basic Assertions .. _primer_basic_assertions: 基本的なアサーション ============= .. These assertions do basic true/false condition testing. これらのアサーションは,基本的な true/false 条件のテストを行います. .. Fatal assertion Nonfatal assertion Verifies .. ASSERT_TRUE(condition); EXPECT_TRUE(condition); condition is true .. ASSERT_FALSE(condition); EXPECT_FALSE(condition); condition is false .. csv-table:: :header: 致命的なアサーション, 致命的ではないアサーション, 検証内容 :widths: 30,30,15 ASSERT_TRUE(condition);, EXPECT_TRUE(condition);, condition が true ASSERT_FALSE(condition);, EXPECT_FALSE(condition);, condition が false .. Remember, when they fail, ASSERT_* yields a fatal failure and returns from the current function, while EXPECT_* yields a nonfatal failure, allowing the function to continue running. In either case, an assertion failure means its containing test fails. ASSERT_* が失敗した場合は,致命的な失敗となって現在の関数から戻ります.EXPECT_* の場合は,致命的ではない失敗となり,関数はそのまま実行されます.このことを忘れないでください.いずれにせよ,アサーションが失敗するということは,テストが失敗するということを意味します. .. Availability: Linux, Windows, Mac. *利用可能な環境:* Linux,Windows,Mac. .. Binary Comparison .. _primer_binary_comparison: 2つの値の比較 ========= .. This section describes assertions that compare two values. ここでは,2つの値を比較するアサーションについて述べます. .. Fatal assertion Nonfatal assertion Verifies .. ASSERT_EQ(expected, actual); EXPECT_EQ(expected, actual); expected == actual .. ASSERT_NE(val1, val2); EXPECT_NE(val1, val2); val1 != val2 .. ASSERT_LT(val1, val2); EXPECT_LT(val1, val2); val1 < val2 .. ASSERT_LE(val1, val2); EXPECT_LE(val1, val2); val1 <= val2 .. ASSERT_GT(val1, val2); EXPECT_GT(val1, val2); val1 > val2 .. ASSERT_GE(val1, val2); EXPECT_GE(val1, val2); val1 >= val2 .. csv-table:: :header: 致命的なアサーション, 致命的ではないアサーション, 検証内容 :widths: 30, 30, 15 "ASSERT_EQ(expected, actual);", "EXPECT_EQ(expected, actual);", "expected == actual" "ASSERT_NE(val1, val2);", "EXPECT_NE(val1, val2);", "val1 != val2" "ASSERT_LT(val1, val2);", "EXPECT_LT(val1, val2);", "val1 < val2" "ASSERT_LE(val1, val2);", "EXPECT_LE(val1, val2);", "val1 <= val2" "ASSERT_GT(val1, val2);", "EXPECT_GT(val1, val2);", "val1 > val2" "ASSERT_GE(val1, val2);", "EXPECT_GE(val1, val2);", "val1 >= val2" .. In the event of a failure, Google Test prints both val1 and val2 . In ASSERT_EQ* and EXPECT_EQ* (and all other equality assertions we'll introduce later), you should put the expression you want to test in the position of actual, and put its expected value in expected, as Google Test's failure messages are optimized for this convention. Google Test は失敗時に, val1 と val2 の両方を出力します.ASSERT_EQ* と EXPECT_EQ* (および,これ以降で紹介するすべての等号評価アサーション)では,テストしたい式を actual の位置に,期待する値を expected の位置に書きます.Google Test の失敗メッセージは,この順序を前提として出力されます. .. Value arguments must be comparable by the assertion's comparison operator or you'll get a compiler error. We used to require the arguments to support the << operator for streaming to an ostream, but it's no longer necessary since v1.6.0 (if << is supported, it will be called to print the arguments when the assertion fails; otherwise Google Test will attempt to print them in the best way it can. For more details and how to customize the printing of the arguments, see this Google Mock recipe.). 引数の値は,アサーションの比較演算子によって比較可能なものでなければいけません.そうでない場合は,コンパイルエラーになります.通常,ostream に出力するための << 演算子をサポートする引数が必要ですが,v1.6.0以降では必須ではなくなりました.(もし << がサポートされている場合は,アサーション失敗時の出力用にそれが呼ばれます.そうでない場合は,Google Test は,最適な方法で出力を行おうとします.これの詳細および引数の出力をカスタマイズする方法については,Google Mock レシピを参照してください). .. These assertions can work with a user-defined type, but only if you define the corresponding comparison operator (e.g. ==, <, etc). If the corresponding operator is defined, prefer using the ASSERT_*() macros because they will print out not only the result of the comparison, but the two operands as well. これらのアサーションは,対応する比較演算子(例えば,==, <, など)を定義すれば,ユーザ定義型に対しても動作します.対応する演算子が定義されていれば,ASSERT_*() マクロを使う方が良いでしょう.比較結果に加えて2つのオペランドも表示するからです. .. Arguments are always evaluated exactly once. Therefore, it's OK for the arguments to have side effects. However, as with any ordinary C/C++ function, the arguments' evaluation order is undefined (i.e. the compiler is free to choose any order) and your code should not depend on any particular argument evaluation order. 引数は,常に1回だけ評価されます.したがって,引数に副作用があっても問題ありません.しかし,通常の C/C++ 関数と同様に,引数の評価順序は未定義(つまり,コンパイラ依存)です.よって,引数の特定の評価順に依存するようなコードを書いてはいけません. .. ASSERT_EQ() does pointer equality on pointers. If used on two C strings, it tests if they are in the same memory location, not if they have the In particular, to assert that a C string is NULL, use ASSERT_STREQ(NULL, c_string) . However, to compare two string objects, you should use ASSERT_EQ. ASSERT_EQ() は,ポインタに対しては,ポインタが等しいか否かを評価します.2つの C 文字列に対しては,文字列の内容ではなくメモリのアドレスが等しいか否かをテストします.したがって,C 文字列(例えば,const char*)を,その値で比較したい場合は,後述の ASSERT_STREQ() を利用してください.特に,C文字列が NULL の場合は,ASSERT_STREQ(NULL, c_string) を利用します.しかし,2つの string オブジェクトを比較する場合は,ASSERT_EQ を利用する必要があります. .. Macros in this section work with both narrow and wide string objects (string and wstring). ここで説明したマクロは,通常の文字列およびワイド文字列(string と wstring)に対して動作します. .. Availability: Linux, Windows, Mac. *利用可能な環境:* Linux,Windows,Mac. .. String Comparison .. _primer_string_comparison: 文字列の比較 ======== .. The assertions in this group compare two C strings. If you want to compare two string objects, use EXPECT_EQ, EXPECT_NE, and etc instead. ここでは,2つの **C 文字列** を比較するアサーションについて説明します.2つの string オブジェクトを比較したい場合は,EXPECT_EQ,EXPECT_NE,などを代わりに利用してください. .. .. Fatal assertion Nonfatal assertion Verifies .. ASSERT_STREQ(expected_str, actual_str); EXPECT_STREQ(expected_str, actual_str); the two C strings have the same content .. ASSERT_STRNE(str1, str2); EXPECT_STRNE(str1, str2); the two C strings have different content .. ASSERT_STRCASEEQ(expected_str, actual_str); EXPECT_STRCASEEQ(expected_str, actual_str); the two C strings have the same content, ignoring case .. ASSERT_STRCASENE(str1, str2); EXPECT_STRCASENE(str1, str2); the two C strings have different content, ignoring case .. csv-table:: :header: 致命的なアサーション, 致命的ではないアサーション, 検証内容 :widths: 15,15,15 "ASSERT_STREQ(expected_str, actual_str);", "EXPECT_STREQ(expected_str, actual_str);", "2つの C 文字列の内容が等しい" "ASSERT_STRNE(str1, str2);", "EXPECT_STRNE(str1, str2);", "2つの C 文字列の内容が等しくない" "ASSERT_STRCASEEQ(expected_str, actual_str);", "EXPECT_STRCASEEQ(expected_str, actual_str);", "大文字小文字を無視した場合,2つの C 文字列の内容が等しい" "ASSERT_STRCASENE(str1, str2);", "EXPECT_STRCASENE(str1, str2);", "大文字小文字を無視した場合,2つの C 文字列の内容が等しくない" .. Note that "CASE" in an assertion name means that case is ignored. 名前に"CASE"と付いているアサーションは,引数の大文字小文字の区別をしないことに注意してください. .. *STREQ* and *STRNE* also accept wide C strings (wchar_t*). If a comparison of two wide strings fails, their values will be printed as UTF-8 narrow strings. \*STREQ\* と \*STRNE\* も,C文字列(wchar_t*)を引数にとります.2つのワイド文字列の比較が失敗した場合,それらの値は UTF-8 の文字列として出力されます. .. A NULL pointer and an empty string are considered different. NULL ポインタと空文字は,別のものとして区別されます. .. Availability: Linux, Windows, Mac. *利用可能な環境:* Linux,Windows,Mac. .. See also: For more string comparison tricks (substring, prefix, suffix, and regular expression matching, for example), see the [AdvancedGuide Advanced Google Test Guide]. 参考:より詳細な文字列比較の方法(例えば,部分文字列,接頭語,接尾語,正規表現一致など)については, :ref:`advancedguide` を参照してください. .. Simple Tests .. _primer_simple_tests: 簡単なテスト =========== .. To create a test: テストの作成方法: .. Use the TEST() macro to define and name a test function, These are ordinary C++ functions that don't return a value. .. In this function, along with any valid C++ statements you want to include, use the various Google Test assertions to check values. .. The test's result is determined by the assertions; if any assertion in the test fails (either fatally or non-fatally), or if the test crashes, the entire test fails. Otherwise, it succeeds. .. TEST(test_case_name, test_name) { .. ... test body ... .. } #. TEST() マクロを利用してテスト関数を定義し,名前を付けます.これらのテスト関数は,値を返さない通常の C++ 関数です. #. この関数内には,有効な C++ の文を自由に書けます.そして,ここで様々な Google Test アサーションを利用して値を検証します. #. アサーションによってテスト結果が決まります.テスト内のアサーションが1つでも失敗する(致命的である,ないにかかわらず),またはテストがクラッシュすると,そのテスト全体が失敗したことになります.それ以外の場合は,テスト成功となります. .. code-block:: c TEST(test_case_name, test_name) { ... test body ... } .. TEST() arguments go from general to specific. The first argument is the name of the test case, and the second argument is the test's name within the test case. Both names must be valid C++ identifiers, and they should not contain underscore (_). A test's full name consists of its containing test case and its individual name. Tests from different test cases can have the same individual name. TEST() の引数は,全体そして詳細,の順序に並んでいます.最初の引数は,テストケースの名前です.2番目の引数は,テストケースに含まれるテストの名前です.両者とも有効な C++ の識別子でなければならず,アンダースコア(_)を含んではいけません.テストケースと個々のテスト名を合わせたものが,テストの完全な名前となります.属するテストケースが別ならば,個々のテスト名として同じ名前を付けることもできます. .. For example, let's take a simple integer function: 例として,整数を引数に取る単純な関数を見てみましょう: .. int Factorial(int n); // Returns the factorial of n .. code-block:: c int Factorial(int n); // nの階乗を返す .. A test case for this function might look like: この関数のテストケースは,例えば次のようになります: .. // Tests factorial of 0. .. TEST(FactorialTest, HandlesZeroInput) { .. EXPECT_EQ(1, Factorial(0)); .. } .. // Tests factorial of positive numbers. .. TEST(FactorialTest, HandlesPositiveInput) { .. EXPECT_EQ(1, Factorial(1)); .. EXPECT_EQ(2, Factorial(2)); .. EXPECT_EQ(6, Factorial(3)); .. EXPECT_EQ(40320, Factorial(8)); .. } .. code-block:: c // 0 の階乗をテスト TEST(FactorialTest, HandlesZeroInput) { EXPECT_EQ(1, Factorial(0)); } // 正の数の階乗をテスト TEST(FactorialTest, HandlesPositiveInput) { EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(2, Factorial(2)); EXPECT_EQ(6, Factorial(3)); EXPECT_EQ(40320, Factorial(8)); } .. Google Test groups the test results by test cases, so logically-related tests should be in the same test case; in other words, the first argument to their TEST() should be the same. In the above example, we have two tests, HandlesZeroInput and HandlesPositiveInput, that belong to the same test case FactorialTest. Google Test は,テスト結果をテストケース毎にグループ化します.ですから,論理的に関連するテストは,同じテストケースに入れられるべきです.言い換えれば,TEST() の最初の引数が同じであるべきです.上述の例では,HandlesZeroInput と HandlesPositiveInput という2つのテストが,同じテストケース FactorialTest に属しています. .. Availability: Linux, Windows, Mac. *利用可能な環境:* Linux,Windows,Mac. .. Test Fixtures: Using the Same Data Configuration for Multiple Tests .. _primer_test_fixtures: テストフィクスチャ:複数のテストで同じデータ設定を使う =================================== .. If you find yourself writing two or more tests that operate on similar data, you can use a test fixture. It allows you to reuse the same configuration of objects for several different tests. 同じようなデータを扱うテストを複数書く場合は,テストフィクスチャを利用することができます.これを使うと,異なるテストに対して同じオブジェクト設定を再利用できます. .. To create a fixture, just: フィクスチャの作り方: .. Derive a class from ::testing::Test . Start its body with protected: or public: as we'll want to access fixture members from sub-classes. .. Inside the class, declare any objects you plan to use. .. If necessary, write a default constructor or SetUp() function to prepare the objects for each test. A common mistake is to spell SetUp() as Setup() with a small u - don't let that happen to you. .. If necessary, write a destructor or TearDown() function to release any resources you allocated in SetUp() . To learn when you should use the constructor/destructor and when you should use SetUp()/TearDown(), read this FAQ entry. .. If needed, define subroutines for your tests to share. #. ::testing::Test クラスからの派生クラスを作ります.フィクスチャの派生クラスからフィクスチャメンバにアクセスしたいので,ここでは protected: または public: でメンバを宣言します. #. 利用する予定のオブジェクトをすべて,クラス内で宣言します. #. 必要に応じて,デフォルトコンストラクタまたは SetUp() 関数を書きます.これは,テスト毎にオブジェクトの準備をするためのものです.よくある失敗は,SetUp() の代わりに,小文字の u- を使って Setup() と書いてしまい,実際には何も起こらない,というものです. #. 必要に応じて,デストラクタまたは TearDown() 関数を書きます.これは,SetUp() で確保されたりソースをすべて解放するためのものです.コンストラクタ/デストラクタ,そしてSetUp()/TearDown() をどのような場合に利用すればよいかについて知りたい場合は,この :ref:`FAQ エントリ ` を参照してください. #. 必要ならば,複数のテストで共有するサブルーチンを書きます. .. When using a fixture, use TEST_F() instead of TEST() as it allows you to access objects and subroutines in the test fixture: フィクスチャを利用する場合,TEST() の代わりに TEST_F() を使ってください.これによって,テストフィクスチャ内のオブジェクトやサブルーチンにアクセスできるようになります: .. TEST_F(test_case_name, test_name) { .. ... test body ... .. } .. code-block:: c TEST_F(test_case_name, test_name) { ... test body ... } .. Like TEST(), the first argument is the test case name, but for TEST_F() this must be the name of the test fixture class. You've probably guessed: _F is for fixture. TEST() と同様に,最初の引数はテストケースの名前ですが,TEST_F() の場合は,これは必ずテストフィクスチャクラスの名前でなければいけません.ご想像の通り,_F はフィクスチャを表します. .. Unfortunately, the C++ macro system does not allow us to create a single macro that can handle both types of tests. Using the wrong macro causes a compiler error. 残念ながら,C++ のマクロシステムでは1種類のマクロで両方のテストに対応することはできません.間違ったマクロを使うと,コンパイルエラーが起こります. .. Also, you must first define a test fixture class before using it in a TEST_F(), or you'll get the compiler error "`virtual outside class declaration`". また,TEST_F() で利用するよりも前に,テストフィクスチャクラスを定義する必要があります.そうしない場合,"virtual outside class declaration" コンパイルエラーが発生します. .. For each test defined with TEST_F(), Google Test will: Google Test は, TEST_F() で定義される各テストに対して次の処理を行います: .. Create a fresh test fixture at runtime .. Immediately initialize it via SetUp() , .. Run the test .. Clean up by calling TearDown() .. .. Delete the test fixture. Note that different tests in the same test case have different test fixture objects, and Google Test always deletes a test fixture before it creates the next one. Google Test does not reuse the same test fixture for multiple tests. Any changes one test makes to the fixture do not affect other tests. #. 実行時に新たなテストフィクスチャを作成します. #. 直後に,SetUp() による初期化を行います. #. テストを実行します. #. TearDown() による後処理を行います. #. テストフィクスチャを削除します.同じテストケース内の別のテストは,それぞれ異なるテストフィクスチャオブジェクトを持つことに注意してください.Google Test は,新たなテストフィクスチャオブジェクトを作成する前に,必ず以前のオブジェクトを削除します.Google Test は,同じテストフィクスチャを複数のテストで使いまわすことはしません.よって,あるテストがフィクスチャを変更しても,それが別のテストに影響することはありません. .. As an example, let's write tests for a FIFO queue class named Queue, which has the following interface: 例として,Queue という名前の FIFO キュークラスのテストを書いてみましょう.そのインタフェースは,次のようになります: .. .. template // E is the element type. .. class Queue { .. public: .. Queue(); .. void Enqueue(const E& element); .. E* Dequeue(); // Returns NULL if the queue is empty. .. size_t size() const; .. ... .. }; .. code-block:: c template // E は要素の型 class Queue { public: Queue(); void Enqueue(const E& element); E* Dequeue(); // queue が空の場合は NULL を返します. size_t size() const; ... }; .. First, define a fixture class. By convention, you should give it the name FooTest where Foo is the class being tested. まず最初に,フィクスチャクラスを定義します.慣例により,FooTest という名前にします.ここで,Foo はテストされるクラスの名前です. .. class QueueTest : public ::testing::Test { .. protected: .. virtual void SetUp() { .. q1_.Enqueue(1); .. q2_.Enqueue(2); .. q2_.Enqueue(3); .. } .. // virtual void TearDown() {} .. Queue q0_; .. Queue q1_; .. Queue q2_; .. }; .. code-block:: c class QueueTest : public ::testing::Test { protected: virtual void SetUp() { q1_.Enqueue(1); q2_.Enqueue(2); q2_.Enqueue(3); } // virtual void TearDown() {} Queue q0_; Queue q1_; Queue q2_; }; .. In this case, TearDown() is not needed since we don't have to clean up after each test, other than what's already done by the destructor. この場合,各テストにおいてデストラクタで行われる以上の後処理は不要なので, TearDown() は必要ありません. .. Now we'll write tests using TEST_F() and this fixture. では,このフィクスチャとTEST_F() を利用してテストを書いてみましょう. .. code-block:: c TEST_F(QueueTest, IsEmptyInitially) { EXPECT_EQ(0, q0_.size()); } TEST_F(QueueTest, DequeueWorks) { int* n = q0_.Dequeue(); EXPECT_EQ(NULL, n); n = q1_.Dequeue(); ASSERT_TRUE(n != NULL); EXPECT_EQ(1, *n); EXPECT_EQ(0, q1_.size()); delete n; n = q2_.Dequeue(); ASSERT_TRUE(n != NULL); EXPECT_EQ(2, *n); EXPECT_EQ(1, q2_.size()); delete n; } .. The above uses both ASSERT_* and EXPECT_* assertions. The rule of thumb is to use EXPECT_* when you want the test to continue to reveal more errors after the assertion failure, and use ASSERT_* when continuing after failure doesn't make sense. For example, the second assertion in the Dequeue test is ASSERT_TRUE(n != NULL), as we need to dereference the pointer n later, which would lead to a segfault when n is NULL. 上述の例では,ASSERT_* と EXPECT_* の両方のアサーションを利用しています.簡単に言えば,アサーション失敗後のエラーも調べるために関数を続行したい場合は EXPECT_* を利用し,アサーション失敗後に続けても意味がない場合は ASSERT_* を利用します.例えば,Dequeue テストの2番目のアサーションは ASSERT_TRUE(n != NULL) となっています.これは,後でポインタ n の参照を外しますが,そこで n が NULL の場合はセグメンテーションフォルトが起こるので,テストを続ける意味がないためです. .. When these tests run, the following happens: これらのテストが実行されると,以下のようなことが起こります: .. Google Test constructs a QueueTest object (let's call it t1 ). .. t1.SetUp() initializes t1 . .. The first test ( IsEmptyInitially ) runs on t1 . .. t1.TearDown() cleans up after the test finishes. .. t1 is destructed. .. The above steps are repeated on another QueueTest object, this time running the DequeueWorks test. #. Google Test は,QueueTest オブジェクトを作成します(これを t1 とします). #. t1.SetUp() が t1 を初期化します. #. t1 に対して最初のテスト(IsEmptyInitially)が実行されます. #. t1.TearDown() がテスト終了後の後処理をします. #. t1 が削除されます. #. 上述のステップが,別の QueueTest オブジェクトでも繰り返されます.今回の場合は,DequeueWorks テストが実行されます. .. Availability: Linux, Windows, Mac. *利用可能な環境:* Linux,Windows,Mac. .. Note: Google Test automatically saves all Google Test flags when a test object is constructed, and restores them when it is destructed. *注意* :Google Test は,テストオブジェクトが生成された時に自動的にすべての Google Test フラグを保存します.そして,オブジェクトが破棄された時にそれらを復元します. .. Invoking the Tests .. _primer_invoking_the_tests: テストの呼び出し =========== .. TEST() and TEST_F() implicitly register their tests with Google Test. So, unlike with many other C++ testing frameworks, you don't have to re-list all your defined tests in order to run them. TEST() と TEST_F() によって定義されたテストは,暗黙のうちに Google Test に登録されます.したがって,他の多くの C++ testing framework とは異なり,定義したテストを実行順にリストアップする必要はありません. .. After defining your tests, you can run them with RUN_ALL_TESTS() , which returns 0 if all the tests are successful, or 1 otherwise. Note that RUN_ALL_TESTS() runs all tests in your link unit -- they can be from different test cases, or even different source files. テストを定義したら,RUN_ALL_TESTS() でテストを実行できます.すべてのテストが成功すれば 0 が返り,そうでなければ 1 が返ります.RUN_ALL_TESTS() は,リンクされたバイナリのすべてのテストを実行することに注意してください.これらのテストは,異なるテストケース,さらには異なるソースファイルから構成される場合もあります. .. When invoked, the RUN_ALL_TESTS() macro: RUN_ALL_TESTS() マクロを呼び出した場合の動作は次のようになります: .. .. Saves the state of all Google Test flags. .. Creates a test fixture object for the first test. .. Initializes it via SetUp(). .. Runs the test on the fixture object. .. Cleans up the fixture via TearDown(). .. Deletes the fixture. .. Restores the state of all Google Test flags. .. Repeats the above steps for the next test, until all tests have run. #. すべての Google Test フラグの状態を保存します. #. 最初のテストのために,テストフィクスチャオブジェクトを作成します. #. SetUp() によって初期化されます. #. フィクスチャオブジェクト上で,最初のテストが実行されます. #. TearDown() によってフィクスチャの後処理が実行されます. #. フィクスチャが削除されます. #. すべてのGoogle Test フラグの状態を復元します. #. 上述のステップを,すべてのテストが実行されるまで繰り返します. .. Similarly, if step 3 generates a fatal failure, step 4 will be skipped. また,ステップ2でテストフィクスチャのコンストラクタが失敗した場合,以降のステップ3-5は意味がないのでスキップされます.同様に,ステップ3で致命的な失敗が発生した場合,ステップ4はスキップされます. .. Important: You must not ignore the return value of RUN_ALL_TESTS(), or gcc will give you a compiler error. The rationale for this design is that the automated testing service determines whether a test has passed based on its exit code, not on its stdout/stderr output; thus your main() function must return the value of RUN_ALL_TESTS(). *重要* :RUN_ALL_TESTS() の戻り値を無視しないでください.無視すれば,gcc ではコンパイルエラーになります.何故このような仕組みなっているかといえば,テストが成功したか否かは自動的に判断されますが,この判断は stdout/stderr 出力ではなく終了コードに基づいているからです.よって,main() 関数は,必ず RUN_ALL_TESTS() の戻り値を返すようにしてください. .. Also, you should call RUN_ALL_TESTS() only once. Calling it more than once conflicts with some advanced Google Test features (e.g. thread-safe death tests) and thus is not supported. また,RUN_ALL_TESTS() を呼び出せるのは1度だけです.2回以上呼び出すと,Google Test の別の機能(例えば,thread-safe death テスト)と衝突します.したがって,そような呼び出しはサポートされていません. .. Availability: Linux, Windows, Mac. *利用可能な環境:* Linux,Windows,Mac. .. Writing the main() Function .. _primer_writing_the_main: main() 関数を書く ============ .. You can start from this boilerplate: まずは,お決まりの形からはじめましょう: .. #include "this/package/foo.h" .. #include "gtest/gtest.h" .. namespace { .. // The fixture for testing class Foo. .. class FooTest : public ::testing::Test { .. protected: .. // You can remove any or all of the following functions if its body .. // is empty. .. FooTest() { .. // You can do set-up work for each test here. .. } .. virtual ~FooTest() { .. // You can do clean-up work that doesn't throw exceptions here. .. } .. // If the constructor and destructor are not enough for setting up .. // and cleaning up each test, you can define the following methods: .. virtual void SetUp() { .. // Code here will be called immediately after the constructor (right .. // before each test). .. } .. virtual void TearDown() { .. // Code here will be called immediately after each test (right .. // before the destructor). .. } .. // Objects declared here can be used by all tests in the test case for Foo. .. }; .. // Tests that the Foo::Bar() method does Abc. .. TEST_F(FooTest, MethodBarDoesAbc) { .. const string input_filepath = "this/package/testdata/myinputfile.dat"; .. const string output_filepath = "this/package/testdata/myoutputfile.dat"; .. Foo f; .. EXPECT_EQ(0, f.Bar(input_filepath, output_filepath)); .. } .. // Tests that Foo does Xyz. .. TEST_F(FooTest, DoesXyz) { .. // Exercises the Xyz feature of Foo. .. } .. } // namespace .. int main(int argc, char **argv) { .. ::testing::InitGoogleTest(&argc, argv); .. return RUN_ALL_TESTS(); .. } .. code-block:: c #include "this/package/foo.h" #include "gtest/gtest.h" namespace { // テスト対象となるクラス Foo のためのフィクスチャ class FooTest : public ::testing::Test { protected: // 以降の関数で中身のないものは自由に削除できます. // FooTest() { // テスト毎に実行される set-up をここに書きます. } virtual ~FooTest() { // テスト毎に実行される,例外を投げない clean-up をここに書きます. } // コンストラクタとデストラクタでは不十分な場合. // 以下のメソッドを定義することができます: virtual void SetUp() { // このコードは,コンストラクタの直後(各テストの直前) // に呼び出されます. } virtual void TearDown() { // このコードは,各テストの直後(デストラクタの直前) // に呼び出されます. } // ここで宣言されるオブジェクトは,テストケース内の全てのテストで利用できます. }; // Abc を行う Foo::Bar() メソッドをテストします. TEST_F(FooTest, MethodBarDoesAbc) { const string input_filepath = "this/package/testdata/myinputfile.dat"; const string output_filepath = "this/package/testdata/myoutputfile.dat"; Foo f; EXPECT_EQ(0, f.Bar(input_filepath, output_filepath)); } // Xyz を行う Foo をテストします. TEST_F(FooTest, DoesXyz) { // Foo の Xyz を検査 } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } .. The ::testing::InitGoogleTest() function parses the command line for Google Test flags, and removes all recognized flags. This allows the user to control a test program's behavior via various flags, which we'll cover in AdvancedGuide. You must call this function before calling RUN_ALL_TESTS(), or the flags won't be properly initialized. ::testing::InitGoogleTest() 関数は,コマンドラインの Google Test フラグを解析して,認識されたフラグを削除します.これによって,ユーザは様々なフラグを介してテストプログラムの挙動を制御することができます.これについては, :ref:`advancedguide` で述べます. この関数は,RUN_ALL_TESTS() よりも前に呼び出す必要があります.そうしない場合,フラグが適切に初期化されません. .. On Windows, InitGoogleTest() also works with wide strings, so it can be used in programs compiled in UNICODE mode as well. Windows 環境では,InitGoogleTest() はワイド文字列に対しても動作するので,UNICODE モードでコンパイルされたプログラムでも利用できます. .. But maybe you think that writing all those main() functions is too much work? We agree with you completely and that's why Google Test provides a basic implementation of main(). If it fits your needs, then just link your test with gtest_main library and you are good to go. しかし,このような main() 関数を書くのは大変すぎると思うかもしれません.確かにその通りなので,Google Test では基本的な main() 関数の実装を用意してあります.これで十分な場合は,テストに gtest_main ライブラリをリンクするだけで利用できます. .. Important note for Visual C++ users .. _primer_important_note_4vc: Visual C++ ユーザのための重大な注意 =========================== .. If you put your tests into a library and your main() function is in a different library or in your .exe file, those tests will not run. The reason is a bug in Visual C++. When you define your tests, Google Test creates certain static objects to register them. These objects are not referenced from elsewhere but their constructors are still supposed to run. When Visual C++ linker sees that nothing in the library is referenced from other places it throws the library out. You have to reference your library with tests from your main program to keep the linker from discarding it. Here is how to do it. Somewhere in your library code declare a function: ライブラリ内部にテストを書いる場合, main() 関数が別のライブラリまたは別の .exe ファイルにあると,これらのテストは実行されません.これは,Visual C++ の `バグ `_ によるものです.テストを定義する際, Google Test は静的なオブジェクトを生成して,それを登録します.これらのオブジェクトはどこからも参照されませんが,オブジェクトのコンストラクタは,本来ならば実行されるはずです.しかし,Visual C++ のリンカは,外部参照されないライブラリであると判断して,リンクを行いません.リンカが無視しないように,メインプログラムから,テストの書かれたライブラリを参照する必要があります. ここでは,その方法について説明します.ライブラリ内のどこかで,次のように関数を宣言します: .. code-block:: c __declspec(dllexport) int PullInMyLibrary() { return 0; } .. If you put your tests in a static library (not DLL) then __declspec(dllexport) is not required. Now, in your main program, write a code that invokes that function: テストを書いたのが(DLLではなく)スタティックライブラリならば, __declspec(dllexport) は不要です.そして,メインプログラムには,この関数を呼び出すコードを書きます: .. code-block:: c int PullInMyLibrary(); static int dummy = PullInMyLibrary(); .. This will keep your tests referenced and will make them register themselves at startup. これにより,外部からの参照が保たれ,テストはスタートアップに登録されます. .. In addition, if you define your tests in a static library, add /OPT:NOREF to your main program linker options. If you use MSVC++ IDE, go to your .exe project properties/Configuration Properties/Linker/Optimization and set References setting to Keep Unreferenced Data (/OPT:NOREF). This will keep Visual C++ linker from discarding individual symbols generated by your tests from the final executable. さらに,テストをスタティックライブラリに書いた場合,メインプログラムのリンカオプションに /OPT:NOREF を追加してください.MSVC++ IDE を利用する場合,.exeプロジェクトのプロパティ/構成プロパティ/リンカ/最適化にある参照の設定を,参照されないデータを保持する (/OPT:NOREF) に変更してください.このようにすることで,Visual C++ のリンカは,最終的な実行ファイルを作る際に,テストによって生成される個々のシンボルを破棄しなくなります. .. There is one more pitfall, though. If you use Google Test as a static library (that's how it is defined in gtest.vcproj) your tests must also reside in a static library. If you have to have them in a DLL, you must change Google Test to build into a DLL as well. Otherwise your tests will not run correctly or will not run at all. The general conclusion here is: make your life easier - do not write your tests in libraries! しかし,落とし穴がもう1つあります.Google Test をスタティックライブラリとして利用する場合(これは,gtest.vcproj内で使われてる方法です),あなたのテストコードもまたスタティックライブラリ内に存在し続けることになります.テストをDLL内部に持つ必要があるならば,必ず Google Test も DLL としてビルドしなおさなければいけません.そうしなければ,テストは正常に動作しないか,もしくはまったく動作しないでしょう.ここで得られる結論はこうです.こういう事で悩みたくないならば,テストをライブラリ内に書かないようにしてください! .. Where to Go from Here .. _primer_where_to_go: 次のステップ ============= .. Congratulations! You've learned the Google Test basics. You can start writing and running Google Test tests, read some samples, or continue with AdvancedGuide, which describes many more useful Google Test features. おめでとうございます!あなたは,Google Test の基本を学び終えました.これで,Google Test でテストを書いて実行できます. :ref:`samples` を読んだり,Google Test のさらに役立つ機能について書かれた :ref:`advancedguide` に進むこともできます. .. Known Limitations .. _primer_known_limitations: 既知の制限事項 ============== .. Google Test is designed to be thread-safe. The implementation is thread-safe on systems where the pthreads library is available. It is currently unsafe to use Google Test assertions from two threads concurrently on other systems (e.g. Windows). In most tests this is not an issue as usually the assertions are done in the main thread. If you want to help, you can volunteer to implement the necessary synchronization primitives in gtest-port.h for your platform. Google Test はスレッドセーフであるように設計されています.この実装では,pthreads ライブラリが使えるシステムにおいてスレッドセーフとなります.それ以外のシステム(例えば,Windows)で,2つのスレッドから同時に Google Test のアサーションを利用するのは,現在のところスレッドセーフではありません.普通,アサーションはメインスレッドで実行されるので,ほとんどのテストではこれは問題にはなりません.この問題の対処に協力したい場合,あなたのプラットフォームで必要な同期プリミティブを gtest-port.h に実装して提供することができます.