.. _FAQ: ======== よくある質問 ======== .. Tips and Frequently-Asked Questions about Google C++ Testing Framework *Google C++ Testing Framework に関するヒントとよくある質問* * :ref:`faq_why_should_i_use_google_test` * :ref:`faq_im_getting_warnings_when_compiling_google_test` * :ref:`faq_why_should_not_test_case_names_and_test_names_contain_underscore` * :ref:`faq_why_is_it_not_recommended_to_install_a_precompiled_copy` * :ref:`faq_how_do_i_generate_64bit_binaries_on_windows` * :ref:`faq_can_i_use_google_test_on_mingw` * :ref:`faq_why_does_google_test_support_eq_not_ne` * :ref:`faq_does_google_test_support_in_parallel` * :ref:`faq_why_dont_google_test_run_the_tests_in_different` * :ref:`faq_why_arent_google_test_assertions_implemented_using_exceptions` * :ref:`faq_why_do_we_use_two_different_macros` * :ref:`faq_why_dont_we_use_structs_as_test_fixtures` * :ref:`faq_why_are_death_tests_implemented_as_assertions` * :ref:`faq_my_death_test_modifies_some_state_but_lost` * :ref:`faq_the_compiler_complains_about_undefined_reference` * :ref:`faq_i_have_an_interface_that_has_several_implementations` * :ref:`faq_can_i_derive_a_test_fixture_from_another` * :ref:`faq_my_compiler_complains_void_value_not_ignored` * :ref:`faq_my_death_test_hungs` * :ref:`faq_should_i_use_the_constructor_destructor_or_setup_teardown` * :ref:`faq_the_compiler_complains_no_matching_function` * :ref:`faq_my_compiler_complains_about_ignoring_return_value` * :ref:`faq_my_compiler_complains_that_constructor_cannot_return_a_value` * :ref:`faq_my_setup_function_is_not_called` * :ref:`faq_how_do_i_jump_to_the_line_of_a_failure_in_emacs` * :ref:`faq_i_have_several_test_cases_which_share_the_same_test_fixture` * :ref:`faq_the_google_test_output_is_buried_in` * :ref:`faq_why_should_i_prefer_test_fixtures_over_global_variables` * :ref:`faq_how_do_i_test_private_class_members` * :ref:`faq_how_do_i_ispvas_you_account` * :ref:`faq_i_would_like_to_run_a_test_several_times_with_different_params` * :ref:`faq_how_do_i_test_a_file_that_defines_main` * :ref:`faq_what_can_the_statement_argument_in_ASSERT_DEATH` * :ref:`faq_what_syntax_does_the_regular_expression` * :ref:`faq_i_have_a_fixture_class_foo` * :ref:`faq_why_does_ASSERT_DEATH_complain_about_previous_threads` * :ref:`faq_why_does_google_test_require_the_entire_test_case` * :ref:`faq_but_i_dont_like_calling_my_entire_test_case` * :ref:`faq_the_compiler_complains_about_no_match_for_operator` * :ref:`faq_i_am_building_my_project_with_google_test_in_VC` * :ref:`faq_i_put_my_tests_in_a_library` * :ref:`faq_i_want_to_use_google_test_with_VC` * :ref:`faq_i_am_seeing_compile_errors_mentioning_std_type_traits` * :ref:`faq_how_can_my_code_detect_if_it_is_running_in_a_test` * :ref:`faq_google_test_defines_a_macro_that_clashes_with_one_defined_by_another_library` * :ref:`faq_my_question_is_not_covered_in_your_faq` .. If you cannot find the answer to your question here, and you have read Primer and AdvancedGuide, send it to googletestframework@googlegroups.com. ここを見て疑問が解決できないならば, :ref:`primer` や :ref:`AdvancedGuide` を読んだり, googletestframework@googlegroups.com にメールを送ったりしてください. .. Why should I use Google Test instead of my favorite C++ testing framework? .. _faq_why_should_i_use_google_test: 今使っている C++ testing framework の代わりに Google Test を使うべきなのはなぜですか? ========================================================================================= .. First, let us say clearly that we don't want to get into the debate of which C++ testing framework is the best. There exist many fine frameworks for writing C++ tests, and we have tremendous respect for the developers and users of them. We don't think there is (or will be) a single best framework - you have to pick the right tool for the particular task you are tackling. まず最初に,どの C++ testing framework が **最高** かを議論するつもりはない,ということを言わせてください.C++ テスト用の多くの優れたフレームワークがありますが,我々は,その開発者やユーザに敬意を払っています.(今も,これからも)ただ1つの最高のフレームワークが存在するとは考えていません.あなたが取り組んでいるタスクにあった適切なツールを選択する必要があります. .. We created Google Test because we couldn't find the right combination of features and conveniences in an existing framework to satisfy our needs. The following is a list of things that we like about Google Test. We don't claim them to be unique to Google Test - rather, the combination of them makes Google Test the choice for us. We hope this list can help you decide whether it is for you too. 我々が Google Test を開発したのは,既存のフレームワークには, *我々の* 要求を満たす機能の組み合わせと利便性を兼ね備えたものが見つからなかったからです.Google Test で *我々が* 気に入っているところを以下に示します.これらが Google Test だけの特徴だとは言いません.むしろ,これらを全て備えていることが Google Test を選ぶ理由になっています.あなたも Google Test を選ぶかどうか,このリストが判断の役に立つことを願います. .. Google Test is designed to be portable: it doesn't require exceptions or RTTI; it works around various bugs in various compilers and environments; etc. As a result, it works on Linux, Mac OS X, Windows and several embedded operating systems. .. Nonfatal assertions (EXPECT_*) have proven to be great time savers, as they allow a test to report multiple failures in a single edit-compile-test cycle. .. It's easy to write assertions that generate informative messages: you just use the stream syntax to append any additional information, e.g. ASSERT_EQ(5, Foo(i)) << " where i = " << i;. It doesn't require a new set of macros or special functions. .. Google Test automatically detects your tests and doesn't require you to enumerate them in order to run them. .. No framework can anticipate all your needs, so Google Test provides EXPECT_PRED* to make it easy to extend your assertion vocabulary. For a nicer syntax, you can define your own assertion macros trivially in terms of EXPECT_PRED*. .. Death tests are pretty handy for ensuring that your asserts in production code are triggered by the right conditions. .. SCOPED_TRACE helps you understand the context of an assertion failure when it comes from inside a sub-routine or loop. .. You can decide which tests to run using name patterns. This saves time when you want to quickly reproduce a test failure. .. Google Test can generate XML test result reports that can be parsed by popular continuous build system like Hudson. .. Simple things are easy in Google Test, while hard things are possible: in addition to advanced features like global test environments and tests parameterized by values or types, Google Test supports various ways for the user to extend the framework -- if Google Test doesn't do something out of the box, chances are that a user can implement the feature using Google Test's public API, without changing Google Test itself. In particular, you can: .. expand your testing vocabulary by defining custom predicates, .. teach Google Test how to print your types, .. define your own testing macros or utilities and verify them using Google Test's Service Provider Interface, and .. reflect on the test cases or change the test output format by intercepting the test events. * Google Test はポータブルに設計されています:例外やRTTIを必要としませんし,様々なコンパイラや環境のバグに対応しています.結果として,Linux や Mac OS X,Windows,そしていくつかの組み込みOS でも動作します. * 致命的でないアサーション(EXPECT_*)を利用すると,1回の「編集-コンパイル-テスト」サイクルにおいて,テストが複数の失敗を報告できるので,大いに時間が節約できます. * 役立つメッセージを生成するアサーションを簡単に書くことができます:好きな情報を追加するには,例えば,ASSERT_EQ(5, Foo(i)) << " where i = " << i; というようにストリーム構文を使うだけです.これには,マクロや特殊な関数を必要としません. * Google Test は自動的にテストを検出するので,それらを実行順に列挙する必要はありません. * あなたが望むすべての機能を備えたフレームワークは存在しませんが,Google Test では,EXPECT_PRED* を利用してアサーションの種類を簡単に増やせます.また,EXPECT_PRED* を使って,自分の使いやすいアサーションマクロを定義して,より便利な構文にすることもできます. * Death テストは,製品版コードのアサーションが正しい条件で動作することを保証するのに非常に役立ちます. * サブルーチンやループの内側でアサーションが失敗した場合,SCOPED_TRACE を使うと,そのコンテキストを理解する助けになります. * テスト名のパターンを利用して,どのテストを実行するかを決めることができます.テスト失敗を素早く再現したい場合に,時間が節約できます. * Google Test は,Hudson のような有名な continuous build システムでパース可能なXML形式のテスト結果レポートを出力できます. * Google Test を使うと,単純なテストは簡単に行えますし,難しいテストも実現可能です:つまり,グローバルテスト環境や値や型によって並列化されたテストなどの高度な機能に加えて,Google Test はユーザがこのフレームワークを拡張する様々な方法を提供します.既存の Google Test では実現できない事があれば,Google Test 自身には手を加えずに,Google Test の public API を利用して,ユーザがその機能を実装する事も可能かもしれません.ユーザができることは以下の通りです: * カスタム述語関数を定義して,テスト用の語彙を拡張する * ユーザ定義型の表示方法を Google Test に教える * 独自のテストマクロやユーティリティを定義して,Google Test のサービスプロバイダインタフェースを利用してそれらを検証する * テストイベントを中断することで,テストケースを見直したり,テストの出力フォーマットを変更したりする. .. I'm getting warnings when compiling Google Test. Would you fix them? .. _faq_im_getting_warnings_when_compiling_google_test: Google Test をコンパイルする際に警告が出ます.直してもらえますか? ================================================================= .. We strive to minimize compiler warnings Google Test generates. Before releasing a new version, we test to make sure that it doesn't generate warnings when compiled using its CMake script on Windows, Linux, and Mac OS. 我々は,Google Test 生成時の警告を最小限にしようと努力しています.新しいバージョンをリリースする前に,Windows,Linux,Mac OSでの CMake スクリプトを利用して,コンパイル時に警告が出ないことを確認するためにテストを行っています. .. Unfortunately, this doesn't mean you are guaranteed to see no warnings when compiling Google Test in your environment: しかし残念ながら,これは,ユーザの環境で Google Test をコンパイルした際に警告が出ないことを保障するものではありません: .. You may be using a different compiler as we use, or a different version of the same compiler. We cannot possibly test for all compilers. .. You may be compiling on a different platform as we do. .. Your project may be using different compiler flags as we do. * ユーザは,我々とは別のコンパイラ,または同じコンパイラの別のバージョンを利用しているかもしれません.すべてのコンパイラに対するテストは到底不可能です. * ユーザは,我々とは別のプラットフォームでコンパイルしているかもしれません. * ユーザのプロジェクトで,我々とは別のコンパイラフラグを利用しているもしれません. .. It is not always possible to make Google Test warning-free for everyone. Or, it may not be desirable if the warning is rarely enabled and fixing the violations makes the code more complex. すべての人の Google Test で警告を出なくするというのは,常に可能というわけではありません.また,その警告がまれにしか有効でなく,それの修正がコードをより複雑にしてしまうならば,それは意味がないかもしれません. .. If you see warnings when compiling Google Test, we suggest that you use the -isystem flag (assuming your are using GCC) to mark Google Test headers as system headers. That'll suppress warnings from Google Test headers. Google Test のコンパイル時に警告がでた場合,Google Test のヘッダをシステムヘッダとしてマークするために(GCC を利用していると仮定して)-isystem フラグを利用することを勧めます.これは,Google Test ヘッダからの警告を抑制してくれるでしょう. .. Why should not test case names and test names contain underscore? .. _faq_why_should_not_test_case_names_and_test_names_contain_underscore: なぜ,テストケース名やテスト名にアンダースコアを利用してはいけないのでしょうか? ================================================================= .. Underscore (_) is special, as C++ reserves the following to be used by the compiler and the standard library: C++ はコンパイラや標準ライブラリで利用するために以下の識別子を予約しており,アンダースコア(_)は特殊な文字と言えます: .. any identifier that starts with an _ followed by an upper-case letter, and .. any identifier that containers two consecutive underscores (i.e. __) anywhere in its name. #. _ の後に大文字で始まる任意の識別子 #. 連続したアンダースコア(つまり,__)を名前に含む任意の識別子 .. User code is prohibited from using such identifiers. ユーザのコードでは,このような識別子を利用することは禁止されています. .. Now let's look at what this means for TEST and TEST_F. さて,これが TEST や TEST_F にどのような影響を与えるのか見てみましょう. .. Currently TEST(TestCaseName, TestName) generates a class named TestCaseName_TestName_Test. What happens if TestCaseName or TestName contains _? 現在, TEST(TestCaseName, TestName) は, TestCaseName_TestName_Test という名前のクラスを生成します.TestCaseName や TestName に _ が含まれていると何が起こるでしょうか? .. If TestCaseName starts with an _ followed by an upper-case letter (say, _Foo), we end up with _Foo_TestName_Test, which is reserved and thus invalid. .. If TestCaseName ends with an _ (say, Foo_), we get Foo__TestName_Test, which is invalid. .. If TestName starts with an _ (say, _Bar), we get TestCaseName__Bar_Test, which is invalid. .. If TestName ends with an _ (say, Bar_), we get TestCaseName_Bar__Test, which is invalid. #. TestCaseName が _ の後に大文字で始まると(例えば,_Foo),_Foo_TestName_Test とう名前になってしまい,これは予約されているので無効になります. #. TestCaseName が _ で終わると(例えば,Foo_),Foo__TestName_Test という名前になり,無効になります. #. TestName が _ で始まると(例えば,_Bar),TestCaseName__Bar_Test という名前になり,無効になります. #. TestName が _ で終わると(例えば,Bar_),TestCaseName_Bar__Test という名前になり,無効になります. .. So clearly TestCaseName and TestName cannot start or end with _ (Actually, TestCaseName can start with _ -- as long as the _ isn't followed by an upper-case letter. But that's getting complicated. So for simplicity we just say that it cannot start with _.). つまり,TestCaseName と TestName が,_ で始まったり終わったりできないことは明らかです(実際には,_ の後が大文字でなければ, TestCaseName は _ で始まることができます. しかし,これでは複雑になってしまいますので,簡単のために, _ で始めてはいけない,としています). .. It may seem fine for TestCaseName and TestName to contain _ in the middle. However, consider this: TestCaseName と TestName の先頭や末尾ではなく中間にだったら, _ が含まれても良いように思えます.しかし,次の例を考えてみてください: .. code-block:: c TEST(Time, Flies_Like_An_Arrow) { ... } TEST(Time_Flies, Like_An_Arrow) { ... } .. Now, the two TESTs will both generate the same class (Time_Files_Like_An_Arrow_Test). That's not good. この 2つの TEST は,どちらも同じクラス(Time_Files_Like_An_Arrow_Test)を生成します.これは,良くありません. .. So for simplicity, we just ask the users to avoid _ in TestCaseName and TestName. The rule is more constraining than necessary, but it's simple and easy to remember. It also gives Google Test some wiggle room in case its implementation needs to change in the future. やはり簡単のため,TestCaseName や TestName に _ を含めないように,とだけお願いしておきます.このルールは必要というよりは制約に近いですが,簡単で覚えやすいものです.また,これによって,将来的に Google Test の実装を変更する必要が出てきた場合も,多少の融通が利くようになります. .. If you violate the rule, there may not be immediately consequences, but your test may (just may) break with a new compiler (or a new version of the compiler you are using) or with a new version of Google Test. Therefore it's best to follow the rule. このルールを破っても,すぐには影響がないかもしれませんが,新しいコンパイラ(あるいは,今のコンパイラの新しいバージョンで)や Google Test の新しいバージョンでテストが失敗する可能性(あくまでも可能性)があります.よって,ルールに従うのがベストな選択です. .. Why is it not recommended to install a pre-compiled copy of Google Test (for example, into /usr/local)? .. _faq_why_is_it_not_recommended_to_install_a_precompiled_copy: コンパイル済みの Google Test を(例えば /usr/local に)インストールするのが推奨されないのはなぜですか? ====================================================================================================== .. In the early days, we said that you could install compiled Google Test libraries on *nix systems using make install. Then every user of your machine can write tests without recompiling Google Test. 開発初期は,*nix システム上で make insall して,コンパイルした Google Test ライブラリをインストールできました.すると,Google Test を際コンパイルしなくても,そのマシンを使うすべてのユーザがテストを書けます. .. This seemed like a good idea, but it has a got-cha: every user needs to compile his tests using the same compiler flags used to compile the installed Google Test libraries; otherwise he may run into undefined behaviors (i.e. the tests can behave strangely and may even crash for no obvious reasons). 良いアイディアのように思えますが,これには1つ問題があります:つまり,すべてのユーザが,Google Test のバイナリをコンパイルするのに使ったコンパイラフラグと *同じ* フラグを使ってテストをコンパイルする必要があります.そうしなければ,未定義の挙動に出くわす可能性があります(つまり,テストがおかしな動作をしたり,理由もなくクラッシュしたりすることが起こり得ます). .. Why? Because C++ has this thing called the One-Definition Rule: if two C++ source files contain different definitions of the same class/function/variable, and you link them together, you violate the rule. The linker may or may not catch the error (in many cases it's not required by the C++ standard to catch the violation). If it doesn't, you get strange run-time behaviors that are unexpected and hard to debug. なぜでしょうか?C++ には One-Definition rule と呼ばれるものがあるからです.同じクラス/関数/変数に対する異なる定義を含む2つの C++ ソースファイルがある場合に,これらを一緒にリンクしてしまうとルール違反になります.リンカは,このエラーを検知するかもしれないし,しないかもしれません(多くの場合,標準 C++ ではこの違反の検知が必須というわけではありません).検知されない場合,実行時に,予想外でデバッグ困難な挙動を示すことになります. .. If you compile Google Test and your test code using different compiler flags, they may see different definitions of the same class/function/variable (e.g. due to the use of #if in Google Test). Therefore, for your sanity, we recommend to avoid installing pre-compiled Google Test libraries. Instead, each project should compile Google Test itself such that it can be sure that the same flags are used for both Google Test and the tests. Google Test とテストコードを,それぞれ異なるコンパイラフラグでコンパイルすると,(例えば,Google Test では #if を利用しているので)同じクラス/関数/変数に別の定義があるように見える可能性があります. したがって,混乱しないためにも,コンパイル済みの Google Test ライブラリをインストールしないことをお勧めします.代わりに,プロジェクトごとに Google Test 自体をコンパイルして,Google Test とテストのコンパイルに確実に同じフラグが使われるようにしてください. .. How do I generate 64-bit binaries on Windows (using Visual Studio 2008)? .. _faq_how_do_i_generate_64bit_binaries_on_windows: Windows(Visual Studio 2008) で 64-bit バイナリを作るにはどうすればいいですか? ================================================================================= .. (Answered by Trevor Robinson) (Trevor Robinson の回答) .. Load the supplied Visual Studio solution file, either msvc\gtest-md.sln or msvc\gtest.sln. Go through the migration wizard to migrate the solution and project files to Visual Studio 2008. Select Configuration Manager... from the Build menu. Select from the Active solution platform dropdown. Select x64 from the new platform dropdown, leave Copy settings from set to Win32 and Create new project platforms checked, then click OK. You now have Win32 and x64 platform configurations, selectable from the Standard toolbar, which allow you to toggle between building 32-bit or 64-bit binaries (or both at once using Batch Build). Visual Studio ソリューションファイル msvc\\gtest-md.sln または msvc\\gtest.sln をロードしてください.変換ウィザードによって,ソリューションファイルとプロジェクトファイルが Visual Studio 2008 向けに変換されます.ビルドメニューの 構成マネージャ... を選択してください.次に,アクティブソリューションプラットフォーム ドロップダウンメニューから,<新規作成...> を選択してください.新しいプラットフォームドロップダウンメニューからの x64 を選択して,設定のコピー元は Win32のままにします.新しいプロジェクトプラットフォームを作成する,にチェックを入れて,OK をクリックします.Win32 と x64 のプラットフォーム構成ができたので,標準の ツールバーから選択でき,32-bit または 64-bit バイナリを切り替えて作成できます(バッチビルドを使って両方いっぺんにビルドすることもできます). .. In order to prevent build output files from overwriting one another, you'll need to change the Intermediate Directory settings for the newly created platform configuration across all the projects. To do this, multi-select (e.g. using shift-click) all projects (but not the solution) in the Solution Explorer. Right-click one of them and select Properties. In the left pane, select Configuration Properties, and from the Configuration dropdown, select All Configurations. Make sure the selected platform is x64. For the Intermediate Directory setting, change the value from $(PlatformName)\$(ConfigurationName) to $(OutDir)\$(ProjectName). Click OK and then build the solution. When the build is complete, the 64-bit binaries will be in the msvc\x64\Debug directory. 出力ファイルが上書きされるのを防ぐには,すべてのプロジェクトで,新しく作成したプラットフォーム構成の中間ディレクトリ設定を変更する必要があります.これを行うには,ソリューションエクスプローラで,すべてのプロジェクトを(例えば,シフトキーを押しながら)複数選択します.そのうち1つを右クリックして,プロパティ を選択します.左上にある 構成プロパティ の 構成 ドロップダウンメニューから,すべての構成 を選択します.プラットフォームが x64 になっていることを確認してください.中間ディレクトリ 設定を, $(PlatformName)\\$(ConfigurationName) から $(OutDir)\\$(ProjectName) に変更します.OK をクリックして,ソリューションのビルドを行います.ビルドが完了すると,msvc\\x64\\Debug ディレクトリに 64-bit バイナリができます. .. Can I use Google Test on MinGW? .. _faq_can_i_use_google_test_on_mingw: MinGW で Google Test を利用できますか? ======================================== .. We haven't tested this ourselves, but Per Abrahamsen reported that he was able to compile and install Google Test successfully when using MinGW from Cygwin. You'll need to configure it with: 我々自身がテストしたわけではありませんが,Per Abrahamsen の報告によると,Cygwin から MinGW を使って Google Test のコンパイルとインストールに成功したそうです.次のように設定する必要があります: :: PATH/TO/configure CC="gcc -mno-cygwin" CXX="g++ -mno-cygwin" .. You should be able to replace the -mno-cygwin option with direct links to the real MinGW binaries, but we haven't tried that. -mno-cygwin オプションを,MinGW バイナリへの直接リンクに置き換えることもできるはずですが,我々は試していません. .. Caveats: 注意事項: .. There are many warnings when compiling. .. make check will produce some errors as not all tests for Google Test itself are compatible with MinGW. * コンパイル時に,大量の警告が出ます. * Google Test 自身に対するテストが,すべて MinGW との互換性があるわけではないので,make check ではエラーがでます. .. We also have reports on successful cross compilation of Google Test MinGW binaries on Linux using these instructions on the WxWidgets site. WxWidgets のサイトにある `この方法 `_ を用いて Linux 上で,MinGW 用の Google Test バイナリをクロスコンパイルできたという報告も受けています. .. Please contact googletestframework@googlegroups.com if you are interested in improving the support for MinGW. MinGW のサポート強化に興味があれば, googletestframework@googlegroups.com に連絡をお願いします. .. Why does Google Test support EXPECT_EQ(NULL, ptr) and ASSERT_EQ(NULL, ptr) but not EXPECT_NE(NULL, ptr) and ASSERT_NE(NULL, ptr)? .. _faq_why_does_google_test_support_eq_not_ne: Google Test では,EXPECT_NE(NULL, ptr) や ASSERT_NE(NULL, ptr) ではなく,EXPECT_EQ(NULL, ptr) や ASERT_EQ(NULL, ptr) をサポートしているのはなぜですか? ======================================================================================================== .. Due to some peculiarity of C++, it requires some non-trivial template meta programming tricks to support using NULL as an argument of the EXPECT_XX() and ASSERT_XX() macros. Therefore we only do it where it's most needed (otherwise we make the implementation of Google Test harder to maintain and more error-prone than necessary). C++ の仕様により,EXPECT_XX() および ASSERT_XX() マクロの引数として NULL をサポートするには,テンプレートメタプログラミングの複雑なテクニックが必要になります.よって,必要な場所だけで,そうするようにしています(そうしなければ,Google Test の実装は,必要以上にメンテナンスし難く,間違いが起こりやすいものになっていたでしょう). .. The EXPECT_EQ() macro takes the expected value as its first argument and the actual value as the second. It's reasonable that someone wants to write EXPECT_EQ(NULL, some_expression), and this indeed was requested several times. Therefore we implemented it. EXPECT_EQ() マクロは,最初の引数として *期待する* 値,2番目の引数として *実際の* 値をとります.EXPECT_EQ(NULL, some_expression) と書きたいと考える人がいても不思議ではありませんし,実際,何度も要望はありました.なので,我々はこれを実装しました. .. The need for EXPECT_NE(NULL, ptr) isn't nearly as strong. When the assertion fails, you already know that ptr must be NULL, so it doesn't add any information to print ptr in this case. That means EXPECT_TRUE(ptr ! NULL) works just as well. EXPECT_NE(NULL, ptr) の必要性は,これほど強くはありません.アサーション失敗時には, ptr が必ず NULL であることが分かっているので,この場合,追加の情報は出力されません.つまり, EXPECT_TRUE(ptr != NULL) マクロの動作で十分だということです. .. If we were to support EXPECT_NE(NULL, ptr), for consistency we'll have to support EXPECT_NE(ptr, NULL) as well, as unlike EXPECT_EQ, we don't have a convention on the order of the two arguments for EXPECT_NE. This means using the template meta programming tricks twice in the implementation, making it even harder to understand and maintain. We believe the benefit doesn't justify the cost. もし EXPECT_NE(NULL, ptr) をサポートするならば,整合性を保つために EXPECT_NE(ptr, NULL) も同様にサポートしなければいけないでしょう.EXPECT_EQ とは違って,EXPECT_NE の引数の順番には特に決まりがないからです.これはつまり,実装時に使われるテンプレートメタプログラミングの技法が2倍になり,理解やメンテナンスがより困難になる,ということです.これをサポートしてもコストに見合わない,と我々は考えています. .. Finally, with the growth of Google Mock's matcher library, we are encouraging people to use the unified EXPECT_THAT(value, matcher) syntax more often in tests. One significant advantage of the matcher approach is that matchers can be easily combined to form new matchers, while the EXPECT_NE, etc, macros cannot be easily combined. Therefore we want to invest more in the matchers than in the EXPECT_XX() macros. 最後に,我々は EXPECT_THAT(value, matcher) という統合構文をテストでもっと使うように勧めています.これは,Google Mock の matcher ライブラリを利用したものです.matcher を利用する大きな利点の1つは,matcher を組み合わせて新しい matcher を簡単に作れる,ということです.一方,EXPECT_NE などのマクロを組み合わせるのは容易ではありません.よって,EXPECT_XX() マクロよりも matcher に注力していきたいと考えています. .. Does Google Test support running tests in parallel? .. _faq_does_google_test_support_in_parallel: Google Test ではテストの並列実行をサポートしていますか? ===================================== .. Test runners tend to be tightly coupled with the build/test environment, and Google Test doesn't try to solve the problem of running tests in parallel. Instead, we tried to make Google Test work nicely with test runners. For example, Google Test's XML report contains the time spent on each test, and its gtest_list_tests and gtest_filter flags can be used for splitting the execution of test methods into multiple processes. These functionalities can help the test runner run the tests in parallel. テストランナーはビルド/テスト環境と密接に関係している傾向があり,これはテストを並列に実行する際に問題になりますが,Google Test はこの問題を無理に解決しようとはしません.代わりに,Google Test をテストランナーと一緒にうまく動作するようにしました.例えば,Google Test の XML レポートには,各テストの実行時間が含まれており,また,テストメソッド実行を複数のプロセスに分けて行うためには, gtest_list_tests や gtest_filter フラグが利用できます. これらの機能は,テストランナーがテストを並列実行するのに役立ちます. .. Why don't Google Test run the tests in different threads to speed things up? .. _faq_why_dont_google_test_run_the_tests_in_different: Google Test が,テストをマルチスレッドで実行して高速化しないのはなぜですか? ================================================== .. It's difficult to write thread-safe code. Most tests are not written with thread-safety in mind, and thus may not work correctly in a multi-threaded setting. スレッドセーフなコードを書くのは難しいことです.ほとんどのテストは,スレッドの安全性を考慮して書かれておらず,マルチスレッド環境では正しく動作しません. .. If you think about it, it's already hard to make your code work when you know what other threads are doing. It's much harder, and sometimes even impossible, to make your code work when you don't know what other threads are doing (remember that test methods can be added, deleted, or modified after your test was written). If you want to run the tests in parallel, you'd better run them in different processes. 考えてみると,他のスレッドが何をしているのか知っている場合でさえ,正しく動くコードを書くのは困難です.他のスレッドが何をしているのか分からずに正しく動くコードを書くのは,それよりもずっと難しいですし,不可能な場合さえあります(あなたがテストを書いた後でも,テストメソッドが追加,削除,変更される可能性があることを考えてください).テストを並列に実行したいならば,マルチプロセスで実行するのがより良い方法でしょう. .. Why aren't Google Test assertions implemented using exceptions? .. _faq_why_arent_google_test_assertions_implemented_using_exceptions: Google Test のアサーションが例外を使った実装になっていないのはなぜですか? ================================================ .. Our original motivation was to be able to use Google Test in projects that disable exceptions. Later we realized some additional benefits of this approach: 我々の元々のモチベーションは,例外が使えないプロジェクトで Google Test を利用できるようにすることでした.その後,このアプローチには他にも利点があることに気付いたのです: .. Throwing in a destructor is undefined behavior in C++. Not using exceptions means Google Test's assertions are safe to use in destructors. .. The EXPECT_* family of macros will continue even after a failure, allowing multiple failures in a TEST to be reported in a single run. This is a popular feature, as in C++ the edit-compile-test cycle is usually quite long and being able to fixing more than one thing at a time is a blessing. .. If assertions are implemented using exceptions, a test may falsely ignore a failure if it's caught by user code: * C++では,デストラクタで例外を投げたときの動作が未定義です.例外を使わないことで,Google Test のアサーションはデストラクタでも安全に利用できます. * EXPECT_* マクロは,これが失敗した後でも処理が続行されるので,1回の実行で1つの TEST 中の複数の失敗を報告できます.通常,C++ の「編集-コンパイル-テスト」サイクルは非常に長く,1度で複数の修正ができるようになってきているのはありがたいので,これは人気の機能です. * もしアサーションが例外を用いて実装されていたとしたら,その例外がユーザにキャッチされてしまうと失敗を見逃してしまいます: .. code-block:: c try { ... ASSERT_TRUE(...) ... } catch (...) { ... } .. The above code will pass even if the ASSERT_TRUE throws. While it's unlikely for someone to write this in a test, it's possible to run into this pattern when you write assertions in callbacks that are called by the code under test. 上記のコードは,ASSERT_TRUE が例外を投げた場合でも成功してしまいます.テストでこのように書くことはなさそうですが,テストされるコードから呼ばれるコールバック中にアサーションを書くときには,このようなパターンに出くわす可能性があります. .. The downside of not using exceptions is that ASSERT_* (implemented using return) will only abort the current function, not the current TEST. 例外を使用しないことの欠点は,ASSERT_* (return を用いた実装)は,現在の関数を終了させることはできても現在の TEST を終了させることはできない,ということです. .. Why do we use two different macros for tests with and without fixtures? .. _faq_why_do_we_use_two_different_macros: フィクスチャを使う場合と使わない場合とで別のマクロを使うのはなぜですか? =============================================== .. Unfortunately, C++'s macro system doesn't allow us to use the same macro for both cases. One possibility is to provide only one macro for tests with fixtures, and require the user to define an empty fixture sometimes: 残念ですが,C++ のマクロシステムでは,これらの場合で同じマクロを利用することはできません.フィクスチャを用いるテスト用の1つのマクロだけを提供して,ユーザに空のフィクスチャを定義してもらう,という手段も可能ではあります: .. code-block:: c class FooTest : public ::testing::Test {}; TEST_F(FooTest, DoesThis) { ... } .. or または, .. code-block:: c typedef ::testing::Test FooTest; TEST_F(FooTest, DoesThat) { ... } .. Yet, many people think this is one line too many. :-) Our goal was to make it really easy to write tests, so we tried to make simple tests trivial to create. That means using a separate macro for such tests. しかし,これでは1行コードが多すぎると思われるでしょう.:-) 我々の目的は,テストを楽に書けるようにすることだったので,簡単なテストは簡単に作れるようにしました. これが,それぞれのテスト用にマクロが分かれている理由です. .. We think neither approach is ideal, yet either of them is reasonable. In the end, it probably doesn't matter much either way. どちらのアプローチも理想的とは言えなくても,合理的ではあると考えています.結局,おそらくどちらの方法にしても,そこまで重要な問題ではありません. .. Why don't we use structs as test fixtures? .. _faq_why_dont_we_use_structs_as_test_fixtures: テストフィクスチャとして構造体を利用しないのはなぜですか? ========================================================= .. We like to use structs only when representing passive data. This distinction between structs and classes is good for documenting the intent of the code's author. Since test fixtures have logic like SetUp() and TearDown(), they are better defined as classes. 我々の方針は,受動的なデータを表現するときにだけ構造体を利用する,というものです.このように構造体とクラスを区別すると,コードを書く人間の意図を上手く示すことができます.テストフィクスチャには setUp() や TearDown() などのロジックが含まれているので,これはクラスとして定義されるのが良いでしょう. .. Why are death tests implemented as assertions instead of using a test runner? .. _faq_why_are_death_tests_implemented_as_assertions: Death テストは アサーションとして実装されていますが,代わりにテストランナーを使わないのはなぜですか? ================================================================================== .. Our goal was to make death tests as convenient for a user as C++ possibly allows. In particular: 我々の目的は,C++ が許す範囲で,Death テストをユーザにとって便利なものにすることでした.特に,次のような点が挙げられます: .. The runner-style requires to split the information into two pieces: the definition of the death test itself, and the specification for the runner on how to run the death test and what to expect. The death test would be written in C++, while the runner spec may or may not be. A user needs to carefully keep the two in sync. ASSERT_DEATH(statement, expected_message) specifies all necessary information in one place, in one language, without boilerplate code. It is very declarative. .. ASSERT_DEATH has a similar syntax and error-reporting semantics as other Google Test assertions, and thus is easy to learn. .. ASSERT_DEATH can be mixed with other assertions and other logic at your will. You are not limited to one death test per test method. For example, you can write something like: * ランナー形式では,情報を2つに分ける必要があります:まず,Death テスト自体の定義.そして,Death テストをどのように実行して,結果として何を期待するか,というランナーの仕様です.Death テストは C++ で書かれるでしょうが,ランナーの仕様は何で書かれているか不明です.ユーザは,これらの協調に気を配る必要があります.ASSERT_DEATH(statement, expected_message) では,必要な情報すべてを,1か所で,かつ1言語で定義します.余計な決まり文句的コードもありません.これは,とても平叙文的です. * ASSERT_DEATH の構文やエラーレポートの挙動は,Google Test のアサーションと似ているので,理解が容易です. * ASSERT_DEATH は,他のアサーションや好きなロジックと一緒に利用することができます.1つのテストメソッドに1つの Death テスト,といった制限はありません.例えば,次のような書き方もできます: .. code-block:: c if (FooCondition()) { ASSERT_DEATH(Bar(), "blah"); } else { ASSERT_EQ(5, Bar()); } .. If you prefer one death test per test method, you can write your tests in that style too, but we don't want to impose that on the users. The fewer artificial limitations the better. 1つのテストメソッドに1つの Death テストという書き方が好きならば,そのようなスタイルで書くこともできます.しかし,それをユーザに強要することはしたくありません.人為的な制限は,少なければ少ないほど良いです. .. ASSERT_DEATH can reference local variables in the current function, and you can decide how many death tests you want based on run-time information. For example, * ASSERT_DEATH は,現在の関数のローカル変数を参照できます.ユーザは,Death テストを何回実行するかを,実行時情報に基づいて決めることができます.以下に例を示します: .. code-block:: c const int count = GetCount(); // 実行時に初めて分かる. for (int i = 1; i <= count; i++) { ASSERT_DEATH({ double* buffer = new double[i]; ... initializes buffer ... Foo(buffer, i) }, "blah blah"); } .. The runner-based approach tends to be more static and less flexible, or requires more user effort to get this kind of flexibility. ランナーを使った方法は,より静的で柔軟性に欠けたものになりやすく,その分ユーザが努力する必要があります. .. Another interesting thing about ASSERT_DEATH is that it calls fork() to create a child process to run the death test. This is lightening fast, as fork() uses copy-on-write pages and incurs almost zero overhead, and the child process starts from the user-supplied statement directly, skipping all global and local initialization and any code leading to the given statement. If you launch the child process from scratch, it can take seconds just to load everything and start running if the test links to many libraries dynamically. ASSERT_DEATH には,もう1つおもしろい点があります. Death テストを実行する子プロセスを作るために fork() を呼ぶ,ということです. fork() は,メモリページのコピーオンライトを利用してほとんどオーバヘッドがないので,これはほぼ瞬間的に動作します. また,子プロセスは,全てのグローバル変数とローカル変数の初期化,その他与えられた文までに存在する全てのコードをスキップして,ユーザの与えた文から直接開始します. もし,子プロセスを一から立ち上げるとすると,テストが多くの動的ライブラリにリンクされている場合,すべてをロードしてテスト開始するまでに数秒の時間がかかるでしょう. .. My death test modifies some state, but the change seems lost after the death test finishes. Why? .. _faq_my_death_test_modifies_some_state_but_lost: Death テストで状態を変更しても,テスト終了後にはそれが元に戻るようです.なぜですか? ======================================================== .. Death tests (EXPECT_DEATH, etc) are executed in a sub-process s.t. the expected crash won't kill the test program (i.e. the parent process). As a result, any in-memory side effects they incur are observable in their respective sub-processes, but not in the parent process. You can think of them as running in a parallel universe, more or less. (EXPECT_DEATH などの)Death テストは,サブプロセスで実行されます.ただし, 期待されるクラッシュはテストプログラム(つまり,親プロセス)を殺したりはしません.その結果,メモリ内のあらゆる副作用は,親プロセスではなく,それぞれのサブプロセス内で生じます.テストはどこか別の宇宙で実行されている,と考えてもらっても構いませんよ. .. The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong? .. _faq_the_compiler_complains_about_undefined_reference: コンパイラが,static const なメンバ変数に対して "undefined reference" というエラーを出しますが,クラス内でちゃんと定義しています.何がおかしいのでしょうか? ==================================================================================================== .. If your class has a static data member: クラスに static データメンバがある場合: .. code-block:: c // foo.h class Foo { ... static const int kBar = 100; }; .. You also need to define it outside of the class body in foo.cc: クラス定義の *外* ,foo.cc でもこれを定義する必要があります: .. code-block:: c const int Foo::kBar; // ここでは初期化は不要です. .. Otherwise your code is invalid C++, and may break in unexpected ways. In particular, using it in Google Test comparison assertions (EXPECT_EQ, etc) will generate an "undefined reference" linker error. 上記のようにしなければ, **無効な C++ のコード** になってしまいます.具体的には,Google Test の(EXPECT_EQ などの)比較アサーションを利用したときに,"undefined reference" リンカエラーが起こります. .. I have an interface that has several implementations. Can I write a set of tests once and repeat them over all the implementations? .. _faq_i_have_an_interface_that_has_several_implementations: 複数の実装を持つインタフェースがあります.テストセットを1度だけ書いて,すべての実装に対してそれを繰り返し実行することができますか? ====================================================================================== .. Google Test doesn't yet have good support for this kind of tests, or data-driven tests in general. We hope to be able to make improvements in this area soon. Google Test には,まだこの手のテスト,あるいは一般的なデータ駆動テストに対する良い対処法がありません.しかし,すぐにこの部分での改善を行うことができると思っています. .. Can I derive a test fixture from another? .. _faq_can_i_derive_a_test_fixture_from_another: テストフィクスチャが別のテストフィクスチャを継承することはできますか? ============================================== .. Yes. できます. .. Each test fixture has a corresponding and same named test case. This means only one test case can use a particular fixture. Sometimes, however, multiple test cases may want to use the same or slightly different fixtures. For example, you may want to make sure that all of a GUI library's test cases don't leak important system resources like fonts and brushes. 各テストフィクスチャには,それに対応する同じ名前のテストケースがあります.つまり,ある1つのフィクスチャを利用できるのは,1つのテストケースだけだという事です.しかし,場合によっては,複数のテストケースで同じフィクスチャ(あるいは,少しだけ異なったフィクスチャ)を使いたい事があります.例えば, GUI ライブラリのすべてのテストケースが,フォントやブラシなどの重要なシステムリソースをリークしていない事を確認したい場合などがあります. .. In Google Test, you share a fixture among test cases by putting the shared logic in a base test fixture, then deriving from that base a separate fixture for each test case that wants to use this common logic. You then use TEST_F() to write tests using each derived fixture. Google Test では,テストケース間でフィクスチャを共有できます.まず,基底テストフィクスチャで共有ロジックを定義し,その共通ロジックを使いたいフィクスチャを,各テストケース毎に派生させます.そして,それぞれの派生クラスを用いてテストを書くために TEST_F() を利用します. .. Typically, your code looks like this: 典型的には,以下の様なコードになります: .. code-block:: c // 基底テストフィクスチャクラスを定義します. class BaseTest : public ::testing::Test { protected: ... }; // BaseTest から FooTest フィクスチャを派生させます. class FooTest : public BaseTest { protected: virtual void SetUp() { BaseTest::SetUp(); // まず,基底フィクスチャクラスの初期化 ... additional set-up work ... } virtual void TearDown() { ... clean-up work for FooTest ... BaseTest::TearDown(); // FooTest の終了処理後に, // 基底フィクスチャクラスの終了処理も忘れずに. } ... functions and variables for FooTest ... }; // フィクスチャ FooTest を利用したテスト TEST_F(FooTest, Bar) { ... } TEST_F(FooTest, Baz) { ... } ... additional fixtures derived from BaseTest ... .. If necessary, you can continue to derive test fixtures from a derived fixture. Google Test has no limit on how deep the hierarchy can be. 必要ならば,派生したテストフィクスチャからさらに別のフィクスチャを派生させることもできます.Google Test には,この階層の制限はありません. .. For a complete example using derived test fixtures, see sample5. 派生したテストフィクスチャを使う完全な例は,sample5 を参照してください. .. My compiler complains "void value not ignored as it ought to be." What does this mean? .. _faq_my_compiler_complains_void_value_not_ignored: コンパイラが,"void value not ignored as it ought to be" というエラーを出します.これはどういう意味ですか? ====================================================================== .. You're probably using an ASSERT_*() in a function that doesn't return void. ASSERT_*() can only be used in void functions. おそらく,void を返さない関数で ASSERT_*() を使っています.ASSERT_*() を使うことができるのは,void を返す関数の中だけです. .. My death test hangs (or seg-faults). How do I fix it? .. _faq_my_death_test_hungs: Death テストがハングアップ(または,セグメンテーションフォルト)します.どうやって修正すればよいでしょうか? =========================================================================== .. In Google Test, death tests are run in a child process and the way they work is delicate. To write death tests you really need to understand how they work. Please make sure you have read this. Google Test では,Death テストは子プロセスで実行され,その実行方法はデリケートです.Death テストを書くためには,その動作をきちんと理解する必要があります.これを,しっかり読んでください. .. In particular, death tests don't like having multiple threads in the parent process. So the first thing you can try is to eliminate creating threads outside of EXPECT_DEATH(). 特に,Death テストでは,親プロセス内に複数のスレッドを持つのは良くありません.最初に試すことができる方法は,EXPECT_DEATH() の外側でスレッドを作成している部分を削除することです. .. Sometimes this is impossible as some library you must use may be creating threads before main() is even reached. In this case, you can try to minimize the chance of conflicts by either moving as many activities as possible inside EXPECT_DEATH() (in the extreme case, you want to move everything inside), or leaving as few things as possible in it. Also, you can try to set the death test style to "threadsafe", which is safer but slower, and see if it helps. 不可欠なライブラリが, main() の開始よりも前にスレッドを作る場合などのように,これが不可能な場合もあります.この場合,できる限り多くの処理を EXPECT_DEATH() 内部に移動させる(極端な場合,すべてを内部に移す)か,あるいは逆に,内部の処理をできるだけ少なくするかして,衝突する可能性を最小にします.また,Death テストのスタイルを "threadsafe" に設定することもできます.これは,安全ですが遅くなりますので,使えるかどうか試してください. .. If you go with thread-safe death tests, remember that they rerun the test program from the beginning in the child process. Therefore make sure your program can run side-by-side with itself and is deterministic. スレッドセーフな Death テストを使う場合,子プロセスでテストプログラムが再び最初から実行されることを忘れないでください.つまり,連続的に自分自身を実行し,決定的に動作するプログラムが必要になります. .. In the end, this boils down to good concurrent programming. You have to make sure that there is no race conditions or dead locks in your program. No silver bullet - sorry! 結局のところ,優れた並列プログラミングが必要だということです.プログラム中で,競合状態やデッドロックが決して起こらないようにしなければいけません.銀の弾丸はないのです - ごめんなさい! .. Should I use the constructor/destructor of the test fixture or the set-up/tear-down function? .. _faq_should_i_use_the_constructor_destructor_or_setup_teardown: テストフィクスチャのコンストラクタ/デストラクタと,set-up/tear-down 関数のどちらを使うべきでしょうか? ===================================================================== .. The first thing to remember is that Google Test does not reuse the same test fixture object across multiple tests. For each TEST_F, Google Test will create a fresh test fixture object, immediately call SetUp(), run the test, call TearDown(), and then immediately delete the test fixture object. Therefore, there is no need to write a SetUp() or TearDown() function if the constructor or destructor already does the job. Google Test では,複数のテストで同じテストフィクスチャオブジェクトを再利用したりしない,ということをまず覚えてください.Google Test は,それぞれの TEST_F に対して新しいテストフィクスチャオブジェクトを作成します.そして,SetUp() を すぐに 呼び出し,テストを実行,そして TearDown() を呼び出して,すぐに テストフィクスチャを削除します.したがって,コンストラクタやデストラクタが既にその役割をしているならば,SetUp() や TearDown() 関数を書く必要はありません. .. You may still want to use SetUp()/TearDown() in the following cases: しかし,次のような場合は SetUp()/TearDown() を使いたいと思うかもしれません: .. If the tear-down operation could throw an exception, you must use TearDown() as opposed to the destructor, as throwing in a destructor leads to undefined behavior and usually will kill your program right away. Note that many standard libraries (like STL) may throw when exceptions are enabled in the compiler. Therefore you should prefer TearDown() if you want to write portable tests that work with or without exceptions. .. The Google Test team is considering making the assertion macros throw on platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux client-side), which will eliminate the need for the user to propagate failures from a subroutine to its caller. Therefore, you shouldn't use Google Test assertions in a destructor if your code could run on such a platform. .. In a constructor or destructor, you cannot make a virtual function call on this object. (You can call a method declared as virtual, but it will be statically bound.) Therefore, if you need to call a method that will be overriden in a derived class, you have to use SetUp()/TearDown(). * デストラクタ中で例外が投げられると,未定義の動作がおこり,通常はプログラムが不正終了するので,tear-down 処理が例外を投げる可能性があるならば,デストラクタではなく TearDown() を使うべきです. (STLのような)多くの標準ライブラリは,コンパイラで例外が有効にされた場合には例外を投げます.よって,例外が有効でも無効でも動作するようなポータブルなテストを書きたいならば, TearDown() の方を使うべきでしょう. * Google Test チームは,例外が有効になっているプラットフォーム(例えば,Windows,Mac OS,そして Linux client-side)では,アサーションマクロが例外を投げるようにすることを検討しています.そうすると,ユーザがサブルーチンで発生した失敗を,呼び出し側まで伝播させる必要がなくなります.したがって,このようなプラットフォームでコードを実行するならば,デストラクタで Google Test のアサーションを使うべきではありません. * コンストラクタやデストラクタでは,this オブジェクトの仮想関数呼び出しができません.(virtual として宣言されているメソッドを呼び出すことはできますが,それは静的結合されることになります.)したがって,派生クラスでオーバライドされるメソッドを呼び出す必要がある場合は,SetUp()/TearDown() を使う必要があります. .. The compiler complains "no matching function to call" when I use ASSERT_PREDn. How do I fix it? .. _faq_the_compiler_complains_no_matching_function: ASSERT_PREDn を使うと,コンパイラが "no matching function to call" というエラーを出します.どうやって修正すればよいでしょうか? ======================================================================================= .. If the predicate function you use in ASSERT_PRED* or EXPECT_PRED* is overloaded or a template, the compiler will have trouble figuring out which overloaded version it should use. ASSERT_PRED_FORMAT* and EXPECT_PRED_FORMAT* don't have this problem. ASSERT_PRED* や EXPECT_PRED* で利用する述語関数がオーバーロードされたものだったり,テンプレートだったりすると,コンパイラは,どのオーバーロードバージョンを使うべきか決めるのが難しくなります.ASSERT_PRED_FORMAT* と EXPECT_PRED_FORMAT* では,この問題は起こりません. .. If you see this error, you might want to switch to (ASSERT|EXPECT)_PRED_FORMAT*, which will also give you a better failure message. If, however, that is not an option, you can resolve the problem by explicitly telling the compiler which version to pick. このエラーを見て,分かりやすい失敗メッセージを生成する (ASSERT|EXPECT)_PRED_FORMAT* に変更したいと思うかもしれません.しかし,もしこの方法が選べないならば,コンパイラに利用する関数のバージョンを教えることで,この問題を解決できます. .. For example, suppose you have 例えば,次のように定義されているとします. .. code-block:: c bool IsPositive(int n) { return n > 0; } bool IsPositive(double x) { return x > 0; } .. you will get a compiler error if you write 次のように書くと,コンパイルエラーになります. .. code-block:: c EXPECT_PRED1(IsPositive, 5); .. However, this will work: しかし,次のように書けば問題ありません: .. code-block:: c EXPECT_PRED1(static_cast(IsPositive), 5); .. (The stuff inside the angled brackets for the static_cast operator is the type of the function pointer for the int-version of IsPositive().) (static_cast 演算子のカギ括弧の中は,IsPositive() の int バージョンを表す関数ポインタの型です.) .. As another example, when you have a template function また別の例として,テンプレート関数の場合を考えます. .. code-block:: c template bool IsNegative(T x) { return x < 0; } .. you can use it in a predicate assertion like this: 述語関数アサーションでは,これを次のように利用します: .. code-block:: c ASSERT_PRED1(IsNegative, -5); .. Things are more interesting if your template has more than one parameters. The following won't compile: テンプレートが2つ以上のパラメータを持つ場合は,より興味深いものになります.次のコードは,コンパイルできません: .. code-block:: c ASSERT_PRED2(GreaterThan, 5, 0); .. as the C++ pre-processor thinks you are giving ASSERT_PRED2 4 arguments, which is one more than expected. The workaround is to wrap the predicate function in parentheses: C++ プリプロセッサは,ASSERT_PRED2 に,期待より1つ多い4つの引数が与えられたと考えます.回避策は,述語関数を丸括弧で囲むことです: .. code-block:: c ASSERT_PRED2((GreaterThan), 5, 0); .. My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why? .. _faq_my_compiler_complains_about_ignoring_return_value: RUN_ALL_TESTS() を呼ぶと,コンパイラが "ignoring return value" というエラーを出します.なぜでしょうか? ==================================================================== .. Some people had been ignoring the return value of RUN_ALL_TESTS(). That is, instead of RUN_ALL_TESTS() の戻り値を無視してしまう人が時々います.つまり, .. code-block:: c return RUN_ALL_TESTS(); .. they write と書く代わりに, .. code-block:: c RUN_ALL_TESTS(); .. This is wrong and dangerous. A test runner needs to see the return value of RUN_ALL_TESTS() in order to determine if a test has passed. If your main() function ignores it, your test will be considered successful even if it has a Google Test assertion failure. Very bad. と書く人がいます.これは誤りであり,危険です.テストランナーは,テストが成功したかどうかを決めるために,RUN_ALL_TESTS() の戻り値を知る必要があります.main() 関数がこれを無視すると,Google Test アサーションが失敗した場合でも,テストが成功したと勘違いされてしまいます.これは,よろしくないですね. .. To help the users avoid this dangerous bug, the implementation of RUN_ALL_TESTS() causes gcc to raise this warning, when the return value is ignored. If you see this warning, the fix is simple: just make sure its value is used as the return value of main(). ユーザがこの危険なバグにはまらないように,RUN_ALL_TESTS() の戻り値が無視された場合に gcc が警告をだすように実装されています.この警告を見た場合の修正は簡単です.つまり,その戻り値を main() の戻り値として利用するようにしてください. .. My compiler complains that a constructor (or destructor) cannot return a value. What's going on? .. _faq_my_compiler_complains_that_constructor_cannot_return_a_value: コンパイラが,コンストラクタ(または,デストラクタ)は値を返せません,というエラーを出します.どうなっているのでしょうか? ================================================================================ .. Due to a peculiarity of C++, in order to support the syntax for streaming messages to an ASSERT_*, e.g. ASSERT_* へのストリーミングメッセージの構文,例えば, .. code-block:: c ASSERT_EQ(1, Foo()) << "blah blah" << foo; .. we had to give up using ASSERT* and FAIL* (but not EXPECT* and ADD_FAILURE*) in constructors and destructors. The workaround is to move the content of your constructor/destructor to a private void member function, or switch to EXPECT_*() if that works. This section in the user's guide explains it. をサポートするために,コンストラクタとデストラクタで,ASSERT* と FAIL* (EXPECT* と ADD_FAILURE* は大丈夫)を使うことを断念しました.これは,C++ の特性に依存するものです.これの回避策は,コンストラクタ/デストラクタの中身を,private で void を返すメンバ関数に移動するか,あるいは EXPECT_*() が使えるなら,それに切り替えることです.これに関しては,user's guide の関連セクションで説明されています. .. My set-up function is not called. Why? .. _faq_my_setup_function_is_not_called: set-up 関数が呼ばれません.なぜですか? ========================== .. C++ is case-sensitive. It should be spelled as SetUp(). Did you spell it as Setup()? C++ では,大文字と小文字が区別されます.正しい綴りは SetUp() です.Setup() と書いていませんか? .. Similarly, sometimes people spell SetUpTestCase() as SetupTestCase() and wonder why it's never called. 同じように, SetUpTestCase() を SetupTestCase() と書いてしまい,なんで呼ばれないんだ,と悩む人もいます. .. How do I jump to the line of a failure in Emacs directly? .. _faq_how_do_i_jump_to_the_line_of_a_failure_in_emacs: Emacs で直接,失敗した行に移動するにはどうすればよいでしょうか? =========================================== .. Google Test's failure message format is understood by Emacs and many other IDEs, like acme and XCode. If a Google Test message is in a compilation buffer in Emacs, then it's clickable. You can now hit enter on a message to jump to the corresponding source code, or use C-x ` to jump to the next failure. Google Test の失敗メッセージフォーマットは,Emacs ,そして acme や XCode のような他の多くの IDE でも利用できます. Google Test のメッセージが Emacs のコンパイルバッファに表示されたら,それをクリックすることができます.メッセージを選択してエンターキーを押すとソースコード中の対応する場所に移動し,C-x を押すと次の失敗地点に移動します. .. I have several test cases which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious. .. _faq_i_have_several_test_cases_which_share_the_same_test_fixture: 同じテストフィクスチャロジックを共有する,複数のテストケースがあります.毎回,新しいテストフィクスチャクラスを定義する必要がありますか?面倒なのですが. =================================================================================================== .. You don't have to. Instead of その必要はありません. .. code-block:: c class FooTest : public BaseTest {}; TEST_F(FooTest, Abc) { ... } TEST_F(FooTest, Def) { ... } class BarTest : public BaseTest {}; TEST_F(BarTest, Abc) { ... } TEST_F(BarTest, Def) { ... } .. you can simply typedef the test fixtures: と書く代わりに,テストフィクスチャを typedef すれば良いだけです: .. code-block:: c typedef BaseTest FooTest; TEST_F(FooTest, Abc) { ... } TEST_F(FooTest, Def) { ... } typedef BaseTest BarTest; TEST_F(BarTest, Abc) { ... } TEST_F(BarTest, Def) { ... } .. The Google Test output is buried in a whole bunch of log messages. What do I do? .. _faq_the_google_test_output_is_buried_in: Google Test の出力が,ログメッセージ全体に埋もれてしまいます.どうすればよいでしょうか? ========================================================================================= .. The Google Test output is meant to be a concise and human-friendly report. If your test generates textual output itself, it will mix with the Google Test output, making it hard to read. However, there is an easy solution to this problem. Google Test の出力は,簡潔で人間が読みやすいレポートになるように作られています.テストがテキスト出力を生成すると,Google Test の出力と混ざって読みにくくなります.しかし,この問題には簡単な解決法があります. .. Since most log messages go to stderr, we decided to let Google Test output go to stdout. This way, you can easily separate the two using redirection. For example: ほとんどのログメッセージは標準エラー出力に送られるので,我々は Google Test 出力を標準出力に出すようにしました.この場合,リダイレクトを利用して2つを簡単に分けることができます. 例を示しましょう: :: ./my_test > googletest_output.txt .. Why should I prefer test fixtures over global variables? .. _faq_why_should_i_prefer_test_fixtures_over_global_variables: グローバル変数よりもテストフィクスチャの方を使うべきなのはなぜですか? ============================================== .. There are several good reasons: それには,いくつかの理由があります: .. It's likely your test needs to change the states of its global variables. This makes it difficult to keep side effects from escaping one test and contaminating others, making debugging difficult. By using fixtures, each test has a fresh set of variables that's different (but with the same names). Thus, tests are kept independent of each other. .. Global variables pollute the global namespace. .. Test fixtures can be reused via subclassing, which cannot be done easily with global variables. This is useful if many test cases have something in common. * テストで,グローバル変数の状態を変更する必要がでてくるかもしれません.これによって,あるテストの副作用が別のテストに影響しないようにするのが難しくなり,デバッグが困難になります.フィクスチャを使うと,各テストで新しい(同じ名前の)変数が利用できます.したがって,それぞれのテストの独立性が維持されます. * グローバル変数は,グローバルな名前空間を汚染します. * テストフィクスチャは,派生クラスを使って再利用することができますが,グローバル変数ではそれは簡単ではありません.多くのテストケースに共通するものがある場合,これは便利です. .. How do I test private class members without writing FRIEND_TEST()s? .. _faq_how_do_i_test_private_class_members: FRIEND_TEST() を使わずに private なクラスメンバをテストするにはどうすればよいでしょうか? ============================================================================================================ .. You should try to write testable code, which means classes should be easily tested from their public interface. One way to achieve this is the Pimpl idiom: you move all private members of a class into a helper class, and make all members of the helper class public. まず,テスト可能なコード,つまり public なインタフェースから簡単にテストできるクラスを書けないか試してみるべきです.このための手段の1つが,Pimplイディオムです:つまり,クラスの private メンバをすべて helper クラスに移動して,helper クラスの全てのメンバを public にします. .. You have several other options that don't require using FRIEND_TEST: FRIEND_TEST を使わずに済む手段は他にもあります: .. Write the tests as members of the fixture class: * テストを,フィクスチャクラスのメンバとして書いてください: .. code-block:: c class Foo { friend class FooTest; ... }; class FooTest : public ::testing::Test { protected: ... void Test1() {...} // これは Foo クラスの private メンバにアクセスできます. void Test2() {...} // こちらも同様です. }; TEST_F(FooTest, Test1) { Test1(); } TEST_F(FooTest, Test2) { Test2(); } .. In the fixture class, write accessors for the tested class' private members, then use the accessors in your tests: * フィクスチャクラスに,テストされるクラスの private メンバのアクセサを書いて,テストではそのアクセサを使ってください: .. code-block:: c class Foo { friend class FooTest; ... }; class FooTest : public ::testing::Test { protected: ... T1 get_private_member1(Foo* obj) { return obj->private_member1_; } }; TEST_F(FooTest, Test1) { ... get_private_member1(x) ... } .. If the methods are declared protected, you can change their access level in a test-only subclass: * メソッドが protected として宣言されているならば,テスト用サブクラスでアクセスレベルを変更できます: .. code-block:: c class YourClass { ... protected: // テストしやすいように protected int DoSomethingReturningInt(); ... }; // your_class_test.cc ファイルに書きます. class TestableYourClass : public YourClass { ... public: using YourClass::DoSomethingReturningInt; // アクセス権を変更 ... }; TEST_F(YourClassTest, DoSomethingTest) { TestableYourClass obj; assertEquals(expected_value, obj.DoSomethingReturningInt()); } .. How do I test private class static members without writing FRIEND_TEST()s? .. _faq_how_do_i_ispvas_you_account: FRIEND_TEST() を使わずに private で static なクラスメンバをテストするにはどうすればよいでしょうか? ===================================================================================================== .. We find private static methods clutter the header file. They are implementation details and ideally should be kept out of a .h. So often I make them free functions instead. private な static メソッドがヘッダファイルに散乱しているのを見かけます.それは,実装部分であり,理想を言えば .h ファイルの外部で定義されるべきです.それらをクラスに属さない関数に変更するのは,よくやられる方法です. .. Instead of: 例えば, .. code-block:: c // foo.h class Foo { ... private: static bool Func(int n); }; // foo.cc bool Foo::Func(int n) { ... } // foo_test.cc EXPECT_TRUE(Foo::Func(12345)); .. You probably should better write: と書く代わりに,次のように書くと良いでしょう: .. code-block:: c // foo.h class Foo { ... }; // foo.cc namespace internal { bool Func(int n) { ... } } // foo_test.cc namespace internal { bool Func(int n); } EXPECT_TRUE(internal::Func(12345)); .. I would like to run a test several times with different parameters. Do I need to write several similar copies of it? .. _faq_i_would_like_to_run_a_test_several_times_with_different_params: 異なるパラメータを与えてテストを複数回実行したいのですが,同じことを何度も書く必要がありますか? ================================================================================================================================= .. No. You can use a feature called [V1_6_AdvancedGuide#Value_Parameterized_Tests value-parameterized tests] which lets you repeat your tests with different parameters, without defining it more than once. いいえ. :ref:`adv_value_parameterized_tests` と呼ばれる機能を使うことができます.これによって,改めてテストを定義しなくても,異なるパラメータを与えてテストを繰り返すことが可能になります. .. How do I test a file that defines main()? .. _faq_how_do_i_test_a_file_that_defines_main: main() が定義されているソースファイルをテストするにはどうすればよいでしょうか? ======================================================================================== .. To test a foo.cc file, you need to compile and link it into your unit test program. However, when the file contains a definition for the main() function, it will clash with the main() of your unit test, and will result in a build error. foo.cc ファイルをテストするには,それをコンパイルして,ユニットテストプログラムにリンクする必要があります.しかし,ファイル内で main() 関数が定義されていると,ユニットテストは main() でクラッシュし,その結果ビルドエラーになります. .. The right solution is to split it into three files: 正しい解決法は,3つのファイルに分割することです: .. foo.h which contains the declarations, .. foo.cc which contains the definitions except main(), and .. foo_main.cc which contains nothing but the definition of main(). * 宣言が書かれた foo.h. * main() 以外の定義が書かれた foo.cc. * main() の定義だけが書かれた foo_main.cc .. Then foo.cc can be easily tested. foo.cc は,簡単にテストできます. .. If you are adding tests to an existing file and don't want an intrusive change like this, there is a hack: just include the entire foo.cc file in your unit test. For example: 既存のファイルにテストを追加している途中で,このような煩わしい変更をしたくないならば別の方法もあります:つまり単に,ユニットテストに foo.cc ファイル全体をインクルードするという方法です.以下に例を示します: .. code-block:: c // foo_unittest.cc ファイル // ヘッダファイル ... // ユニットテストに main() があるので,foo.cc の main() の名前を変更します. #define main FooMain #include "a/b/foo.cc" // ここから,テストを書きます. ... .. However, please remember this is a hack and should only be used as the last resort. ただし,これはあくまでもハックであり,最後の手段として使うべきものであることを忘れないでください. .. What can the statement argument in ASSERT_DEATH() be? .. _faq_what_can_the_statement_argument_in_ASSERT_DEATH: ASSERT_DEATH() の statement 引数には何を与えられますか? ========================================================================== .. ASSERT_DEATH(_statement_, _regex_) (or any death assertion macro) can be used wherever _statement_ is valid. So basically _statement_ can be any C++ statement that makes sense in the current context. In particular, it can reference global and/or local variables, and can be: ASSERT_DEATH(_statement_, _regex_)(または,任意の Death アサーションマクロ)は,_statement_ が有効な場所ならどこでも利用できます.通常,_statement_ には,現在のコンテキストで意味が通る任意の C++ の文が利用できます.具体的には,グローバル変数,ローカル変数を自由に参照できる,次のような文が利用可能です: .. a simple function call (often the case), .. a complex expression, or .. a compound statement. * 関数の単純な呼び出し(よくあるケース) * 複雑な式 * 複合文 .. Some examples are shown here: 以下にいくつかの例を示します: .. code-block:: c // Death テストでは,単純な関数呼び出しが使えます. TEST(MyDeathTest, FunctionCall) { ASSERT_DEATH(Xyz(5), "Xyz failed"); } // また,変数と関数を参照する複雑な式も使えます. TEST(MyDeathTest, ComplexExpression) { const bool c = Condition(); ASSERT_DEATH((c ? Func1(0) : object2.Method("test")), "(Func1|Method) failed"); } // Death アサーションは,関数のどこでも利用できます. // ループ内部でも利用できます. TEST(MyDeathTest, InsideLoop) { // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die. for (int i = 0; i < 5; i++) { EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors", ::testing::Message() << "where i is " << i); } } // Death テストでは,複合文を使うこともできます. TEST(MyDeathTest, CompoundStatement) { // Bar(0), Bar(1), ..., Bar(4) の少なくとも1つが // クラッシュすることを確認します. ASSERT_DEATH({ for (int i = 0; i < 5; i++) { Bar(i); } }, "Bar has \\d+ errors");} .. googletest_unittest.cc contains more examples if you are interested. もし興味があれば,googletest_unittest.cc により多くのサンプルが含まれています. .. What syntax does the regular expression in ASSERT_DEATH use? .. _faq_what_syntax_does_the_regular_expression: ASSERT_DEATH で利用される正規表現の構文はどのようになっていますか? ======================================================================== .. On POSIX systems, Google Test uses the POSIX Extended regular expression syntax (http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions). On Windows, it uses a limited variant of regular expression syntax. For more details, see the [V1_6_AdvancedGuide#Regular_Expression_Syntax regular expression syntax]. POSIX システム上の Google Test では, `POSIX 拡張正規表現構文 `_ を利用します.詳細は, :ref:`adv_regular_expression_syntax` の項を参照してください. .. I have a fixture class Foo, but TEST_F(Foo, Bar) gives me error "no matching function for call to Foo::Foo()". Why? .. _faq_i_have_a_fixture_class_foo: フィクスチャクラス Foo は定義されているのですが,TEST_F(Foo, Bar) で "no matching function for call to Foo::Foo()" というエラーが出ます.なぜですか? ===================================================================================================================================================== .. Google Test needs to be able to create objects of your test fixture class, so it must have a default constructor. Normally the compiler will define one for you. However, there are cases where you have to define your own: Google Test が,テストフィクスチャクラスのオブジェクトを作れなければならないので,必ずデフォルトコンストラクタが必要です.通常,コンパイラはそれを1つ自動的に定義します.しかし,自分自身で定義しなければならない場合があります: .. If you explicitly declare a non-default constructor for class Foo, then you need to define a default constructor, even if it would be empty. .. If Foo has a const non-static data member, then you have to define the default constructor and initialize the const member in the initializer list of the constructor. (Early versions of gcc doesn't force you to initialize the const member. It's a bug that has been fixed in gcc 4.) * Foo クラスのデフォルトではないコンストラクタを明示的に宣言している場合,中身が空でも良いので,デフォルトコンストラクタを定義する必要があります. * Foo に,const かつ static ではないデータメンバが含まれる場合,デフォルトコンストラクタを定義して,なおかつ, そのコンストラクタの初期化リストで const メンバを初期化する必要があります.(gcc の初期バージョンでは,const メンバの初期化は必須ではありません.このバグは gcc 4 で修正されています.) .. Why does ASSERT_DEATH complain about previous threads that were already joined? .. _faq_why_does_ASSERT_DEATH_complain_about_previous_threads: 既に join されている以前のスレッドについて,ASSERT_DEATH がエラーを出すのはなぜですか? ================================================================================================ .. With the Linux pthread library, there is no turning back once you cross the line from single thread to multiple threads. The first time you create a thread, a manager thread is created in addition, so you get 3, not 2, threads. Later when the thread you create joins the main thread, the thread count decrements by 1, but the manager thread will never be killed, so you still have 2 threads, which means you cannot safely run a death test. Linux pthread ライブラリを利用した場合,1度シングルスレッドからマルチスレッドになると,それを戻す方法はありません.初めてスレッドを作成するときに,追加で管理スレッドが作られます.つまり,2スレッドではなく,3スレッドになります.作成したスレッドがメインスレッドに join するとき,スレッドカウントが1つ減りますが,管理スレッドが殺されることはありませんので,2スレッドが動作していることになります.つまり,Death テストを安全に実行することができない,ということです. .. The new NPTL thread library doesn't suffer from this problem, as it doesn't create a manager thread. However, if you don't control which machine your test runs on, you shouldn't depend on this. 新しい NPTL スレッドライブラリは管理スレッドを作成しないので,この問題で悩むことはありません.しかし,どのマシンでテストを実行するかを制御しない場合は,この方法に頼ることはできません. .. Why does Google Test require the entire test case, instead of individual tests, to be named FOODeathTest when it uses ASSERT_DEATH? .. _faq_why_does_google_test_require_the_entire_test_case: Google Test で ASSERT_DEATH を利用する場合,FOODeathTest という名前にするために,個々のテスト名ではなくテストケース名が必要になりますが,これはなぜですか? ==================================================================================================================================================================== .. Google Test does not interleave tests from different test cases. That is, it runs all tests in one test case first, and then runs all tests in the next test case, and so on. Google Test does this because it needs to set up a test case before the first test in it is run, and tear it down afterwords. Splitting up the test case would require multiple set-up and tear-down processes, which is inefficient and makes the semantics unclean. Google Test は,異なるテストケースのテストを混ぜることはしません.つまり,まず1つのテストケースの全テストが実行され,さらに次のテストケースの全テストが実行され,と続いていきます.Google Test がこのように動作する理由は,テストケース内の最初のテストが実行されるよりも前にテストケースを初期化し,最後に終了処理をする必要があるからです.テストケースを分割すると,初期化と終了の処理が複数必要になり,非効率的で動作も複雑になります. .. If we were to determine the order of tests based on test name instead of test case name, then we would have a problem with the following situation: もし,テストケース名ではなくテスト名に基づいてテストの順序を決めていたら,次のような状況で問題になっていたでしょう: .. code-block:: c TEST_F(FooTest, AbcDeathTest) { ... } TEST_F(FooTest, Uvw) { ... } TEST_F(BarTest, DefDeathTest) { ... } TEST_F(BarTest, Xyz) { ... } .. Since FooTest.AbcDeathTest needs to run before BarTest.Xyz, and we don't interleave tests from different test cases, we need to run all tests in the FooTest case before running any test in the BarTest case. This contradicts with the requirement to run BarTest.DefDeathTest before FooTest.Uvw. FooTest.AbcDeathTest は BarTest.Xyz よりも前に実行する必要があり,異なるテストケースのテストを混ぜないとなると,BarTest テストケースのどのテストよりも前に,FooTest テストケースの全てのテストを実行する必要があります.しかしこれは,FooTest.Uvw よりも前に BarTest.DefDeathTest を実行するという要件に矛盾します. .. But I don't like calling my entire test case FOODeathTest when it contains both death tests and non-death tests. What do I do? .. _faq_but_i_dont_like_calling_my_entire_test_case: Death テストと通常のテストの両方を含むテストケースを,FOODeathTest という名前にするのが気に入りません. どうすればよいでしょうか? ================================================================================================================================================== .. You don't have to, but if you like, you may split up the test case into FooTest and FooDeathTest, where the names make it clear that they are related: とくに必要があるわけではないのですが,もし望むならば,テストケースを FooTest と FooDeathTest に分割して,名が体を表すようにもできます: .. code-block:: c class FooTest : public ::testing::Test { ... }; TEST_F(FooTest, Abc) { ... } TEST_F(FooTest, Def) { ... } typedef FooTest FooDeathTest; TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... } TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... } .. The compiler complains about "no match for 'operator<<'" when I use an assertion. What gives? .. _faq_the_compiler_complains_about_no_match_for_operator: アサーションを使うと,コンパイラが "no match for 'operator<<'" というエラーを出します.どういうことでしょうか? ====================================================================================================================== .. If you use a user-defined type FooType in an assertion, you must make sure there is an std::ostream& operator<<(std::ostream&, const FooType&) function defined such that we can print a value of FooType. アサーションでユーザ定義型 FooType を利用する場合は,FooType の値を出力するための std::ostream& operator<<(std::ostream&, const FooType&) 関数が定義されていることを確認してください. .. In addition, if FooType is declared in a name space, the << operator also needs to be defined in the same name space. さらに,ある名前空間内で FooType が宣言されている場合,この << 演算子も,同じ 名前空間で定義される必要があります. .. How do I suppress the memory leak messages on Windows? .. _faq_how_do_i_suppress_the_memory_leak_messages: Windows でメモリリークのメッセージを表示させないようにするにはどうすればよいでしょうか? ========================================================================================== .. Since the statically initialized Google Test singleton requires allocations on the heap, the Visual C++ memory leak detector will report memory leaks at the end of the program run. The easiest way to avoid this is to use the _CrtMemCheckpoint and _CrtMemDumpAllObjectsSince calls to not report any statically initialized heap objects. See MSDN for more details and additional heap check/debug routines. 静的に初期化される Google Test シングルトンは,ヒープ上に配置される必要があるので,プログラム実行終了時に,Visual C++ メモリリーク検出器がメモリリークを報告します.これを避ける最も簡単な方法は,_CrtMemCheckpoint と _CrtMemDumpAllObjectsSince を呼んで,静的に初期化されたヒープオブジェクトを無視することです.詳細やヒープチェック/デバッグの方法については,MSDN を参照してください. .. I am building my project with Google Test in Visual Studio and all I'm getting is a bunch of linker errors (or warnings). Help! .. _faq_i_am_building_my_project_with_google_test_in_VC: Google Test を使ったプロジェクトを Visual Studio でビルドしていますが,大量のリンカエラー(または警告)が出ます.助けてください! ======================================================================================================================================= .. You may get a number of the following linker error or warnings if you attempt to link your test project with the Google Test library when your project and the are not built using the same compiler settings. テストプロジェクトと Google Test が同じコンパイラフラグでコンパイルされていない場合に,そのプロジェクトを Google Test ライブラリにリンクしようとすると,次のようなリンカエラーや警告が大量にでる可能性があります. * LNK2005: symbol already defined in object * LNK4217: locally defined symbol 'symbol' imported in function 'function' * LNK4049: locally defined symbol 'symbol' imported .. The Google Test project (gtest.vcproj) has the Runtime Library option set to /MT (use multi-threaded static libraries, /MTd for debug). If your project uses something else, for example /MD (use multi-threaded DLLs, /MDd for debug), you need to change the setting in the Google Test project to match your project's. Google Test プロジェクト(gtest.vcproj)では,ランタイムライブラリオプションが /MT(マルチスレッドスタティクライブラリを利用,/MTd はデバッグ用)にセットされています.あなたのプロジェクトが,何か別のオプション,例えば /MD(マルチスレッドDLLを利用,/MDdはデバッグ用)を使う場合,Google Test プロジェクトの設定もそれに合わせて変更する必要があります. .. To update this setting open the project properties in the Visual Studio IDE then select the branch Configuration Properties | C/C++ | Code Generation and change the option "Runtime Library". You may also try using gtest-md.vcproj instead of gtest.vcproj. この設定を更新するためには,Visual Studio IDE でプロジェクトのプロパティを開いて,構成プロパティ|C/C++|コード生成 のオプション "ランタイムライブラリ" のオプションを変更してください.また,gtest.vcproj の代わりに gtest-md.vcproj を利用してみるのもよいでしょう. .. I put my tests in a library and Google Test doesn't run them. What's happening? .. _faq_i_put_my_tests_in_a_library: テストをライブラリの中に書いているのですが,Google Test が実行してくれません.どうなっているのでしょうか? ============================================================================================================ .. Have you read a warning on the Google Test Primer page? :ref:`primer_important_note_4vc` を読みましたか? .. I want to use Google Test with Visual Studio but don't know where to start. .. _faq_i_want_to_use_google_test_with_VC: Visual Studio で Google Test を使いたいのですが,何から始めればよいかわかりません. =================================================================================== .. Many people are in your position and one of the posted his solution to our mailing list. Here is his link: http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html. 多く人が同じことを考えており,そのうちの1人がメーリングリストに解決法を投稿してくれました.以下が,彼のリンクです: http://hassanjamilahmad.blogspot.com/2009/07/gtest-starters-help.html .. I am seeing compile errors mentioning std::type_traits when I try to use Google Test on Solaris. .. _faq_i_am_seeing_compile_errors_mentioning_std_type_traits: Solaris で Google Test を使おうとすると,std::type_traits に関するコンパイルエラーが出ます. ===================================================================================================== .. Google Test uses parts of the standard C++ library that SunStudio does not support. Our users reported success using alternative implementations. Try running the build after runing this commad: Google Test は,SunStudio がサポートしていない標準 C++ ライブラリを一部利用しています.代替となる実装を利用して動作を成功させた報告がありました.以下のコマンドを実行した後にビルドしてみてください: :: export CC=cc CXX=CC CXXFLAGS='-library=stlport4' .. How can my code detect if it is running in a test? .. _faq_how_can_my_code_detect_if_it_is_running_in_a_test: 自分のコードがテスト内で実行されているかどうかを検出するにはどうすればいいでしょうか? ========================================================================================== .. If you write code that sniffs whether it's running in a test and does different things accordingly, you are leaking test-only logic into production code and there is no easy way to ensure that the test-only code paths aren't run by mistake in production. Such cleverness also leads to Heisenbugs. Therefore we strongly advise against the practice, and Google Test doesn't provide a way to do it. テスト内で実行されているかどうかを検出し,それに応じて挙動を変えるコードを書くと,テスト用ロジックが製品に混入してしまいます.テスト用コードが製品でうっかり実行されない事を確実にするのは,容易ではありません.また,このような愚かな行為は,不確定性バグを生み出すことにもつながります.したがって,このような行為をしないように強く勧めますし,Google Test には,そのような機能は用意されていません. .. In general, the recommended way to cause the code to behave differently under test is dependency injection. You can inject different functionality from the test and from the production code. Since your production code doesn't link in the for-test logic at all, there is no danger in accidentally running it. 一般的に,テスト時に異なる動作をさせるたに推奨される方法は,依存性の注入です.テストや製品コードからの異なる機能を注入することができます.製品コードは,テスト用ロジックには全くリンクされないので,それが実際に実行される危険はありません. .. However, if you really, really, really have no choice, and if you follow the rule of ending your test program names with _test, you can use the horrible hack of sniffing your executable name (argv[0] in main()) to know whether the code is under test. しかし,全く,ほんとうに,どうしても他に選択肢がないならば,そして,テストプログラム名を _test で終わるものにするというルールを守るならば,そのコードがテストかどうかを知るために実行プログラム名を検出する(main() の argv[0])という酷いハックもあります. .. Google Test defines a macro that clashes with one defined by another library. How do I deal with that? .. _faq_google_test_defines_a_macro_that_clashes_with_one_defined_by_another_library: Google Test で,他のライブラリと衝突するマクロが定義されています.どうすれば良いでしょうか. ============================================================================== .. In C++, macros don't obey namespaces. Therefore two libraries that both define a macro of the same name will clash if you #include both definitions. In case a Google Test macro clashes with another library, you can force Google Test to rename its macro to avoid the conflict. C++ では,マクロは名前空間に従いません.したがって,同じ名前のマクロを定義する2つのライブラリは,両方の定義を #include すると衝突します.Google Test マクロが他のライブラリと衝突する場合, Google Test のマクロを強制的にリネームして衝突を回避することができます. .. Specifically, if both Google Test and some other code define macro FOO, you can add 特に,Google Test と別のコードが共にマクロ FOO を定義している場合,コンパイラフラグに :: -DGTEST_DONT_DEFINE_FOO=1 .. to the compiler flags to tell Google Test to change the macro's name from FOO to GTEST_FOO. For example, with -DGTEST_DONT_DEFINE_TEST=1, you'll need to write を追加して,Google Test にマクロ名を FOO から GTEST_FOO に変えさせることができます.例えば,-DGTEST_DONT_DEFINE_TEST=1 とした場合,テストを定義するには, :: TEST(SomeTest, DoesThis) { ... } .. instead of の代わりに, :: GTEST_TEST(SomeTest, DoesThis) { ... } .. in order to define a test. と書く必要があります. .. Currently, the following TEST, FAIL, SUCCEED, and the basic comparison assertion macros can have alternative names. You can see the full list of covered macros here. More information can be found in the "Avoiding Macro Name Clashes" section of the README file. 正確には,TEST,FAIL,SUCCEED および基本的な比較アサーションマクロは,別の名前を持つことができます.対象となるマクロの完全な一覧は `ここ `_ で見ることができます.また,より詳細な情報は,README ファイルの "Avoiding Macro Name Clashes" セクションで述べられています. .. My question is not covered in your FAQ! .. _faq_my_question_is_not_covered_in_your_faq: 知りたいことが,この FAQ に載ってないのですが. ================================================================== .. If you cannot find the answer to your question in this FAQ, there are some other resources you can use: もし,疑問の答えがこの FAQ に載っていない場合でも,他にも利用できるリソースがあります: .. read other wiki pages, .. search the mailing list archive, .. ask it on googletestframework@googlegroups.com and someone will answer it (to prevent spam, we require you to join the discussion group before you can post.). #. 他の :ref:`ページ ` を読んでください #. メーリングリストの `アーカイブ `_ を探してください #. googletestframework@googlegroups.com で質問すると,誰かが答えてくれるかもしれません(スパム防止のため,投稿前に `ディスカッショングループ `_ に参加する必要があります). .. Please note that creating an issue in the issue tracker is not a good way to get your answer, as it is monitored infrequently by a very small number of people. `issue tracker `_ は,ごく少数の人間がたまに見ているだけなので,質問に答えてもらうために,ここに issue を作成するのは良い方法ではありません. .. When asking a question, it's helpful to provide as much of the following information as possible (people cannot help you if there's not enough information in your question): 質問するときは,以下の情報をできるだけ多く提示することが役に立ちます(質問に関する情報が十分でなければ,手助けできません): .. the version (or the revision number if you check out from SVN directly) of Google Test you use (Google Test is under active development, so it's possible that your problem has been solved in a later version), .. your operating system, .. the name and version of your compiler, .. the complete command line flags you give to your compiler, .. the complete compiler error messages (if the question is about compilation), .. the actual code (ideally, a minimal but complete program) that has the problem you encounter. * 利用している Google Test のバージョン(SVN から直接チェックアウトしているならば,リビジョン番号.Google Test は開発中なので,最新バージョンで問題が解決されている可能性もあります) * 使っている OS * コンパイラの名前とバージョン * コンパイル時のコマンドラインフラグすべて * (質問がコンパイルに関することならば,)コンパイルエラーメッセージすべて * 問題を起こす実際のコード(理想的には,最小限かつ動作可能なプログラム)