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