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