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