1
2
3Please send your questions to the
4[googlemock](http://groups.google.com/group/googlemock) discussion
5group. If you need help with compiler errors, make sure you have
6tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first.
7
8## I wrote some matchers.  After I upgraded to a new version of Google Mock, they no longer compile.  What's going on? ##
9
10After version 1.4.0 of Google Mock was released, we had an idea on how
11to make it easier to write matchers that can generate informative
12messages efficiently.  We experimented with this idea and liked what
13we saw.  Therefore we decided to implement it.
14
15Unfortunately, this means that if you have defined your own matchers
16by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
17your definitions will no longer compile.  Matchers defined using the
18`MATCHER*` family of macros are not affected.
19
20Sorry for the hassle if your matchers are affected.  We believe it's
21in everyone's long-term interest to make this change sooner than
22later.  Fortunately, it's usually not hard to migrate an existing
23matcher to the new API.  Here's what you need to do:
24
25If you wrote your matcher like this:
26```
27// Old matcher definition that doesn't work with the latest
28// Google Mock.
29using ::testing::MatcherInterface;
30...
31class MyWonderfulMatcher : public MatcherInterface<MyType> {
32 public:
33  ...
34  virtual bool Matches(MyType value) const {
35    // Returns true if value matches.
36    return value.GetFoo() > 5;
37  }
38  ...
39};
40```
41
42you'll need to change it to:
43```
44// New matcher definition that works with the latest Google Mock.
45using ::testing::MatcherInterface;
46using ::testing::MatchResultListener;
47...
48class MyWonderfulMatcher : public MatcherInterface<MyType> {
49 public:
50  ...
51  virtual bool MatchAndExplain(MyType value,
52                               MatchResultListener* listener) const {
53    // Returns true if value matches.
54    return value.GetFoo() > 5;
55  }
56  ...
57};
58```
59(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
60argument of type `MatchResultListener*`.)
61
62If you were also using `ExplainMatchResultTo()` to improve the matcher
63message:
64```
65// Old matcher definition that doesn't work with the lastest
66// Google Mock.
67using ::testing::MatcherInterface;
68...
69class MyWonderfulMatcher : public MatcherInterface<MyType> {
70 public:
71  ...
72  virtual bool Matches(MyType value) const {
73    // Returns true if value matches.
74    return value.GetFoo() > 5;
75  }
76
77  virtual void ExplainMatchResultTo(MyType value,
78                                    ::std::ostream* os) const {
79    // Prints some helpful information to os to help
80    // a user understand why value matches (or doesn't match).
81    *os << "the Foo property is " << value.GetFoo();
82  }
83  ...
84};
85```
86
87you should move the logic of `ExplainMatchResultTo()` into
88`MatchAndExplain()`, using the `MatchResultListener` argument where
89the `::std::ostream` was used:
90```
91// New matcher definition that works with the latest Google Mock.
92using ::testing::MatcherInterface;
93using ::testing::MatchResultListener;
94...
95class MyWonderfulMatcher : public MatcherInterface<MyType> {
96 public:
97  ...
98  virtual bool MatchAndExplain(MyType value,
99                               MatchResultListener* listener) const {
100    // Returns true if value matches.
101    *listener << "the Foo property is " << value.GetFoo();
102    return value.GetFoo() > 5;
103  }
104  ...
105};
106```
107
108If your matcher is defined using `MakePolymorphicMatcher()`:
109```
110// Old matcher definition that doesn't work with the latest
111// Google Mock.
112using ::testing::MakePolymorphicMatcher;
113...
114class MyGreatMatcher {
115 public:
116  ...
117  bool Matches(MyType value) const {
118    // Returns true if value matches.
119    return value.GetBar() < 42;
120  }
121  ...
122};
123... MakePolymorphicMatcher(MyGreatMatcher()) ...
124```
125
126you should rename the `Matches()` method to `MatchAndExplain()` and
127add a `MatchResultListener*` argument (the same as what you need to do
128for matchers defined by implementing `MatcherInterface`):
129```
130// New matcher definition that works with the latest Google Mock.
131using ::testing::MakePolymorphicMatcher;
132using ::testing::MatchResultListener;
133...
134class MyGreatMatcher {
135 public:
136  ...
137  bool MatchAndExplain(MyType value,
138                       MatchResultListener* listener) const {
139    // Returns true if value matches.
140    return value.GetBar() < 42;
141  }
142  ...
143};
144... MakePolymorphicMatcher(MyGreatMatcher()) ...
145```
146
147If your polymorphic matcher uses `ExplainMatchResultTo()` for better
148failure messages:
149```
150// Old matcher definition that doesn't work with the latest
151// Google Mock.
152using ::testing::MakePolymorphicMatcher;
153...
154class MyGreatMatcher {
155 public:
156  ...
157  bool Matches(MyType value) const {
158    // Returns true if value matches.
159    return value.GetBar() < 42;
160  }
161  ...
162};
163void ExplainMatchResultTo(const MyGreatMatcher& matcher,
164                          MyType value,
165                          ::std::ostream* os) {
166  // Prints some helpful information to os to help
167  // a user understand why value matches (or doesn't match).
168  *os << "the Bar property is " << value.GetBar();
169}
170... MakePolymorphicMatcher(MyGreatMatcher()) ...
171```
172
173you'll need to move the logic inside `ExplainMatchResultTo()` to
174`MatchAndExplain()`:
175```
176// New matcher definition that works with the latest Google Mock.
177using ::testing::MakePolymorphicMatcher;
178using ::testing::MatchResultListener;
179...
180class MyGreatMatcher {
181 public:
182  ...
183  bool MatchAndExplain(MyType value,
184                       MatchResultListener* listener) const {
185    // Returns true if value matches.
186    *listener << "the Bar property is " << value.GetBar();
187    return value.GetBar() < 42;
188  }
189  ...
190};
191... MakePolymorphicMatcher(MyGreatMatcher()) ...
192```
193
194For more information, you can read these
195[two](V1_5_CookBook#Writing_New_Monomorphic_Matchers.md)
196[recipes](V1_5_CookBook#Writing_New_Polymorphic_Matchers.md)
197from the cookbook.  As always, you
198are welcome to post questions on `googlemock@googlegroups.com` if you
199need any help.
200
201## 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. ##
202
203Google Mock works out of the box with Google Test.  However, it's easy
204to configure it to work with any testing framework of your choice.
205[Here](V1_5_ForDummies#Using_Google_Mock_with_Any_Testing_Framework.md) is how.
206
207## How am I supposed to make sense of these horrible template errors? ##
208
209If you are confused by the compiler errors gcc threw at you,
210try consulting the _Google Mock Doctor_ tool first.  What it does is to
211scan stdin for gcc error messages, and spit out diagnoses on the
212problems (we call them diseases) your code has.
213
214To "install", run command:
215```
216alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
217```
218
219To use it, do:
220```
221<your-favorite-build-command> <your-test> 2>&1 | gmd
222```
223
224For example:
225```
226make my_test 2>&1 | gmd
227```
228
229Or you can run `gmd` and copy-n-paste gcc's error messages to it.
230
231## Can I mock a variadic function? ##
232
233You cannot mock a variadic function (i.e. a function taking ellipsis
234(`...`) arguments) directly in Google Mock.
235
236The problem is that in general, there is _no way_ for a mock object to
237know how many arguments are passed to the variadic method, and what
238the arguments' types are.  Only the _author of the base class_ knows
239the protocol, and we cannot look into his head.
240
241Therefore, to mock such a function, the _user_ must teach the mock
242object how to figure out the number of arguments and their types.  One
243way to do it is to provide overloaded versions of the function.
244
245Ellipsis arguments are inherited from C and not really a C++ feature.
246They are unsafe to use and don't work with arguments that have
247constructors or destructors.  Therefore we recommend to avoid them in
248C++ as much as possible.
249
250## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter.  Why? ##
251
252If you compile this using Microsoft Visual C++ 2005 SP1:
253```
254class Foo {
255  ...
256  virtual void Bar(const int i) = 0;
257};
258
259class MockFoo : public Foo {
260  ...
261  MOCK_METHOD1(Bar, void(const int i));
262};
263```
264You may get the following warning:
265```
266warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
267```
268
269This is a MSVC bug.  The same code compiles fine with gcc ,for
270example.  If you use Visual C++ 2008 SP1, you would get the warning:
271```
272warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
273```
274
275In C++, if you _declare_ a function with a `const` parameter, the
276`const` modifier is _ignored_.  Therefore, the `Foo` base class above
277is equivalent to:
278```
279class Foo {
280  ...
281  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.
282};
283```
284
285In fact, you can _declare_ Bar() with an `int` parameter, and _define_
286it with a `const int` parameter.  The compiler will still match them
287up.
288
289Since making a parameter `const` is meaningless in the method
290_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
291That should workaround the VC bug.
292
293Note that we are talking about the _top-level_ `const` modifier here.
294If the function parameter is passed by pointer or reference, declaring
295the _pointee_ or _referee_ as `const` is still meaningful.  For
296example, the following two declarations are _not_ equivalent:
297```
298void Bar(int* p);        // Neither p nor *p is const.
299void Bar(const int* p);  // p is not const, but *p is.
300```
301
302## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it.  What can I do? ##
303
304We've noticed that when the `/clr` compiler flag is used, Visual C++
305uses 5~6 times as much memory when compiling a mock class.  We suggest
306to avoid `/clr` when compiling native C++ mocks.
307
308## I can't figure out why Google Mock thinks my expectations are not satisfied.  What should I do? ##
309
310You might want to run your test with
311`--gmock_verbose=info`.  This flag lets Google Mock print a trace
312of every mock function call it receives.  By studying the trace,
313you'll gain insights on why the expectations you set are not met.
314
315## How can I assert that a function is NEVER called? ##
316
317```
318EXPECT_CALL(foo, Bar(_))
319    .Times(0);
320```
321
322## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied.  Isn't this redundant? ##
323
324When Google Mock detects a failure, it prints relevant information
325(the mock function arguments, the state of relevant expectations, and
326etc) to help the user debug.  If another failure is detected, Google
327Mock will do the same, including printing the state of relevant
328expectations.
329
330Sometimes an expectation's state didn't change between two failures,
331and you'll see the same description of the state twice.  They are
332however _not_ redundant, as they refer to _different points in time_.
333The fact they are the same _is_ interesting information.
334
335## I get a heap check failure when using a mock object, but using a real object is fine.  What can be wrong? ##
336
337Does the class (hopefully a pure interface) you are mocking have a
338virtual destructor?
339
340Whenever you derive from a base class, make sure its destructor is
341virtual.  Otherwise Bad Things will happen.  Consider the following
342code:
343
344```
345class Base {
346 public:
347  // Not virtual, but should be.
348  ~Base() { ... }
349  ...
350};
351
352class Derived : public Base {
353 public:
354  ...
355 private:
356  std::string value_;
357};
358
359...
360  Base* p = new Derived;
361  ...
362  delete p;  // Surprise! ~Base() will be called, but ~Derived() will not
363             // - value_ is leaked.
364```
365
366By changing `~Base()` to virtual, `~Derived()` will be correctly
367called when `delete p` is executed, and the heap checker
368will be happy.
369
370## The "newer expectations override older ones" rule makes writing expectations awkward.  Why does Google Mock do that? ##
371
372When people complain about this, often they are referring to code like:
373
374```
375// foo.Bar() should be called twice, return 1 the first time, and return
376// 2 the second time.  However, I have to write the expectations in the
377// reverse order.  This sucks big time!!!
378EXPECT_CALL(foo, Bar())
379    .WillOnce(Return(2))
380    .RetiresOnSaturation();
381EXPECT_CALL(foo, Bar())
382    .WillOnce(Return(1))
383    .RetiresOnSaturation();
384```
385
386The problem is that they didn't pick the **best** way to express the test's
387intent.
388
389By default, expectations don't have to be matched in _any_ particular
390order.  If you want them to match in a certain order, you need to be
391explicit.  This is Google Mock's (and jMock's) fundamental philosophy: it's
392easy to accidentally over-specify your tests, and we want to make it
393harder to do so.
394
395There are two better ways to write the test spec.  You could either
396put the expectations in sequence:
397
398```
399// foo.Bar() should be called twice, return 1 the first time, and return
400// 2 the second time.  Using a sequence, we can write the expectations
401// in their natural order.
402{
403  InSequence s;
404  EXPECT_CALL(foo, Bar())
405      .WillOnce(Return(1))
406      .RetiresOnSaturation();
407  EXPECT_CALL(foo, Bar())
408      .WillOnce(Return(2))
409      .RetiresOnSaturation();
410}
411```
412
413or you can put the sequence of actions in the same expectation:
414
415```
416// foo.Bar() should be called twice, return 1 the first time, and return
417// 2 the second time.
418EXPECT_CALL(foo, Bar())
419    .WillOnce(Return(1))
420    .WillOnce(Return(2))
421    .RetiresOnSaturation();
422```
423
424Back to the original questions: why does Google Mock search the
425expectations (and `ON_CALL`s) from back to front?  Because this
426allows a user to set up a mock's behavior for the common case early
427(e.g. in the mock's constructor or the test fixture's set-up phase)
428and customize it with more specific rules later.  If Google Mock
429searches from front to back, this very useful pattern won't be
430possible.
431
432## 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? ##
433
434When choosing between being neat and being safe, we lean toward the
435latter.  So the answer is that we think it's better to show the
436warning.
437
438Often people write `ON_CALL`s in the mock object's
439constructor or `SetUp()`, as the default behavior rarely changes from
440test to test.  Then in the test body they set the expectations, which
441are often different for each test.  Having an `ON_CALL` in the set-up
442part of a test doesn't mean that the calls are expected.  If there's
443no `EXPECT_CALL` and the method is called, it's possibly an error.  If
444we quietly let the call go through without notifying the user, bugs
445may creep in unnoticed.
446
447If, however, you are sure that the calls are OK, you can write
448
449```
450EXPECT_CALL(foo, Bar(_))
451    .WillRepeatedly(...);
452```
453
454instead of
455
456```
457ON_CALL(foo, Bar(_))
458    .WillByDefault(...);
459```
460
461This tells Google Mock that you do expect the calls and no warning should be
462printed.
463
464Also, you can control the verbosity using the `--gmock_verbose` flag.
465If you find the output too noisy when debugging, just choose a less
466verbose level.
467
468## How can I delete the mock function's argument in an action? ##
469
470If you find yourself needing to perform some action that's not
471supported by Google Mock directly, remember that you can define your own
472actions using
473[MakeAction()](V1_5_CookBook#Writing_New_Actions.md) or
474[MakePolymorphicAction()](V1_5_CookBook#Writing_New_Polymorphic_Actions.md),
475or you can write a stub function and invoke it using
476[Invoke()](V1_5_CookBook#Using_Functions_Methods_Functors.md).
477
478## MOCK\_METHODn()'s second argument looks funny.  Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##
479
480What?!  I think it's beautiful. :-)
481
482While which syntax looks more natural is a subjective matter to some
483extent, Google Mock's syntax was chosen for several practical advantages it
484has.
485
486Try to mock a function that takes a map as an argument:
487```
488virtual int GetSize(const map<int, std::string>& m);
489```
490
491Using the proposed syntax, it would be:
492```
493MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
494```
495
496Guess what?  You'll get a compiler error as the compiler thinks that
497`const map<int, std::string>& m` are **two**, not one, arguments. To work
498around this you can use `typedef` to give the map type a name, but
499that gets in the way of your work.  Google Mock's syntax avoids this
500problem as the function's argument types are protected inside a pair
501of parentheses:
502```
503// This compiles fine.
504MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
505```
506
507You still need a `typedef` if the return type contains an unprotected
508comma, but that's much rarer.
509
510Other advantages include:
511  1. `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.
512  1. 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.
513  1. 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*`!
514
515## My code calls a static/global function.  Can I mock it? ##
516
517You can, but you need to make some changes.
518
519In general, if you find yourself needing to mock a static function,
520it's a sign that your modules are too tightly coupled (and less
521flexible, less reusable, less testable, etc).  You are probably better
522off defining a small interface and call the function through that
523interface, which then can be easily mocked.  It's a bit of work
524initially, but usually pays for itself quickly.
525
526This Google Testing Blog
527[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
528says it excellently.  Check it out.
529
530## My mock object needs to do complex stuff.  It's a lot of pain to specify the actions.  Google Mock sucks! ##
531
532I know it's not a question, but you get an answer for free any way. :-)
533
534With Google Mock, you can create mocks in C++ easily.  And people might be
535tempted to use them everywhere. Sometimes they work great, and
536sometimes you may find them, well, a pain to use. So, what's wrong in
537the latter case?
538
539When you write a test without using mocks, you exercise the code and
540assert that it returns the correct value or that the system is in an
541expected state.  This is sometimes called "state-based testing".
542
543Mocks are great for what some call "interaction-based" testing:
544instead of checking the system state at the very end, mock objects
545verify that they are invoked the right way and report an error as soon
546as it arises, giving you a handle on the precise context in which the
547error was triggered.  This is often more effective and economical to
548do than state-based testing.
549
550If you are doing state-based testing and using a test double just to
551simulate the real object, you are probably better off using a fake.
552Using a mock in this case causes pain, as it's not a strong point for
553mocks to perform complex actions.  If you experience this and think
554that mocks suck, you are just not using the right tool for your
555problem. Or, you might be trying to solve the wrong problem. :-)
556
557## I got a warning "Uninteresting function call encountered - default action taken.."  Should I panic? ##
558
559By all means, NO!  It's just an FYI.
560
561What it means is that you have a mock function, you haven't set any
562expectations on it (by Google Mock's rule this means that you are not
563interested in calls to this function and therefore it can be called
564any number of times), and it is called.  That's OK - you didn't say
565it's not OK to call the function!
566
567What if you actually meant to disallow this function to be called, but
568forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`?  While
569one can argue that it's the user's fault, Google Mock tries to be nice and
570prints you a note.
571
572So, when you see the message and believe that there shouldn't be any
573uninteresting calls, you should investigate what's going on.  To make
574your life easier, Google Mock prints the function name and arguments
575when an uninteresting call is encountered.
576
577## I want to define a custom action.  Should I use Invoke() or implement the action interface? ##
578
579Either way is fine - you want to choose the one that's more convenient
580for your circumstance.
581
582Usually, if your action is for a particular function type, defining it
583using `Invoke()` should be easier; if your action can be used in
584functions of different types (e.g. if you are defining
585`Return(value)`), `MakePolymorphicAction()` is
586easiest.  Sometimes you want precise control on what types of
587functions the action can be used in, and implementing
588`ActionInterface` is the way to go here. See the implementation of
589`Return()` in `include/gmock/gmock-actions.h` for an example.
590
591## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified".  What does it mean? ##
592
593You got this error as Google Mock has no idea what value it should return
594when the mock method is called.  `SetArgumentPointee()` says what the
595side effect is, but doesn't say what the return value should be.  You
596need `DoAll()` to chain a `SetArgumentPointee()` with a `Return()`.
597
598See this [recipe](V1_5_CookBook#Mocking_Side_Effects.md) for more details and an example.
599
600
601## My question is not in your FAQ! ##
602
603If you cannot find the answer to your question in this FAQ, there are
604some other resources you can use:
605
606  1. read other [wiki pages](http://code.google.com/p/googlemock/w/list),
607  1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
608  1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).
609
610Please note that creating an issue in the
611[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_
612a good way to get your answer, as it is monitored infrequently by a
613very small number of people.
614
615When asking a question, it's helpful to provide as much of the
616following information as possible (people cannot help you if there's
617not enough information in your question):
618
619  * 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),
620  * your operating system,
621  * the name and version of your compiler,
622  * the complete command line flags you give to your compiler,
623  * the complete compiler error messages (if the question is about compilation),
624  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.