.. _FAQ: ======== よくある質問 ======== .. Google C++ Mocking Framework FAQ *Google C++ Mocking Framework のよくある質問* * :ref:`faq_when_i_call_a_method_on_my_mock_object_the_method_for_the_real_object_is_invoked_instead` * :ref:`faq_i_write_some_matchers_no_longer_compile` * :ref:`faq_do_i_have_to_use_google_test_as_the _testing_framework` * :ref:`faq_how_am_i_supposed_to_make_sense_of_these_horrible_template_errors` * :ref:`faq_can_i_mock_a_variadic_function` * :ref:`faq_msvc_gives_me_warning_c4301_or_c4373_when_const` * :ref:`faq_i_have_a_huge_mock_class_runs_out_of_memory_when_compiling_it` * :ref:`faq_i_cant_figure_out_why_googlemock_thinks_my_expecations_are_not_satisfied` * :ref:`faq_how_can_i_assert_that_a_function_is_never_called` * :ref:`faq_googlemock_tells_me_twice_that_a_particular_expectation_is_not_satisified` * :ref:`faq_i_get_a_heap_check_failure_with_mock_not_real_object` * :ref:`faq_the_newer_override_older_rule_make_awkward` * :ref:`faq_gmock_prints_a_warning_when_a_function_without_expect_call_is_called_even_if_i_have_set_its_behavior` * :ref:`faq_how_can_i_delete_the_mock_functions_argument_in_an_action` * :ref:`faq_mock_methodn()s_second_argument_looks_funny` * :ref:`faq_my_code_calls_a_static_global_function_can_i_mock_it` * :ref:`faq_my_mock_object_needs_to_do_complex_stuff` * :ref:`faq_i_got_a_warning_uninteresting_function_call_encountered` * :ref:`faq_i_want_to_define_a_custom_aciton` * :ref:`faq_im_using_the_set-argument-pointee_action` * :ref:`faq_my_question_is_not_in_your_faq__mock` .. Please send your questions to the googlemock discussion group. If you need help with compiler errors, make sure you have tried Google Mock Doctor first. 質問は, `googlemock `_ ディスカッショングループに送ってください.また,コンパイルエラーで困っているならば,まずは :ref:`Google Mock Doctor ` を試してください. .. _faq_when_i_call_a_method_on_my_mock_object_the_method_for_the_real_object_is_invoked_instead: .. When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? モックオブジェクトのメソッドを呼び出すと,代わりに実際のオブジェクトのメソッドが呼び出されてしまいます.何が問題なのでしょうか? ========================================================================================== .. In order for a method to be mocked, it must be virtual, unless you use the high-perf dependency injection technique. モック化されるメソッドは仮想関数である必要があります.例外は, :ref:`高効率な依存性の注入 ` のテクニックを使う場合のみです. .. I wrote some matchers. After I upgraded to a new version of Google Mock, they no longer compile. What's going on? .. _faq_i_write_some_matchers_no_longer_compile: Google Mock のバージョンを更新すると,以前書いた matcher がコンパイルできなくなったのですが,何が起こったのでしょうか? ============================================================================================================= .. After version 1.4.0 of Google Mock was released, we had an idea on how to make it easier to write matchers that can generate informative messages efficiently. We experimented with this idea and liked what we saw. Therefore we decided to implement it. Google Mock バージョン 1.4.0 がリリースされた後,我々は,役立つメッセージを効率的に生成することができる matcher をより簡単に書くためのアイディアを思いつきました.このアイディアを試してみて,気に入ったので,それを実装することにしたのです. .. Unfortunately, this means that if you have defined your own matchers by implementing MatcherInterface or using MakePolymorphicMatcher(), your definitions will no longer compile. Matchers defined using the MATCHER* family of macros are not affected. 残念なことに,MatcherInterface を実装したり,MakePolymorphicMatcher() を使用したりして,ユーザが独自の matcher を定義している場合,その定義はコンパイルできないことになります.MATCHER* 形式のマクロを使って定義された matcher には影響がありません. .. Sorry for the hassle if your matchers are affected. We believe it's in everyone's long-term interest to make this change sooner than later. Fortunately, it's usually not hard to migrate an existing matcher to the new API. Here's what you need to do: もし,あなたの matcher が影響を受けたのなら,お手数をおかけします.我々は,すぐにでもこの変更を行うことが,ユーザ全員の長期的利益になると信じています.幸いなことに,既存の matcher を,新しい API に移植するのは通常は難しいことではありません.以下に,必要な作業を示します: .. If you wrote your matcher like this: あなたの matcher が,次のように書かれていたとします: .. code-block:: c // 最新の Google Mock では動作しない, // 古い matcher 定義 using ::testing::MatcherInterface; ... class MyWonderfulMatcher : public MatcherInterface { public: ... virtual bool Matches(MyType value) const { // value がマッチすると true を返します. return value.GetFoo() > 5; } ... }; .. you'll need to change it to: これを,次のように書き換える必要があります: .. code-block:: c // 最新の Google Mock で動作する,新しい matcher 定義. using ::testing::MatcherInterface; using ::testing::MatchResultListener; ... class MyWonderfulMatcher : public MatcherInterface { public: ... virtual bool MatchAndExplain(MyType value, MatchResultListener* listener) const { // value がマッチすると true を返します. return value.GetFoo() > 5; } ... }; .. (i.e. rename Matches() to MatchAndExplain() and give it a second argument of type MatchResultListener*.) (つまり,名前を Matches() から MatchAndExplain() に変更し,2番目の引数に MatchResultListener* を与えます.) .. If you were also using ExplainMatchResultTo() to improve the matcher message: matcher のメッセージを改良するために,ExplainMatchResultTo() も利用しているならば: .. code-block:: c // 最新の Google Mock では動作しない, // 古い matcher 定義 using ::testing::MatcherInterface; ... class MyWonderfulMatcher : public MatcherInterface { public: ... virtual bool Matches(MyType value) const { // value がマッチすると true を返します. return value.GetFoo() > 5; } virtual void ExplainMatchResultTo(MyType value, ::std::ostream* os) const { // なぜ value がマッチしたのか(または,しなかったのか) // を表す,有用な情報を os に出力します. *os << "the Foo property is " << value.GetFoo(); } ... }; .. you should move the logic of ExplainMatchResultTo() into MatchAndExplain(), using the MatchResultListener argument where the ::std::ostream was used: ::std::ostream が利用されていた箇所で MatchResultListener の引数を利用して,ExplainMatchResultTo() のロジックを,MatchAndExplain() に移動する必要があります. .. code-block:: c // 最新の Google Mock で動作する,新しい matcher 定義. using ::testing::MatcherInterface; using ::testing::MatchResultListener; ... class MyWonderfulMatcher : public MatcherInterface { public: ... virtual bool MatchAndExplain(MyType value, MatchResultListener* listener) const { // value がマッチすると true を返します. *listener << "the Foo property is " << value.GetFoo(); return value.GetFoo() > 5; } ... }; .. If your matcher is defined using MakePolymorphicMatcher(): MakePolymorphicMatcher() を用いて matcher を定義している場合: .. code-block:: c // 最新の Google Mock では動作しない, // 古い matcher 定義 using ::testing::MakePolymorphicMatcher; ... class MyGreatMatcher { public: ... bool Matches(MyType value) const { // value がマッチすると true を返します. return value.GetBar() < 42; } ... }; ... MakePolymorphicMatcher(MyGreatMatcher()) ... .. you should rename the Matches() method to MatchAndExplain() and add a MatchResultListener* argument (the same as what you need to do for matchers defined by implementing MatcherInterface): Matches() メソッドを MatchAndExplain() にリネームして,MatchResultListener* 引数を追加してください(MatcherInterface を実装して定義した matcher の場合と,やることは同じです): .. code-block:: c // 最新の Google Mock で動作する,新しい matcher 定義. using ::testing::MakePolymorphicMatcher; using ::testing::MatchResultListener; ... class MyGreatMatcher { public: ... bool MatchAndExplain(MyType value, MatchResultListener* listener) const { // value がマッチする場合に true を返します. return value.GetBar() < 42; } ... }; ... MakePolymorphicMatcher(MyGreatMatcher()) ... .. If your polymorphic matcher uses ExplainMatchResultTo() for better failure messages: ポリモーフィック matcher で,失敗メッセージを分かりやすくするために ExplainMatchResultTo() を使用している場合: .. code-block:: c // 最新の Google Mock では動作しない, // 古い matcher 定義 using ::testing::MakePolymorphicMatcher; ... class MyGreatMatcher { public: ... bool Matches(MyType value) const { // value がマッチすると true を返します. return value.GetBar() < 42; } ... }; void ExplainMatchResultTo(const MyGreatMatcher& matcher, MyType value, ::std::ostream* os) { // なぜ value がマッチしたのか(または,しなかったのか) // を表す,有用な情報を os に出力します. *os << "the Bar property is " << value.GetBar(); } ... MakePolymorphicMatcher(MyGreatMatcher()) ... .. you'll need to move the logic inside ExplainMatchResultTo() to MatchAndExplain(): ExplainMatchResultTo() 内部のロジックを MatchAndExplain() に移動する必要があります: .. code-block:: c // 最新の Google Mock で動作する新しい matcher 定義. using ::testing::MakePolymorphicMatcher; using ::testing::MatchResultListener; ... class MyGreatMatcher { public: ... bool MatchAndExplain(MyType value, MatchResultListener* listener) const { // value がマッチすると true を返します. *listener << "the Bar property is " << value.GetBar(); return value.GetBar() < 42; } ... }; ... MakePolymorphicMatcher(MyGreatMatcher()) ... .. For more information, you can read these two recipes from the cookbook. As always, you are welcome to post questions on googlemock@googlegroups.com if you need any help. 詳細は,クックブックのこれら :ref:`2つの ` :ref:`レシピ` を参照してください.また,助けが必要ならいつでも googlemock@googlegroups.com に質問を投げてください. .. When using Google Mock, do I have to use Google Test as the testing framework? I have my favorite testing framework and don't want to switch. .. _faq_do_i_have_to_use_google_test_as_the _testing_framework: Google Mock を使う場合,testing framework として Google Test を使う必要がありますか?いつも使っている testing framework があるので切り替えたくないのですが. ====================================================================================================================== .. Google Mock works out of the box with Google Test. However, it's easy to configure it to work with any testing framework of your choice. Here is how. Google Test があれば Google Mock を簡単に利用できます.しかし,任意の testing framework で動作するように設定するのは簡単です.やり方は, :ref:`ここ ` を参照してください. .. How am I supposed to make sense of these horrible template errors? .. _faq_how_am_i_supposed_to_make_sense_of_these_horrible_template_errors: これらの恐ろしいテンプレートエラーをどのように理解すればよいのでしょうか? ================================================================================ .. If you are confused by the compiler errors gcc threw at you, try consulting the Google Mock Doctor tool first. What it does is to scan stdin for gcc error messages, and spit out diagnoses on the problems (we call them diseases) your code has. gcc が出すコンパイルエラーに混乱した場合は,まず,Google Mock Doctor ツールを試してみてください.これは,stdin を介して gcc エラーメッセージをスキャンし,あなたのコードが抱える問題(我々は,これらを疾病を呼びます)を診断結果に吐き出します. .. To "install", run command: 「インストール」するには,次のコマンドを実行してください: :: alias gmd='/scripts/gmock_doctor.py' .. To use it, do: 利用するには,次のようにします: :: 2>&1 | gmd .. For example: 以下に例を示します: :: make my_test 2>&1 | gmd .. Or you can run gmd and copy-n-paste gcc's error messages to it. あるいは,gmd を実行して,それに gcc のエラーメッセージをコピー&ペーストすることもできます. .. Can I mock a variadic function? .. _faq_can_i_mock_a_variadic_function: 可変個引数の関数をモック化できますか? ======================================== .. You cannot mock a variadic function (i.e. a function taking ellipsis (...) arguments) directly in Google Mock. Google Mock では,可変個引数の関数(つまり,省略記号(...)引数をとる関数)を直接モック化することはできません. .. The problem is that in general, there is no way for a mock object to know how many arguments are passed to the variadic method, and what the arguments' types are. Only the author of the base class knows the protocol, and we cannot look into his head. 一般的に,この問題は,可変個引数メソッドに何個の引数が渡されたのか,そして引数の型は何なのか,をモックオブジェクトが知る方法がないということです.基底クラスを書いた人だけが,このプロトコルを知っており,我々は彼の頭の中を覗くことはできません. .. Therefore, to mock such a function, the user must teach the mock object how to figure out the number of arguments and their types. One way to do it is to provide overloaded versions of the function. したがって,このような関数をモック化するには,引数の個数と型を知る方法をモックオブジェクトに教えなければいけません.方法の1つは,この関数のオーバーロードバージョンを用意することです. .. Ellipsis arguments are inherited from C and not really a C++ feature. They are unsafe to use and don't work with arguments that have constructors or destructors. Therefore we recommend to avoid them in C++ as much as possible. 省略記号引数は,C から引き継がれたもので,本当は C++ の機能ではありません.これは,安全に利用できるものではなく,コンストラクタやデストラクタを持つ引数と一緒には動作しません.したがって,C++ では,できるだけこれらを利用しないことをお勧めします. .. MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? .. _faq_msvc_gives_me_warning_c4301_or_c4373_when_const: const パラメータを持つモックメソッドを定義すると,MSVC で 警告 C4301 や C4373 が起こります.なぜですか? ========================================================================= .. If you compile this using Microsoft Visual C++ 2005 SP1: Microsoft Visual C++ 2005 SP1 を用いて,以下をコンパイルするとします: .. code-block:: c class Foo { ... virtual void Bar(const int i) = 0; }; class MockFoo : public Foo { ... MOCK_METHOD1(Bar, void(const int i)); }; .. You may get the following warning: すると,以下のような警告が出るでしょう: :: warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier .. This is a MSVC bug. The same code compiles fine with gcc ,for example. If you use Visual C++ 2008 SP1, you would get the warning: これは MSVC のバグです.例えば,gcc では同じコードが問題なくコンパイルできます.また, Visual C++ 2008 SP1 を利用している場合は,次のような警告が出ます: :: warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers .. In C++, if you declare a function with a const parameter, the const modifier is ignored. Therefore, the Foo base class above is equivalent to: C++ では,const なパラメータを使って関数を宣言した場合,その const 修飾子は無視されます.したがって,上述の Foo 基底クラスは,以下と等価になります: .. code-block:: c class Foo { ... virtual void Bar(int i) = 0; // int または const int ?どちらでも同じです. }; .. In fact, you can declare Bar() with an int parameter, and define it with a const int parameter. The compiler will still match them up. 実際,int パラメータを使って Bar() を宣言して,const int パラメータを使って定義することもできます.コンパイラは,これらをうまく合致させます. .. Since making a parameter const is meaningless in the method declaration, we recommend to remove it in both Foo and MockFoo. That should workaround the VC bug. メソッドの宣言でパラメータを const にする意味がないので,Foo と MockFoo からそれを削除することをお勧めします.これで,VC のバグを回避できます. .. Note that we are talking about the top-level const modifier here. If the function parameter is passed by pointer or reference, declaring the pointee or referee as const is still meaningful. For example, the following two declarations are not equivalent: ここでは,トップレベルの const 修飾子について論じていることに注意してください.関数パラメータがポインタや参照で渡される場合,そのポインタや参照の指し示す先を const として宣言することは大きな意味があります.次の2つの宣言は,等価ではありません: .. code-block:: c void Bar(int* p); // p または *p のどちらも const ではありません. void Bar(const int* p); // p は const ではありませんが,*p は const です. .. I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? .. _faq_i_have_a_huge_mock_class_runs_out_of_memory_when_compiling_it: 巨大なモッククラスを Microsoft Visual C++ でコンパイルしようとするとメモリが不足します.どうすれば良いでしょうか? ============================================================================== .. We've noticed that when the /clr compiler flag is used, Visual C++ uses 5~6 times as much memory when compiling a mock class. We suggest to avoid /clr when compiling native C++ mocks. 我々は,/clr コンパイラフラグを使うと,Visual C++ でモッククラスをコンパイルする際に 5〜6 倍のメモリを消費することに気づきました.ネイティブな C++ モックをコンパイルする場合は,/clr を使わないようにするのが良いでしょう. .. I can't figure out why Google Mock thinks my expectations are not satisfied. What should I do? .. _faq_i_cant_figure_out_why_googlemock_thinks_my_expecations_are_not_satisfied: Google Mock で,自分の Expectation が満足されないと判断される理由が分かりません.どうすれば良いでしょうか? =============================================================================== .. You might want to run your test with --gmock_verbose=info. This flag lets Google Mock print a trace of every mock function call it receives. By studying the trace, you'll gain insights on why the expectations you set are not met. ---gmock_verbose=info を利用してテストを実行すると良いでしょう.このフラグを使うと,Google Mock が受けた各モック関数の呼び出しのトレースを出力します.このトレースを調べることで,あなたが設定した Expectation が満足されない理由を見抜くことができるようになります. .. How can I assert that a function is NEVER called? .. _faq_how_can_i_assert_that_a_function_is_never_called: ある関数がまったく呼び出されないことをアサートするにはどうすれば良いでしょうか? =============================================================================== .. code-block:: c EXPECT_CALL(foo, Bar(_)) .Times(0); .. I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? .. _faq_googlemock_tells_me_twice_that_a_particular_expectation_is_not_satisified: Google Mock の特定の Expectation が満足されないと2回も言われて,テストが失敗しました.これは冗長ではないでしょうか? =============================================================================== .. When Google Mock detects a failure, it prints relevant information (the mock function arguments, the state of relevant expectations, and etc) to help the user debug. If another failure is detected, Google Mock will do the same, including printing the state of relevant expectations. Google Mock が失敗を検出すると,ユーザがデバッグしやすいように,関連情報(モック関数の引数,関連する Expectation の状態,など)が出力されます.別の失敗を検出した場合も,Google Mock は同様のことを行い,やはり関連する Expectation の状態が出力されます. .. Sometimes an expectation's state didn't change between two failures, and you'll see the same description of the state twice. They are however not redundant, as they refer to different points in time. The fact they are the same is interesting information. これら2つの失敗の間で,Expectation の状態が変化しないこともあるので,この状態の同じ説明を2度見ることがあります.しかし,その時々で異なるポイントを参照しているので,これは冗長ではありません.これらが等しい,ということ自体が興味深い情報です. .. I get a heap check failure when using a mock object, but using a real object is fine. What can be wrong? .. _faq_i_get_a_heap_check_failure_with_mock_not_real_object: モックオブジェクトを使っている時にヒープチェックに失敗しましたが,実際のオブジェクトだと問題ありません.何が悪いのでしょうか? =============================================================================== .. Does the class (hopefully a pure interface) you are mocking have a virtual destructor? モック化しようとしているクラス(できれば,純粋なインタフェース)は,仮想デストラクタを持っていますか? .. Whenever you derive from a base class, make sure its destructor is virtual. Otherwise Bad Things will happen. Consider the following code: 基底クラスからの派生を行う場合,必ずそのデストラクタを仮想関数にしてください.そうしなければ,困ったことになります.次のコードを見てください: .. code-block:: c class Base { public: // 仮想関数であるべきですが,これはそうではありません. ~Base() { ... } ... }; class Derived : public Base { public: ... private: std::string value_; }; ... Base* p = new Derived; ... delete p; // なんと! ~Base() が呼び出されても,~Derived() は呼び出されません. // - value_ がリークします. .. By changing ~Base() to virtual, ~Derived() will be correctly called when delete p is executed, and the heap checker will be happy. ~Base() を仮想関数にすると,p を削除した際に ~Derived() が正しく呼び出されるので,ヒープチェッカーも満足します. .. The "newer expectations override older ones" rule makes writing expectations awkward. Why does Google Mock do that? .. _faq_the_newer_override_older_rule_make_awkward: 「より新しい Expectation が古いものに優先する」ルールのせいで,Expectation の書き方が不恰好になります.Google Mock はどうしてこうなっているのでしょうか? ========================================================================================================= .. When people complain about this, often they are referring to code like: これについて文句を言う場合,よく次のようなコードが持ち出されます: .. code-block:: c // foo.Bar() は2回呼び出され,最初は1を,2度目は2を返すはずです. // しかし,Expectation はその逆の順番で書く必要があります. // これはヒドイ!!! EXPECT_CALL(foo, Bar()) .WillOnce(Return(2)) .RetiresOnSaturation(); EXPECT_CALL(foo, Bar()) .WillOnce(Return(1)) .RetiresOnSaturation(); .. The problem is that they didn't pick the best way to express the test's intent. この問題は,テストの意図を表現するための最適な方法をとらないことにあります. .. By default, expectations don't have to be matched in any particular order. If you want them to match in a certain order, you need to be explicit. This is Google Mock's (and jMock's) fundamental philosophy: it's easy to accidentally over-specify your tests, and we want to make it harder to do so. デフォルトでは,Expectation は,ある特定の順番でマッチしなければならないというわけではありません.ある順序でマッチしてほしいならば,それを明示する必要があります.テストは過剰に指定されやすいので,簡単にはそうできないようにしたい,というのが Google Mock の(そして,jMock の)基本哲学です. .. There are two better ways to write the test spec. You could either put the expectations in sequence: テストの仕様を記述する,より良い方法は2つあります.どちらの場合も,Expectation を順序どおりに書くことができます: .. code-block:: c // foo.Bar() は2回呼び出され,最初は1を, // 2度目は2を返すはずです.シーケンスを利用すると, // 自然な順番で Expectation を書くことができます. { InSequence s; EXPECT_CALL(foo, Bar()) .WillOnce(Return(1)) .RetiresOnSaturation(); EXPECT_CALL(foo, Bar()) .WillOnce(Return(2)) .RetiresOnSaturation(); } .. or you can put the sequence of actions in the same expectation: または,一連の Action を同じ Expectation に書きます: .. code-block:: c // foo.Bar() は2回呼び出され,最初は1を, // 2度目は2を返すはずです. EXPECT_CALL(foo, Bar()) .WillOnce(Return(1)) .WillOnce(Return(2)) .RetiresOnSaturation(); .. Back to the original questions: why does Google Mock search the expectations (and ON_CALLs) from back to front? Because this allows a user to set up a mock's behavior for the common case early (e.g. in the mock's constructor or the test fixture's set-up phase) and customize it with more specific rules later. If Google Mock searches from front to back, this very useful pattern won't be possible. 最初の質問に戻ります:Google Mock はなぜ,Expectation(および ON_CALL)を後ろから前に探索するのでしょうか?このおかげで,ユーザは,まず共通のケースに対するモックの挙動を定義して(例えば,モックのコンストラクタやテストフィクスチャの set-up フェーズ),それから,より具体的なルールを用いてそれをカスタマイズできるからです.もし,Google Mock が前から後ろに探索を行うと,この非常に便利なパターンは利用できなくなるでしょう. .. Google Mock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case? .. _faq_gmock_prints_a_warning_when_a_function_without_expect_call_is_called_even_if_i_have_set_its_behavior: ON_CALL を使って挙動を設定しているのに,EXPECT_CALL がない関数呼び出しが行われた,という警告を Google Mock が出力します.この場合,警告を出さない方が良いのではないですか? ================================================================================================================================================== .. When choosing between being neat and being safe, we lean toward the latter. So the answer is that we think it's better to show the warning. 綺麗であることと安全であることの,どちらかを選択する場合,我々は後者を好みます.よって,警告を出したほうが良い,というのがこの質問に対する答えです. .. Often people write ON_CALLs in the mock object's constructor or SetUp(), as the default behavior rarely changes from test to test. Then in the test body they set the expectations, which are often different for each test. Having an ON_CALL in the set-up part of a test doesn't mean that the calls are expected. If there's no EXPECT_CALL and the method is called, it's possibly an error. If we quietly let the call go through without notifying the user, bugs may creep in unnoticed. テスト毎に変更さることが滅多にないデフォルトの挙動として,モックオブジェクトのコンストラクタや SetUp() 内に ON_CALL を書く人をよく見かけます.そして,テスト本体部分に Expectation を設定しますが,それは各テストごとに異なります.テストの set-up 部分に ON_CALL があるからといって,その呼び出しが期待されているという意味にはなりません.EXPECT_CALL がない場合にそのメソッドが呼ばれると,場合によってはエラーになります.そのような呼び出しを,ユーザに知らせることなく黙って通過させると,気づかないうちにバグが入り込む可能性があります. .. If, however, you are sure that the calls are OK, you can write しかし,もし,その呼び出しが問題ないことが分かっていれば,次のように書くことができます. .. code-block:: c EXPECT_CALL(foo, Bar(_)) .WillRepeatedly(...); .. instead of これは,以下の代わりになります. .. code-block:: c ON_CALL(foo, Bar(_)) .WillByDefault(...); .. This tells Google Mock that you do expect the calls and no warning should be printed. これは,その呼び出しを期待しており警告を出力するべきではない,ということを Google Mock に伝えます. .. Also, you can control the verbosity using the --gmock_verbose flag. If you find the output too noisy when debugging, just choose a less verbose level. ---gmock_verbose フラグを使って,出力メッセージの詳細レベルを制御できます.デバッグ時に,出力に邪魔なものが多すぎると思った場合は,このレベルを下げてください. .. How can I delete the mock function's argument in an action? .. _faq_how_can_i_delete_the_mock_functions_argument_in_an_action: Action の中で,モック関数の引数を削除するにはどうすればよいのでしょうか? ================================================================ .. If you find yourself needing to perform some action that's not supported by Google Mock directly, remember that you can define your own actions using MakeAction() or MakePolymorphicAction(), or you can write a stub function and invoke it using Invoke(). Google Mock が直接サポートしていない Action を実行する必要がある場合, :ref:`MakeAction() ` や :ref:`MakePolymorphicAction() ` を利用して自分で Action を定義したり,スタブ関数を書いて :ref:`Invoke() ` でそれを呼び出すことができることを思い出してください. .. MOCK_METHODn()'s second argument looks funny. Why don't you use the MOCK_METHODn(Method, return_type, arg_1, ..., arg_n) syntax? .. _faq_mock_methodn()s_second_argument_looks_funny: MOCK_METHODn() の2番目の引数は奇妙です.なぜ MOCK_METHODn(Method, return_type, arg_1, ..., arg_n) という構文ではないのでしょうか? ======================================================================================================= .. What?! I think it's beautiful. :-) なぜか?それが綺麗だと思っているからです.:-) .. While which syntax looks more natural is a subjective matter to some extent, Google Mock's syntax was chosen for several practical advantages it has. どの構文が自然に見えるかは,ある程度は主観の問題です.Google Mock の構文は,いくつかの実際的な利点を考慮して選択されました. .. Try to mock a function that takes a map as an argument: 引数に map をとる関数をモック化してみましょう: .. code-block:: c virtual int GetSize(const map& m); .. Using the proposed syntax, it would be: 提案にあった構文を使うと,これは次のようになります: .. code-block:: c MOCK_METHOD1(GetSize, int, const map& m); .. Guess what? You'll get a compiler error as the compiler thinks that const map& m are two, not one, arguments. To work around this you can use typedef to give the map type a name, but that gets in the way of your work. Google Mock's syntax avoids this problem as the function's argument types are protected inside a pair of parentheses: さて,これはどうなるでしょう?コンパイラは const map& m を1つではなく2つの引数と考えるので,コンパイルエラーが起こります.これを動作させるには,面倒ですが,与えられた map を typedef する必要があります.Google Mock の構文では,関数の引数が丸括弧内に保護されているので,このような問題を避けることができます. .. code-block:: c // これはコンパイルできます. MOCK_METHOD1(GetSize, int(const map& m)); .. You still need a typedef if the return type contains an unprotected comma, but that's much rarer. もし戻り値の型にカンマがあれば,typedef が必要になりますが,そのようなケースは非常にまれです. .. Other advantages include: 他にも,次のような利点があります: .. MOCK_METHOD1(Foo, int, bool) can leave a reader wonder whether the method returns int or bool, while there won't be such confusion using Google Mock's syntax. .. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it. The same syntax was used in C, and the function library in tr1 uses this syntax extensively. Since tr1 will become a part of the new version of STL, we feel very comfortable to be consistent with it. .. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features. We'd as well stick to the same syntax in MOCK_METHOD*! #. MOCK_METHOD1(Foo, int, bool) という書き方では,そのメソッドが int を返すのか bool を返すのか,読み手が悩む可能性があります.しかし,Google Mock の構文では,そのような混乱は起こりません. #. Google Mock の関数の型を書く方法は,何も新しいものではありませんが,多くの人がこれには慣れていないでしょう.同様の構文が C 言語でも利用され,tr1 の関数ライブラリでも広範囲で使われています.また,tr1 は新バージョンの STL に取り込まれるので,これと一貫性があるのはとても快適なことです. #. この関数の型の構文は,実装を扱いやすいものにするために,Google Mock の API の別の部分(例えば,Action インタフェース)でも利用されています.Google Mock をより便利に使うためには,ともかくこれを学ぶ必要があります.また,MOCK_METHOD* でも同様の構文を利用しています! .. My code calls a static/global function. Can I mock it? .. _faq_my_code_calls_a_static_global_function_can_i_mock_it: コードで static/global な関数を使っています.これをモック化できますか? ========================================================= .. You can, but you need to make some changes. できますが,いくつかの変更が必要です. .. In general, if you find yourself needing to mock a static function, it's a sign that your modules are too tightly coupled (and less flexible, less reusable, less testable, etc). You are probably better off defining a small interface and call the function through that interface, which then can be easily mocked. It's a bit of work initially, but usually pays for itself quickly. 一般的にいって,static 関数をモック化したくなったとすると,それはモジュール同士がが強く結びつきすぎている(そして,柔軟性や再利用性,テスト可能性などが低下している)ことを示すサインです.おそらく,より小さなインタフェースを定義し,そのインタフェースを介してメソッドを呼び出すほうが良いでしょう.そのようなメソッドは,簡単にモック化できます.それは,ちょっとした仕事になりますが,すぐに元が取れます. .. This Google Testing Blog post says it excellently. Check it out. Google Testing Blog のこの `ポスト `_ が,それを見事に述べています.ぜひ見てください. .. My mock object needs to do complex stuff. It's a lot of pain to specify the actions. Google Mock sucks! .. _faq_my_mock_object_needs_to_do_complex_stuff: モックオブジェクトが複雑なことをする必要があり,その Action を指定するのがとても大変です.Google Mock にはがっかりです! ====================================================================================================== .. I know it's not a question, but you get an answer for free any way. :-) これが質問ではないことは分かっていますが,ともかく回答を書きます.:-) .. With Google Mock, you can create mocks in C++ easily. And people might be tempted to use them everywhere. Sometimes they work great, and sometimes you may find them, well, a pain to use. So, what's wrong in the latter case? Google Mock を使うと,C++ で簡単にモックを作ることができます.そして,あらゆる場所でそれを使おうとするかもしれません.非常に上手く使えることもあれば,えー,まったく苦痛でしかないこともあります.後者の場合では,何が問題なのでしょうか? .. When you write a test without using mocks, you exercise the code and assert that it returns the correct value or that the system is in an expected state. This is sometimes called "state-based testing". モックを利用せずにテストを書く場合,コードを実行して,それが正しい値を返すことや,システムが期待した状態にあることをアサートします.これは,「状態に基づくテスト(state-based testing)」と呼ばれることがあります. .. Mocks are great for what some call "interaction-based" testing: instead of checking the system state at the very end, mock objects verify that they are invoked the right way and report an error as soon as it arises, giving you a handle on the precise context in which the error was triggered. This is often more effective and economical to do than state-based testing. モックが役立つのは,「インタラクションに基づく(interaction-based)」テストと呼ばれるものに対してです.このテストでは,すべて終わった後にシステムの状態をチェックする代わりに,モックオブジェクトが,自分自身が正しく実行されたかを検証し,エラーが起これば即座にレポートします.これにより,ユーザはエラーが発生したときの正確なコンテキストを把握することができます.これは,状態に基づくテストに比べて,より便利で経済的な場合が多いです. .. If you are doing state-based testing and using a test double just to simulate the real object, you are probably better off using a fake. Using a mock in this case causes pain, as it's not a strong point for mocks to perform complex actions. If you experience this and think that mocks suck, you are just not using the right tool for your problem. Or, you might be trying to solve the wrong problem. :-) もし,あなたが状態に基づくテストを行っており,実際のオブジェクトをシミュレートするためだけにテストダブルを使っているならば,フェイクを使ったほうが良いでしょう.モックは,複雑な動作を行うことを重視していないので,このような場合にモックを利用しても苦痛なだけです.もし,このようなことで悩み,モックは駄目だと思ったなら,それは単に問題に合った正しい道具を使っていないだけです.あるいは,間違った問題を解こうとしているのかもしれません.:-) .. I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? .. _faq_i_got_a_warning_uninteresting_function_call_encountered: "Uninteresting function call encountered - default action taken.." という警告がでました.パニックになるべき? ===================================================================================================== .. By all means, NO! It's just an FYI. いいえ,そんな必要はまったくありません.これは,単に参考のための情報です. .. What it means is that you have a mock function, you haven't set any expectations on it (by Google Mock's rule this means that you are not interested in calls to this function and therefore it can be called any number of times), and it is called. That's OK - you didn't say it's not OK to call the function! これは,Expectation を設定していないモック関数があり(Google Mock のルールでは,この関数呼び出しに関心が無いので,任意の回数呼び出すことができます),それが呼び出された,ということを意味しています.大丈夫,問題ありません.この関数を呼び出してはいけない,とは決めませんでしたから. .. What if you actually meant to disallow this function to be called, but forgot to write EXPECT_CALL(foo, Bar()).Times(0)? While one can argue that it's the user's fault, Google Mock tries to be nice and prints you a note. 実際にはこの関数の呼び出しを許可していないつもりで,EXPECT_CALL(foo, Bar()).Times(0) を書き忘れていたのなら,どうでしょうか?それがユーザの誤りだと言える場合でも,Google Mock は,気を使って,注意表示を行います. .. So, when you see the message and believe that there shouldn't be any uninteresting calls, you should investigate what's going on. To make your life easier, Google Mock prints the function name and arguments when an uninteresting call is encountered. 不要な呼び出しは1つも無いはずだと信じている場合でも,このメッセージを目にしたら,何が起こっているのかを調べてみるべきです.不要な呼び出しが起こった場合に悩まなくてもすむように,Google Mock はその関数名と引数を出力します. .. I want to define a custom action. Should I use Invoke() or implement the action interface? .. _faq_i_want_to_define_a_custom_aciton: カスタム Action を定義したいです.Invoke() を使うのと Action インタフェースを実装するのは,どちらが適切でしょうか? =================================================================================================== .. Either way is fine - you want to choose the one that's more convenient for your circumstance. どちらでも構いません.が,状況に応じて便利な方を選択したい,というわけですね. .. Usually, if your action is for a particular function type, defining it using Invoke() should be easier; if your action can be used in functions of different types (e.g. if you are defining Return(value)), MakePolymorphicAction() is easiest. Sometimes you want precise control on what types of functions the action can be used in, and implementing ActionInterface is the way to go here. See the implementation of Return() in include/gmock/gmock-actions.h for an example. あなたの Action が特定の関数型に対するものならば,通常は Invoke() を用いて定義するのが簡単でしょう.その Action が異なる型の関数内で利用される可能性がある場合(例えば,Return(value) を定義している場合)は,MakePolymorphicAction() が最も簡単です.また,関数(この内部で Action が利用されます)の型を正確に制御したい場合もありますが,その場合は,ActionInterface を実装する方法を採ります.例として,include/gmock/gmock-actions.h における Return() の実装を参照してください. .. I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified". What does it mean? .. _faq_im_using_the_set-argument-pointee_action: set-argument-pointee Action を使っているのですが,コンパイラが "conflicting return type specified" というエラーを出します.どういう意味でしょうか? ============================================================================================================== .. You got this error as Google Mock has no idea what value it should return when the mock method is called. SetArgPointee() says what the side effect is, but doesn't say what the return value should be. You need DoAll() to chain a SetArgPointee() with a Return(). モックメソッドが呼ばれたときに,Google Mock がどの値を返すべきか分からないと,このエラーが起こります.SetArgPointee() を使うことで,副作用が何なのかは分かりますが,何の値を返すべきかは分かりません.DoAll() を利用して,SetArgPointee() に続けて Return() を呼ぶ必要があります. .. See this recipe for more details and an example. 詳細は,この :ref:`レシピ ` を参照してください. .. My question is not in your FAQ! .. _faq_my_question_is_not_in_your_faq__mock: 知りたいことが,この 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 googlemock@googlegroups.com and someone will answer it (to prevent spam, we require you to join the discussion group before you can post.). #. 他の :ref:`ページ ` を読んでください. #. メーリングリストの `アーカイブ `_ を検索してみてください. #. googlemock@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 Mock you use (Google Mock 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 Mock のバージョン(SVN から直接チェックアウトしているならば,リビジョン番号.Google Mock は開発中なので,最新バージョンで問題が解決されている可能性もあります) * 使っている OS * コンパイラの名前とバージョン * コンパイル時のコマンドラインフラグすべて * (質問がコンパイルに関することならば,)コンパイルエラーメッセージすべて * 問題を起こす実際のコード(理想的には,最小限かつ動作可能なプログラム)