OpenCores
URL https://opencores.org/ocsvn/s80186/s80186/trunk

Subversion Repositories s80186

[/] [s80186/] [trunk/] [vendor/] [googletest/] [googlemock/] [docs/] [v1_5/] [FrequentlyAskedQuestions.md] - Blame information for rev 2

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 jamieiles
 
2
 
3
Please send your questions to the
4
[googlemock](http://groups.google.com/group/googlemock) discussion
5
group. If you need help with compiler errors, make sure you have
6
tried [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
 
10
After version 1.4.0 of Google Mock was released, we had an idea on how
11
to make it easier to write matchers that can generate informative
12
messages efficiently.  We experimented with this idea and liked what
13
we saw.  Therefore we decided to implement it.
14
 
15
Unfortunately, this means that if you have defined your own matchers
16
by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
17
your definitions will no longer compile.  Matchers defined using the
18
`MATCHER*` family of macros are not affected.
19
 
20
Sorry for the hassle if your matchers are affected.  We believe it's
21
in everyone's long-term interest to make this change sooner than
22
later.  Fortunately, it's usually not hard to migrate an existing
23
matcher to the new API.  Here's what you need to do:
24
 
25
If you wrote your matcher like this:
26
```
27
// Old matcher definition that doesn't work with the latest
28
// Google Mock.
29
using ::testing::MatcherInterface;
30
...
31
class MyWonderfulMatcher : public MatcherInterface {
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
 
42
you'll need to change it to:
43
```
44
// New matcher definition that works with the latest Google Mock.
45
using ::testing::MatcherInterface;
46
using ::testing::MatchResultListener;
47
...
48
class MyWonderfulMatcher : public MatcherInterface {
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
60
argument of type `MatchResultListener*`.)
61
 
62
If you were also using `ExplainMatchResultTo()` to improve the matcher
63
message:
64
```
65
// Old matcher definition that doesn't work with the lastest
66
// Google Mock.
67
using ::testing::MatcherInterface;
68
...
69
class MyWonderfulMatcher : public MatcherInterface {
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
 
87
you should move the logic of `ExplainMatchResultTo()` into
88
`MatchAndExplain()`, using the `MatchResultListener` argument where
89
the `::std::ostream` was used:
90
```
91
// New matcher definition that works with the latest Google Mock.
92
using ::testing::MatcherInterface;
93
using ::testing::MatchResultListener;
94
...
95
class MyWonderfulMatcher : public MatcherInterface {
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
 
108
If your matcher is defined using `MakePolymorphicMatcher()`:
109
```
110
// Old matcher definition that doesn't work with the latest
111
// Google Mock.
112
using ::testing::MakePolymorphicMatcher;
113
...
114
class 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
 
126
you should rename the `Matches()` method to `MatchAndExplain()` and
127
add a `MatchResultListener*` argument (the same as what you need to do
128
for matchers defined by implementing `MatcherInterface`):
129
```
130
// New matcher definition that works with the latest Google Mock.
131
using ::testing::MakePolymorphicMatcher;
132
using ::testing::MatchResultListener;
133
...
134
class 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
 
147
If your polymorphic matcher uses `ExplainMatchResultTo()` for better
148
failure messages:
149
```
150
// Old matcher definition that doesn't work with the latest
151
// Google Mock.
152
using ::testing::MakePolymorphicMatcher;
153
...
154
class MyGreatMatcher {
155
 public:
156
  ...
157
  bool Matches(MyType value) const {
158
    // Returns true if value matches.
159
    return value.GetBar() < 42;
160
  }
161
  ...
162
};
163
void 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
 
173
you'll need to move the logic inside `ExplainMatchResultTo()` to
174
`MatchAndExplain()`:
175
```
176
// New matcher definition that works with the latest Google Mock.
177
using ::testing::MakePolymorphicMatcher;
178
using ::testing::MatchResultListener;
179
...
180
class 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
 
194
For 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)
197
from the cookbook.  As always, you
198
are welcome to post questions on `googlemock@googlegroups.com` if you
199
need 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
 
203
Google Mock works out of the box with Google Test.  However, it's easy
204
to 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
 
209
If you are confused by the compiler errors gcc threw at you,
210
try consulting the _Google Mock Doctor_ tool first.  What it does is to
211
scan stdin for gcc error messages, and spit out diagnoses on the
212
problems (we call them diseases) your code has.
213
 
214
To "install", run command:
215
```
216
alias gmd='/scripts/gmock_doctor.py'
217
```
218
 
219
To use it, do:
220
```
221
  2>&1 | gmd
222
```
223
 
224
For example:
225
```
226
make my_test 2>&1 | gmd
227
```
228
 
229
Or you can run `gmd` and copy-n-paste gcc's error messages to it.
230
 
231
## Can I mock a variadic function? ##
232
 
233
You cannot mock a variadic function (i.e. a function taking ellipsis
234
(`...`) arguments) directly in Google Mock.
235
 
236
The problem is that in general, there is _no way_ for a mock object to
237
know how many arguments are passed to the variadic method, and what
238
the arguments' types are.  Only the _author of the base class_ knows
239
the protocol, and we cannot look into his head.
240
 
241
Therefore, to mock such a function, the _user_ must teach the mock
242
object how to figure out the number of arguments and their types.  One
243
way to do it is to provide overloaded versions of the function.
244
 
245
Ellipsis arguments are inherited from C and not really a C++ feature.
246
They are unsafe to use and don't work with arguments that have
247
constructors or destructors.  Therefore we recommend to avoid them in
248
C++ 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
 
252
If you compile this using Microsoft Visual C++ 2005 SP1:
253
```
254
class Foo {
255
  ...
256
  virtual void Bar(const int i) = 0;
257
};
258
 
259
class MockFoo : public Foo {
260
  ...
261
  MOCK_METHOD1(Bar, void(const int i));
262
};
263
```
264
You may get the following warning:
265
```
266
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
267
```
268
 
269
This is a MSVC bug.  The same code compiles fine with gcc ,for
270
example.  If you use Visual C++ 2008 SP1, you would get the warning:
271
```
272
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
273
```
274
 
275
In C++, if you _declare_ a function with a `const` parameter, the
276
`const` modifier is _ignored_.  Therefore, the `Foo` base class above
277
is equivalent to:
278
```
279
class Foo {
280
  ...
281
  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.
282
};
283
```
284
 
285
In fact, you can _declare_ Bar() with an `int` parameter, and _define_
286
it with a `const int` parameter.  The compiler will still match them
287
up.
288
 
289
Since making a parameter `const` is meaningless in the method
290
_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
291
That should workaround the VC bug.
292
 
293
Note that we are talking about the _top-level_ `const` modifier here.
294
If the function parameter is passed by pointer or reference, declaring
295
the _pointee_ or _referee_ as `const` is still meaningful.  For
296
example, the following two declarations are _not_ equivalent:
297
```
298
void Bar(int* p);        // Neither p nor *p is const.
299
void 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
 
304
We've noticed that when the `/clr` compiler flag is used, Visual C++
305
uses 5~6 times as much memory when compiling a mock class.  We suggest
306
to 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
 
310
You might want to run your test with
311
`--gmock_verbose=info`.  This flag lets Google Mock print a trace
312
of every mock function call it receives.  By studying the trace,
313
you'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
```
318
EXPECT_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
 
324
When Google Mock detects a failure, it prints relevant information
325
(the mock function arguments, the state of relevant expectations, and
326
etc) to help the user debug.  If another failure is detected, Google
327
Mock will do the same, including printing the state of relevant
328
expectations.
329
 
330
Sometimes an expectation's state didn't change between two failures,
331
and you'll see the same description of the state twice.  They are
332
however _not_ redundant, as they refer to _different points in time_.
333
The 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
 
337
Does the class (hopefully a pure interface) you are mocking have a
338
virtual destructor?
339
 
340
Whenever you derive from a base class, make sure its destructor is
341
virtual.  Otherwise Bad Things will happen.  Consider the following
342
code:
343
 
344
```
345
class Base {
346
 public:
347
  // Not virtual, but should be.
348
  ~Base() { ... }
349
  ...
350
};
351
 
352
class 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
 
366
By changing `~Base()` to virtual, `~Derived()` will be correctly
367
called when `delete p` is executed, and the heap checker
368
will be happy.
369
 
370
## The "newer expectations override older ones" rule makes writing expectations awkward.  Why does Google Mock do that? ##
371
 
372
When 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!!!
378
EXPECT_CALL(foo, Bar())
379
    .WillOnce(Return(2))
380
    .RetiresOnSaturation();
381
EXPECT_CALL(foo, Bar())
382
    .WillOnce(Return(1))
383
    .RetiresOnSaturation();
384
```
385
 
386
The problem is that they didn't pick the **best** way to express the test's
387
intent.
388
 
389
By default, expectations don't have to be matched in _any_ particular
390
order.  If you want them to match in a certain order, you need to be
391
explicit.  This is Google Mock's (and jMock's) fundamental philosophy: it's
392
easy to accidentally over-specify your tests, and we want to make it
393
harder to do so.
394
 
395
There are two better ways to write the test spec.  You could either
396
put 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
 
413
or 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.
418
EXPECT_CALL(foo, Bar())
419
    .WillOnce(Return(1))
420
    .WillOnce(Return(2))
421
    .RetiresOnSaturation();
422
```
423
 
424
Back to the original questions: why does Google Mock search the
425
expectations (and `ON_CALL`s) from back to front?  Because this
426
allows 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)
428
and customize it with more specific rules later.  If Google Mock
429
searches from front to back, this very useful pattern won't be
430
possible.
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
 
434
When choosing between being neat and being safe, we lean toward the
435
latter.  So the answer is that we think it's better to show the
436
warning.
437
 
438
Often people write `ON_CALL`s in the mock object's
439
constructor or `SetUp()`, as the default behavior rarely changes from
440
test to test.  Then in the test body they set the expectations, which
441
are often different for each test.  Having an `ON_CALL` in the set-up
442
part of a test doesn't mean that the calls are expected.  If there's
443
no `EXPECT_CALL` and the method is called, it's possibly an error.  If
444
we quietly let the call go through without notifying the user, bugs
445
may creep in unnoticed.
446
 
447
If, however, you are sure that the calls are OK, you can write
448
 
449
```
450
EXPECT_CALL(foo, Bar(_))
451
    .WillRepeatedly(...);
452
```
453
 
454
instead of
455
 
456
```
457
ON_CALL(foo, Bar(_))
458
    .WillByDefault(...);
459
```
460
 
461
This tells Google Mock that you do expect the calls and no warning should be
462
printed.
463
 
464
Also, you can control the verbosity using the `--gmock_verbose` flag.
465
If you find the output too noisy when debugging, just choose a less
466
verbose level.
467
 
468
## How can I delete the mock function's argument in an action? ##
469
 
470
If you find yourself needing to perform some action that's not
471
supported by Google Mock directly, remember that you can define your own
472
actions using
473
[MakeAction()](V1_5_CookBook#Writing_New_Actions.md) or
474
[MakePolymorphicAction()](V1_5_CookBook#Writing_New_Polymorphic_Actions.md),
475
or 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
 
480
What?!  I think it's beautiful. :-)
481
 
482
While which syntax looks more natural is a subjective matter to some
483
extent, Google Mock's syntax was chosen for several practical advantages it
484
has.
485
 
486
Try to mock a function that takes a map as an argument:
487
```
488
virtual int GetSize(const map& m);
489
```
490
 
491
Using the proposed syntax, it would be:
492
```
493
MOCK_METHOD1(GetSize, int, const map& m);
494
```
495
 
496
Guess what?  You'll get a compiler error as the compiler thinks that
497
`const map& m` are **two**, not one, arguments. To work
498
around this you can use `typedef` to give the map type a name, but
499
that gets in the way of your work.  Google Mock's syntax avoids this
500
problem as the function's argument types are protected inside a pair
501
of parentheses:
502
```
503
// This compiles fine.
504
MOCK_METHOD1(GetSize, int(const map& m));
505
```
506
 
507
You still need a `typedef` if the return type contains an unprotected
508
comma, but that's much rarer.
509
 
510
Other 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
 
517
You can, but you need to make some changes.
518
 
519
In general, if you find yourself needing to mock a static function,
520
it's a sign that your modules are too tightly coupled (and less
521
flexible, less reusable, less testable, etc).  You are probably better
522
off defining a small interface and call the function through that
523
interface, which then can be easily mocked.  It's a bit of work
524
initially, but usually pays for itself quickly.
525
 
526
This Google Testing Blog
527
[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
528
says 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
 
532
I know it's not a question, but you get an answer for free any way. :-)
533
 
534
With Google Mock, you can create mocks in C++ easily.  And people might be
535
tempted to use them everywhere. Sometimes they work great, and
536
sometimes you may find them, well, a pain to use. So, what's wrong in
537
the latter case?
538
 
539
When you write a test without using mocks, you exercise the code and
540
assert that it returns the correct value or that the system is in an
541
expected state.  This is sometimes called "state-based testing".
542
 
543
Mocks are great for what some call "interaction-based" testing:
544
instead of checking the system state at the very end, mock objects
545
verify that they are invoked the right way and report an error as soon
546
as it arises, giving you a handle on the precise context in which the
547
error was triggered.  This is often more effective and economical to
548
do than state-based testing.
549
 
550
If you are doing state-based testing and using a test double just to
551
simulate the real object, you are probably better off using a fake.
552
Using a mock in this case causes pain, as it's not a strong point for
553
mocks to perform complex actions.  If you experience this and think
554
that mocks suck, you are just not using the right tool for your
555
problem. 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
 
559
By all means, NO!  It's just an FYI.
560
 
561
What it means is that you have a mock function, you haven't set any
562
expectations on it (by Google Mock's rule this means that you are not
563
interested in calls to this function and therefore it can be called
564
any number of times), and it is called.  That's OK - you didn't say
565
it's not OK to call the function!
566
 
567
What if you actually meant to disallow this function to be called, but
568
forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`?  While
569
one can argue that it's the user's fault, Google Mock tries to be nice and
570
prints you a note.
571
 
572
So, when you see the message and believe that there shouldn't be any
573
uninteresting calls, you should investigate what's going on.  To make
574
your life easier, Google Mock prints the function name and arguments
575
when an uninteresting call is encountered.
576
 
577
## I want to define a custom action.  Should I use Invoke() or implement the action interface? ##
578
 
579
Either way is fine - you want to choose the one that's more convenient
580
for your circumstance.
581
 
582
Usually, if your action is for a particular function type, defining it
583
using `Invoke()` should be easier; if your action can be used in
584
functions of different types (e.g. if you are defining
585
`Return(value)`), `MakePolymorphicAction()` is
586
easiest.  Sometimes you want precise control on what types of
587
functions 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
 
593
You got this error as Google Mock has no idea what value it should return
594
when the mock method is called.  `SetArgumentPointee()` says what the
595
side effect is, but doesn't say what the return value should be.  You
596
need `DoAll()` to chain a `SetArgumentPointee()` with a `Return()`.
597
 
598
See 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
 
603
If you cannot find the answer to your question in this FAQ, there are
604
some 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
 
610
Please note that creating an issue in the
611
[issue tracker](http://code.google.com/p/googlemock/issues/list) is _not_
612
a good way to get your answer, as it is monitored infrequently by a
613
very small number of people.
614
 
615
When asking a question, it's helpful to provide as much of the
616
following information as possible (people cannot help you if there's
617
not 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.

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.