1## Legacy gMock FAQ {#GMockFaq} 2 3<!-- GOOGLETEST_CM0021 DO NOT DELETE --> 4 5### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem? 6 7In order for a method to be mocked, it must be *virtual*, unless you use the 8[high-perf dependency injection technique](#MockingNonVirtualMethods). 9 10### Can I mock a variadic function? 11 12You cannot mock a variadic function (i.e. a function taking ellipsis (`...`) 13arguments) directly in gMock. 14 15The problem is that in general, there is *no way* for a mock object to know how 16many arguments are passed to the variadic method, and what the arguments' types 17are. Only the *author of the base class* knows the protocol, and we cannot look 18into his or her head. 19 20Therefore, to mock such a function, the *user* must teach the mock object how to 21figure out the number of arguments and their types. One way to do it is to 22provide overloaded versions of the function. 23 24Ellipsis arguments are inherited from C and not really a C++ feature. They are 25unsafe to use and don't work with arguments that have constructors or 26destructors. Therefore we recommend to avoid them in C++ as much as possible. 27 28### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why? 29 30If you compile this using Microsoft Visual C++ 2005 SP1: 31 32```cpp 33class Foo { 34 ... 35 virtual void Bar(const int i) = 0; 36}; 37 38class MockFoo : public Foo { 39 ... 40 MOCK_METHOD(void, Bar, (const int i), (override)); 41}; 42``` 43 44You may get the following warning: 45 46```shell 47warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier 48``` 49 50This is a MSVC bug. The same code compiles fine with gcc, for example. If you 51use Visual C++ 2008 SP1, you would get the warning: 52 53```shell 54warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers 55``` 56 57In C++, if you *declare* a function with a `const` parameter, the `const` 58modifier is ignored. Therefore, the `Foo` base class above is equivalent to: 59 60```cpp 61class Foo { 62 ... 63 virtual void Bar(int i) = 0; // int or const int? Makes no difference. 64}; 65``` 66 67In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a 68`const int` parameter. The compiler will still match them up. 69 70Since making a parameter `const` is meaningless in the method declaration, we 71recommend to remove it in both `Foo` and `MockFoo`. That should workaround the 72VC bug. 73 74Note that we are talking about the *top-level* `const` modifier here. If the 75function parameter is passed by pointer or reference, declaring the pointee or 76referee as `const` is still meaningful. For example, the following two 77declarations are *not* equivalent: 78 79```cpp 80void Bar(int* p); // Neither p nor *p is const. 81void Bar(const int* p); // p is not const, but *p is. 82``` 83 84<!-- GOOGLETEST_CM0030 DO NOT DELETE --> 85 86### I can't figure out why gMock thinks my expectations are not satisfied. What should I do? 87 88You might want to run your test with `--gmock_verbose=info`. This flag lets 89gMock print a trace of every mock function call it receives. By studying the 90trace, you'll gain insights on why the expectations you set are not met. 91 92If you see the message "The mock function has no default action set, and its 93return type has no default value set.", then try 94[adding a default action](for_dummies.md#DefaultValue). Due to a known issue, 95unexpected calls on mocks without default actions don't print out a detailed 96comparison between the actual arguments and the expected arguments. 97 98### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug? 99 100gMock and `ScopedMockLog` are likely doing the right thing here. 101 102When a test crashes, the failure signal handler will try to log a lot of 103information (the stack trace, and the address map, for example). The messages 104are compounded if you have many threads with depth stacks. When `ScopedMockLog` 105intercepts these messages and finds that they don't match any expectations, it 106prints an error for each of them. 107 108You can learn to ignore the errors, or you can rewrite your expectations to make 109your test more robust, for example, by adding something like: 110 111```cpp 112using ::testing::AnyNumber; 113using ::testing::Not; 114... 115 // Ignores any log not done by us. 116 EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _)) 117 .Times(AnyNumber()); 118``` 119 120### How can I assert that a function is NEVER called? 121 122```cpp 123using ::testing::_; 124... 125 EXPECT_CALL(foo, Bar(_)) 126 .Times(0); 127``` 128 129<!-- GOOGLETEST_CM0031 DO NOT DELETE --> 130 131### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant? 132 133When gMock detects a failure, it prints relevant information (the mock function 134arguments, the state of relevant expectations, and etc) to help the user debug. 135If another failure is detected, gMock will do the same, including printing the 136state of relevant expectations. 137 138Sometimes an expectation's state didn't change between two failures, and you'll 139see the same description of the state twice. They are however *not* redundant, 140as they refer to *different points in time*. The fact they are the same *is* 141interesting information. 142 143### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong? 144 145Does the class (hopefully a pure interface) you are mocking have a virtual 146destructor? 147 148Whenever you derive from a base class, make sure its destructor is virtual. 149Otherwise Bad Things will happen. Consider the following code: 150 151```cpp 152class Base { 153 public: 154 // Not virtual, but should be. 155 ~Base() { ... } 156 ... 157}; 158 159class Derived : public Base { 160 public: 161 ... 162 private: 163 std::string value_; 164}; 165 166... 167 Base* p = new Derived; 168 ... 169 delete p; // Surprise! ~Base() will be called, but ~Derived() will not 170 // - value_ is leaked. 171``` 172 173By changing `~Base()` to virtual, `~Derived()` will be correctly called when 174`delete p` is executed, and the heap checker will be happy. 175 176### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that? 177 178When people complain about this, often they are referring to code like: 179 180```cpp 181using ::testing::Return; 182... 183 // foo.Bar() should be called twice, return 1 the first time, and return 184 // 2 the second time. However, I have to write the expectations in the 185 // reverse order. This sucks big time!!! 186 EXPECT_CALL(foo, Bar()) 187 .WillOnce(Return(2)) 188 .RetiresOnSaturation(); 189 EXPECT_CALL(foo, Bar()) 190 .WillOnce(Return(1)) 191 .RetiresOnSaturation(); 192``` 193 194The problem, is that they didn't pick the **best** way to express the test's 195intent. 196 197By default, expectations don't have to be matched in *any* particular order. If 198you want them to match in a certain order, you need to be explicit. This is 199gMock's (and jMock's) fundamental philosophy: it's easy to accidentally 200over-specify your tests, and we want to make it harder to do so. 201 202There are two better ways to write the test spec. You could either put the 203expectations in sequence: 204 205```cpp 206using ::testing::Return; 207... 208 // foo.Bar() should be called twice, return 1 the first time, and return 209 // 2 the second time. Using a sequence, we can write the expectations 210 // in their natural order. 211 { 212 InSequence s; 213 EXPECT_CALL(foo, Bar()) 214 .WillOnce(Return(1)) 215 .RetiresOnSaturation(); 216 EXPECT_CALL(foo, Bar()) 217 .WillOnce(Return(2)) 218 .RetiresOnSaturation(); 219 } 220``` 221 222or you can put the sequence of actions in the same expectation: 223 224```cpp 225using ::testing::Return; 226... 227 // foo.Bar() should be called twice, return 1 the first time, and return 228 // 2 the second time. 229 EXPECT_CALL(foo, Bar()) 230 .WillOnce(Return(1)) 231 .WillOnce(Return(2)) 232 .RetiresOnSaturation(); 233``` 234 235Back to the original questions: why does gMock search the expectations (and 236`ON_CALL`s) from back to front? Because this allows a user to set up a mock's 237behavior for the common case early (e.g. in the mock's constructor or the test 238fixture's set-up phase) and customize it with more specific rules later. If 239gMock searches from front to back, this very useful pattern won't be possible. 240 241### gMock 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? 242 243When choosing between being neat and being safe, we lean toward the latter. So 244the answer is that we think it's better to show the warning. 245 246Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as 247the default behavior rarely changes from test to test. Then in the test body 248they set the expectations, which are often different for each test. Having an 249`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected. 250If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If 251we quietly let the call go through without notifying the user, bugs may creep in 252unnoticed. 253 254If, however, you are sure that the calls are OK, you can write 255 256```cpp 257using ::testing::_; 258... 259 EXPECT_CALL(foo, Bar(_)) 260 .WillRepeatedly(...); 261``` 262 263instead of 264 265```cpp 266using ::testing::_; 267... 268 ON_CALL(foo, Bar(_)) 269 .WillByDefault(...); 270``` 271 272This tells gMock that you do expect the calls and no warning should be printed. 273 274Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other 275values are `info` and `warning`. If you find the output too noisy when 276debugging, just choose a less verbose level. 277 278### How can I delete the mock function's argument in an action? 279 280If your mock function takes a pointer argument and you want to delete that 281argument, you can use testing::DeleteArg<N>() to delete the N'th (zero-indexed) 282argument: 283 284```cpp 285using ::testing::_; 286 ... 287 MOCK_METHOD(void, Bar, (X* x, const Y& y)); 288 ... 289 EXPECT_CALL(mock_foo_, Bar(_, _)) 290 .WillOnce(testing::DeleteArg<0>())); 291``` 292 293### How can I perform an arbitrary action on a mock function's argument? 294 295If you find yourself needing to perform some action that's not supported by 296gMock directly, remember that you can define your own actions using 297[`MakeAction()`](#NewMonoActions) or 298[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function 299and invoke it using [`Invoke()`](#FunctionsAsActions). 300 301```cpp 302using ::testing::_; 303using ::testing::Invoke; 304 ... 305 MOCK_METHOD(void, Bar, (X* p)); 306 ... 307 EXPECT_CALL(mock_foo_, Bar(_)) 308 .WillOnce(Invoke(MyAction(...))); 309``` 310 311### My code calls a static/global function. Can I mock it? 312 313You can, but you need to make some changes. 314 315In general, if you find yourself needing to mock a static function, it's a sign 316that your modules are too tightly coupled (and less flexible, less reusable, 317less testable, etc). You are probably better off defining a small interface and 318call the function through that interface, which then can be easily mocked. It's 319a bit of work initially, but usually pays for itself quickly. 320 321This Google Testing Blog 322[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it 323excellently. Check it out. 324 325### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks! 326 327I know it's not a question, but you get an answer for free any way. :-) 328 329With gMock, you can create mocks in C++ easily. And people might be tempted to 330use them everywhere. Sometimes they work great, and sometimes you may find them, 331well, a pain to use. So, what's wrong in the latter case? 332 333When you write a test without using mocks, you exercise the code and assert that 334it returns the correct value or that the system is in an expected state. This is 335sometimes called "state-based testing". 336 337Mocks are great for what some call "interaction-based" testing: instead of 338checking the system state at the very end, mock objects verify that they are 339invoked the right way and report an error as soon as it arises, giving you a 340handle on the precise context in which the error was triggered. This is often 341more effective and economical to do than state-based testing. 342 343If you are doing state-based testing and using a test double just to simulate 344the real object, you are probably better off using a fake. Using a mock in this 345case causes pain, as it's not a strong point for mocks to perform complex 346actions. If you experience this and think that mocks suck, you are just not 347using the right tool for your problem. Or, you might be trying to solve the 348wrong problem. :-) 349 350### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? 351 352By all means, NO! It's just an FYI. :-) 353 354What it means is that you have a mock function, you haven't set any expectations 355on it (by gMock's rule this means that you are not interested in calls to this 356function and therefore it can be called any number of times), and it is called. 357That's OK - you didn't say it's not OK to call the function! 358 359What if you actually meant to disallow this function to be called, but forgot to 360write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the 361user's fault, gMock tries to be nice and prints you a note. 362 363So, when you see the message and believe that there shouldn't be any 364uninteresting calls, you should investigate what's going on. To make your life 365easier, gMock dumps the stack trace when an uninteresting call is encountered. 366From that you can figure out which mock function it is, and how it is called. 367 368### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface? 369 370Either way is fine - you want to choose the one that's more convenient for your 371circumstance. 372 373Usually, if your action is for a particular function type, defining it using 374`Invoke()` should be easier; if your action can be used in functions of 375different types (e.g. if you are defining `Return(*value*)`), 376`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what 377types of functions the action can be used in, and implementing `ActionInterface` 378is the way to go here. See the implementation of `Return()` in 379`testing/base/public/gmock-actions.h` for an example. 380 381### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean? 382 383You got this error as gMock has no idea what value it should return when the 384mock method is called. `SetArgPointee()` says what the side effect is, but 385doesn't say what the return value should be. You need `DoAll()` to chain a 386`SetArgPointee()` with a `Return()` that provides a value appropriate to the API 387being mocked. 388 389See this [recipe](cook_book.md#mocking-side-effects) for more details and an 390example. 391 392### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? 393 394We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6 395times as much memory when compiling a mock class. We suggest to avoid `/clr` 396when compiling native C++ mocks. 397