| 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 | |
| 7 | In 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 | |
| 12 | You cannot mock a variadic function (i.e. a function taking ellipsis (`...`) |
| 13 | arguments) directly in gMock. |
| 14 | |
| 15 | The problem is that in general, there is *no way* for a mock object to know how |
| 16 | many arguments are passed to the variadic method, and what the arguments' types |
| 17 | are. Only the *author of the base class* knows the protocol, and we cannot look |
| 18 | into his or her head. |
| 19 | |
| 20 | Therefore, to mock such a function, the *user* must teach the mock object how to |
| 21 | figure out the number of arguments and their types. One way to do it is to |
| 22 | provide overloaded versions of the function. |
| 23 | |
| 24 | Ellipsis arguments are inherited from C and not really a C++ feature. They are |
| 25 | unsafe to use and don't work with arguments that have constructors or |
| 26 | destructors. 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 | |
| 30 | If you compile this using Microsoft Visual C++ 2005 SP1: |
| 31 | |
| 32 | ```cpp |
| 33 | class Foo { |
| 34 | ... |
| 35 | virtual void Bar(const int i) = 0; |
| 36 | }; |
| 37 | |
| 38 | class MockFoo : public Foo { |
| 39 | ... |
| 40 | MOCK_METHOD(void, Bar, (const int i), (override)); |
| 41 | }; |
| 42 | ``` |
| 43 | |
| 44 | You may get the following warning: |
| 45 | |
| 46 | ```shell |
| 47 | warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier |
| 48 | ``` |
| 49 | |
| 50 | This is a MSVC bug. The same code compiles fine with gcc, for example. If you |
| 51 | use Visual C++ 2008 SP1, you would get the warning: |
| 52 | |
| 53 | ```shell |
| 54 | 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 |
| 55 | ``` |
| 56 | |
| 57 | In C++, if you *declare* a function with a `const` parameter, the `const` |
| 58 | modifier is ignored. Therefore, the `Foo` base class above is equivalent to: |
| 59 | |
| 60 | ```cpp |
| 61 | class Foo { |
| 62 | ... |
| 63 | virtual void Bar(int i) = 0; // int or const int? Makes no difference. |
| 64 | }; |
| 65 | ``` |
| 66 | |
| 67 | In 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 | |
| 70 | Since making a parameter `const` is meaningless in the method declaration, we |
| 71 | recommend to remove it in both `Foo` and `MockFoo`. That should workaround the |
| 72 | VC bug. |
| 73 | |
| 74 | Note that we are talking about the *top-level* `const` modifier here. If the |
| 75 | function parameter is passed by pointer or reference, declaring the pointee or |
| 76 | referee as `const` is still meaningful. For example, the following two |
| 77 | declarations are *not* equivalent: |
| 78 | |
| 79 | ```cpp |
| 80 | void Bar(int* p); // Neither p nor *p is const. |
| 81 | void 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 | |
| 88 | You might want to run your test with `--gmock_verbose=info`. This flag lets |
| 89 | gMock print a trace of every mock function call it receives. By studying the |
| 90 | trace, you'll gain insights on why the expectations you set are not met. |
| 91 | |
| 92 | If you see the message "The mock function has no default action set, and its |
| 93 | return type has no default value set.", then try |
| 94 | [adding a default action](for_dummies.md#DefaultValue). Due to a known issue, |
| 95 | unexpected calls on mocks without default actions don't print out a detailed |
| 96 | comparison 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 | |
| 100 | gMock and `ScopedMockLog` are likely doing the right thing here. |
| 101 | |
| 102 | When a test crashes, the failure signal handler will try to log a lot of |
| 103 | information (the stack trace, and the address map, for example). The messages |
| 104 | are compounded if you have many threads with depth stacks. When `ScopedMockLog` |
| 105 | intercepts these messages and finds that they don't match any expectations, it |
| 106 | prints an error for each of them. |
| 107 | |
| 108 | You can learn to ignore the errors, or you can rewrite your expectations to make |
| 109 | your test more robust, for example, by adding something like: |
| 110 | |
| 111 | ```cpp |
| 112 | using ::testing::AnyNumber; |
| 113 | using ::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 |
| 123 | using ::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 | |
| 133 | When gMock detects a failure, it prints relevant information (the mock function |
| 134 | arguments, the state of relevant expectations, and etc) to help the user debug. |
| 135 | If another failure is detected, gMock will do the same, including printing the |
| 136 | state of relevant expectations. |
| 137 | |
| 138 | Sometimes an expectation's state didn't change between two failures, and you'll |
| 139 | see the same description of the state twice. They are however *not* redundant, |
| 140 | as they refer to *different points in time*. The fact they are the same *is* |
| 141 | interesting 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 | |
| 145 | Does the class (hopefully a pure interface) you are mocking have a virtual |
| 146 | destructor? |
| 147 | |
| 148 | Whenever you derive from a base class, make sure its destructor is virtual. |
| 149 | Otherwise Bad Things will happen. Consider the following code: |
| 150 | |
| 151 | ```cpp |
| 152 | class Base { |
| 153 | public: |
| 154 | // Not virtual, but should be. |
| 155 | ~Base() { ... } |
| 156 | ... |
| 157 | }; |
| 158 | |
| 159 | class 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 | |
| 173 | By 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 | |
| 178 | When people complain about this, often they are referring to code like: |
| 179 | |
| 180 | ```cpp |
| 181 | using ::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 | |
| 194 | The problem, is that they didn't pick the **best** way to express the test's |
| 195 | intent. |
| 196 | |
| 197 | By default, expectations don't have to be matched in *any* particular order. If |
| 198 | you want them to match in a certain order, you need to be explicit. This is |
| 199 | gMock's (and jMock's) fundamental philosophy: it's easy to accidentally |
| 200 | over-specify your tests, and we want to make it harder to do so. |
| 201 | |
| 202 | There are two better ways to write the test spec. You could either put the |
| 203 | expectations in sequence: |
| 204 | |
| 205 | ```cpp |
| 206 | using ::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 | |
| 222 | or you can put the sequence of actions in the same expectation: |
| 223 | |
| 224 | ```cpp |
| 225 | using ::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 | |
| 235 | Back 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 |
| 237 | behavior for the common case early (e.g. in the mock's constructor or the test |
| 238 | fixture's set-up phase) and customize it with more specific rules later. If |
| 239 | gMock 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 | |
| 243 | When choosing between being neat and being safe, we lean toward the latter. So |
| 244 | the answer is that we think it's better to show the warning. |
| 245 | |
| 246 | Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as |
| 247 | the default behavior rarely changes from test to test. Then in the test body |
| 248 | they 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. |
| 250 | If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If |
| 251 | we quietly let the call go through without notifying the user, bugs may creep in |
| 252 | unnoticed. |
| 253 | |
| 254 | If, however, you are sure that the calls are OK, you can write |
| 255 | |
| 256 | ```cpp |
| 257 | using ::testing::_; |
| 258 | ... |
| 259 | EXPECT_CALL(foo, Bar(_)) |
| 260 | .WillRepeatedly(...); |
| 261 | ``` |
| 262 | |
| 263 | instead of |
| 264 | |
| 265 | ```cpp |
| 266 | using ::testing::_; |
| 267 | ... |
| 268 | ON_CALL(foo, Bar(_)) |
| 269 | .WillByDefault(...); |
| 270 | ``` |
| 271 | |
| 272 | This tells gMock that you do expect the calls and no warning should be printed. |
| 273 | |
| 274 | Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other |
| 275 | values are `info` and `warning`. If you find the output too noisy when |
| 276 | debugging, just choose a less verbose level. |
| 277 | |
| 278 | ### How can I delete the mock function's argument in an action? |
| 279 | |
| 280 | If your mock function takes a pointer argument and you want to delete that |
| 281 | argument, you can use testing::DeleteArg<N>() to delete the N'th (zero-indexed) |
| 282 | argument: |
| 283 | |
| 284 | ```cpp |
| 285 | using ::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 | |
| 295 | If you find yourself needing to perform some action that's not supported by |
| 296 | gMock directly, remember that you can define your own actions using |
| 297 | [`MakeAction()`](#NewMonoActions) or |
| 298 | [`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function |
| 299 | and invoke it using [`Invoke()`](#FunctionsAsActions). |
| 300 | |
| 301 | ```cpp |
| 302 | using ::testing::_; |
| 303 | using ::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 | |
| 313 | You can, but you need to make some changes. |
| 314 | |
| 315 | In general, if you find yourself needing to mock a static function, it's a sign |
| 316 | that your modules are too tightly coupled (and less flexible, less reusable, |
| 317 | less testable, etc). You are probably better off defining a small interface and |
| 318 | call the function through that interface, which then can be easily mocked. It's |
| 319 | a bit of work initially, but usually pays for itself quickly. |
| 320 | |
| 321 | This Google Testing Blog |
| 322 | [post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it |
| 323 | excellently. 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 | |
| 327 | I know it's not a question, but you get an answer for free any way. :-) |
| 328 | |
| 329 | With gMock, you can create mocks in C++ easily. And people might be tempted to |
| 330 | use them everywhere. Sometimes they work great, and sometimes you may find them, |
| 331 | well, a pain to use. So, what's wrong in the latter case? |
| 332 | |
| 333 | When you write a test without using mocks, you exercise the code and assert that |
| 334 | it returns the correct value or that the system is in an expected state. This is |
| 335 | sometimes called "state-based testing". |
| 336 | |
| 337 | Mocks are great for what some call "interaction-based" testing: instead of |
| 338 | checking the system state at the very end, mock objects verify that they are |
| 339 | invoked the right way and report an error as soon as it arises, giving you a |
| 340 | handle on the precise context in which the error was triggered. This is often |
| 341 | more effective and economical to do than state-based testing. |
| 342 | |
| 343 | If you are doing state-based testing and using a test double just to simulate |
| 344 | the real object, you are probably better off using a fake. Using a mock in this |
| 345 | case causes pain, as it's not a strong point for mocks to perform complex |
| 346 | actions. If you experience this and think that mocks suck, you are just not |
| 347 | using the right tool for your problem. Or, you might be trying to solve the |
| 348 | wrong problem. :-) |
| 349 | |
| 350 | ### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic? |
| 351 | |
| 352 | By all means, NO! It's just an FYI. :-) |
| 353 | |
| 354 | What it means is that you have a mock function, you haven't set any expectations |
| 355 | on it (by gMock's rule this means that you are not interested in calls to this |
| 356 | function and therefore it can be called any number of times), and it is called. |
| 357 | That's OK - you didn't say it's not OK to call the function! |
| 358 | |
| 359 | What if you actually meant to disallow this function to be called, but forgot to |
| 360 | write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the |
| 361 | user's fault, gMock tries to be nice and prints you a note. |
| 362 | |
| 363 | So, when you see the message and believe that there shouldn't be any |
| 364 | uninteresting calls, you should investigate what's going on. To make your life |
| 365 | easier, gMock dumps the stack trace when an uninteresting call is encountered. |
| 366 | From 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 | |
| 370 | Either way is fine - you want to choose the one that's more convenient for your |
| 371 | circumstance. |
| 372 | |
| 373 | Usually, 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 |
| 375 | different types (e.g. if you are defining `Return(*value*)`), |
| 376 | `MakePolymorphicAction()` is easiest. Sometimes you want precise control on what |
| 377 | types of functions the action can be used in, and implementing `ActionInterface` |
| 378 | is 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 | |
| 383 | You got this error as gMock has no idea what value it should return when the |
| 384 | mock method is called. `SetArgPointee()` says what the side effect is, but |
| 385 | doesn'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 |
| 387 | being mocked. |
| 388 | |
| 389 | See this [recipe](cook_book.md#mocking-side-effects) for more details and an |
| 390 | example. |
| 391 | |
| 392 | ### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do? |
| 393 | |
| 394 | We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6 |
| 395 | times as much memory when compiling a mock class. We suggest to avoid `/clr` |
| 396 | when compiling native C++ mocks. |