Debian Codegraph @

src/external/googletest/docs/reference/mocking.md

raw
1 # Mocking Reference
2
3 This page lists the facilities provided by GoogleTest for creating and working
4 with mock objects. To use them, add `#include <gmock/gmock.h>`.
5
6 ## Macros {#macros}
7
8 GoogleTest defines the following macros for working with mocks.
9
10 ### MOCK_METHOD {#MOCK_METHOD}
11
12 `MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \
13 `MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`),
14 (`*`specs...`*`));`
15
16 Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and
17 return type *`return_type`* within a mock class.
18
19 The parameters of `MOCK_METHOD` mirror the method declaration. The optional
20 fourth parameter *`specs...`* is a comma-separated list of qualifiers. The
21 following qualifiers are accepted:
22
23 | Qualifier | Meaning |
24 | -------------------------- | -------------------------------------------- |
25 | `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. |
26 | `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. |
27 | `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. |
28 | `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. |
29 | `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. |
30
31 Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments
32 correctly if they are not appropriately surrounded by parentheses. See the
33 following example:
34
35 ```cpp
36 class MyMock {
37 public:
38 // The following 2 lines will not compile due to commas in the arguments:
39 MOCK_METHOD(std::pair<bool, int>, GetPair, ()); // Error!
40 MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool)); // Error!
41
42 // One solution - wrap arguments that contain commas in parentheses:
43 MOCK_METHOD((std::pair<bool, int>), GetPair, ());
44 MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool));
45
46 // Another solution - use type aliases:
47 using BoolAndInt = std::pair<bool, int>;
48 MOCK_METHOD(BoolAndInt, GetPair, ());
49 using MapIntDouble = std::map<int, double>;
50 MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool));
51 };
52 ```
53
54 `MOCK_METHOD` must be used in the `public:` section of a mock class definition,
55 regardless of whether the method being mocked is `public`, `protected`, or
56 `private` in the base class.
57
58 ### EXPECT_CALL {#EXPECT_CALL}
59
60 `EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
61
62 Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the
63 method *`method_name`* of the object *`mock_object`* is called with arguments
64 that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any
65 code that exercises the mock object.
66
67 The parameter *`matchers...`* is a comma-separated list of
68 [matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
69 correspond to each argument of the method *`method_name`*. The expectation will
70 apply only to calls of *`method_name`* whose arguments match all of the
71 matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if
72 each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
73 See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
74
75 The following chainable clauses can be used to modify the expectation, and they
76 must be used in the following order:
77
78 ```cpp
79 EXPECT_CALL(mock_object, method_name(matchers...))
80 .With(multi_argument_matcher) // Can be used at most once
81 .Times(cardinality) // Can be used at most once
82 .InSequence(sequences...) // Can be used any number of times
83 .After(expectations...) // Can be used any number of times
84 .WillOnce(action) // Can be used any number of times
85 .WillRepeatedly(action) // Can be used at most once
86 .RetiresOnSaturation(); // Can be used at most once
87 ```
88
89 See details for each modifier clause below.
90
91 #### With {#EXPECT_CALL.With}
92
93 `.With(`*`multi_argument_matcher`*`)`
94
95 Restricts the expectation to apply only to mock function calls whose arguments
96 as a whole match the multi-argument matcher *`multi_argument_matcher`*.
97
98 GoogleTest passes all of the arguments as one tuple into the matcher. The
99 parameter *`multi_argument_matcher`* must thus be a matcher of type
100 `Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
101 function arguments.
102
103 For example, the following code sets the expectation that
104 `my_mock.SetPosition()` is called with any two arguments, the first argument
105 being less than the second:
106
107 ```cpp
108 using ::testing::_;
109 using ::testing::Lt;
110 ...
111 EXPECT_CALL(my_mock, SetPosition(_, _))
112 .With(Lt());
113 ```
114
115 GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
116 matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
117
118 The `With` clause can be used at most once on an expectation and must be the
119 first clause.
120
121 #### Times {#EXPECT_CALL.Times}
122
123 `.Times(`*`cardinality`*`)`
124
125 Specifies how many times the mock function call is expected.
126
127 The parameter *`cardinality`* represents the number of expected calls and can be
128 one of the following, all defined in the `::testing` namespace:
129
130 | Cardinality | Meaning |
131 | ------------------- | --------------------------------------------------- |
132 | `AnyNumber()` | The function can be called any number of times. |
133 | `AtLeast(n)` | The function call is expected at least *n* times. |
134 | `AtMost(n)` | The function call is expected at most *n* times. |
135 | `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. |
136 | `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. |
137
138 If the `Times` clause is omitted, GoogleTest infers the cardinality as follows:
139
140 * If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor
141 [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred
142 cardinality is `Times(1)`.
143 * If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where
144 *n* >= 1, the inferred cardinality is `Times(n)`.
145 * If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where
146 *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`.
147
148 The `Times` clause can be used at most once on an expectation.
149
150 #### InSequence {#EXPECT_CALL.InSequence}
151
152 `.InSequence(`*`sequences...`*`)`
153
154 Specifies that the mock function call is expected in a certain sequence.
155
156 The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects.
157 Expected calls assigned to the same sequence are expected to occur in the order
158 the expectations are declared.
159
160 For example, the following code sets the expectation that the `Reset()` method
161 of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()`
162 and `Describe()` can occur in any order relative to each other:
163
164 ```cpp
165 using ::testing::Sequence;
166 Sequence s1, s2;
167 ...
168 EXPECT_CALL(my_mock, Reset())
169 .InSequence(s1, s2);
170 EXPECT_CALL(my_mock, GetSize())
171 .InSequence(s1);
172 EXPECT_CALL(my_mock, Describe())
173 .InSequence(s2);
174 ```
175
176 The `InSequence` clause can be used any number of times on an expectation.
177
178 See also the [`InSequence` class](#InSequence).
179
180 #### After {#EXPECT_CALL.After}
181
182 `.After(`*`expectations...`*`)`
183
184 Specifies that the mock function call is expected to occur after one or more
185 other calls.
186
187 The parameter *`expectations...`* can be up to five
188 [`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects.
189 The mock function call is expected to occur after all of the given expectations.
190
191 For example, the following code sets the expectation that the `Describe()`
192 method of `my_mock` is called only after both `InitX()` and `InitY()` have been
193 called.
194
195 ```cpp
196 using ::testing::Expectation;
197 ...
198 Expectation init_x = EXPECT_CALL(my_mock, InitX());
199 Expectation init_y = EXPECT_CALL(my_mock, InitY());
200 EXPECT_CALL(my_mock, Describe())
201 .After(init_x, init_y);
202 ```
203
204 The `ExpectationSet` object is helpful when the number of prerequisites for an
205 expectation is large or variable, for example:
206
207 ```cpp
208 using ::testing::ExpectationSet;
209 ...
210 ExpectationSet all_inits;
211 // Collect all expectations of InitElement() calls
212 for (int i = 0; i < element_count; i++) {
213 all_inits += EXPECT_CALL(my_mock, InitElement(i));
214 }
215 EXPECT_CALL(my_mock, Describe())
216 .After(all_inits); // Expect Describe() call after all InitElement() calls
217 ```
218
219 The `After` clause can be used any number of times on an expectation.
220
221 #### WillOnce {#EXPECT_CALL.WillOnce}
222
223 `.WillOnce(`*`action`*`)`
224
225 Specifies the mock function's actual behavior when invoked, for a single
226 matching function call.
227
228 The parameter *`action`* represents the
229 [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
230 call will perform. See the [Actions Reference](actions.md) for a list of
231 built-in actions.
232
233 The use of `WillOnce` implicitly sets a cardinality on the expectation when
234 `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
235
236 Each matching function call will perform the next action in the order declared.
237 For example, the following code specifies that `my_mock.GetNumber()` is expected
238 to be called exactly 3 times and will return `1`, `2`, and `3` respectively on
239 the first, second, and third calls:
240
241 ```cpp
242 using ::testing::Return;
243 ...
244 EXPECT_CALL(my_mock, GetNumber())
245 .WillOnce(Return(1))
246 .WillOnce(Return(2))
247 .WillOnce(Return(3));
248 ```
249
250 The `WillOnce` clause can be used any number of times on an expectation. Unlike
251 `WillRepeatedly`, the action fed to each `WillOnce` call will be called at most
252 once, so may be a move-only type and/or have an `&&`-qualified call operator.
253
254 #### WillRepeatedly {#EXPECT_CALL.WillRepeatedly}
255
256 `.WillRepeatedly(`*`action`*`)`
257
258 Specifies the mock function's actual behavior when invoked, for all subsequent
259 matching function calls. Takes effect after the actions specified in the
260 [`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed.
261
262 The parameter *`action`* represents the
263 [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
264 call will perform. See the [Actions Reference](actions.md) for a list of
265 built-in actions.
266
267 The use of `WillRepeatedly` implicitly sets a cardinality on the expectation
268 when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
269
270 If any `WillOnce` clauses have been specified, matching function calls will
271 perform those actions before the action specified by `WillRepeatedly`. See the
272 following example:
273
274 ```cpp
275 using ::testing::Return;
276 ...
277 EXPECT_CALL(my_mock, GetName())
278 .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls
279
280 EXPECT_CALL(my_mock, GetNumber())
281 .WillOnce(Return(42)) // Return 42 on the first call
282 .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls
283 ```
284
285 The `WillRepeatedly` clause can be used at most once on an expectation.
286
287 #### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation}
288
289 `.RetiresOnSaturation()`
290
291 Indicates that the expectation will no longer be active after the expected
292 number of matching function calls has been reached.
293
294 The `RetiresOnSaturation` clause is only meaningful for expectations with an
295 upper-bounded cardinality. The expectation will *retire* (no longer match any
296 function calls) after it has been *saturated* (the upper bound has been
297 reached). See the following example:
298
299 ```cpp
300 using ::testing::_;
301 using ::testing::AnyNumber;
302 ...
303 EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1
304 .Times(AnyNumber());
305 EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2
306 .Times(2)
307 .RetiresOnSaturation();
308 ```
309
310 In the above example, the first two calls to `my_mock.SetNumber(7)` match
311 expectation 2, which then becomes inactive and no longer matches any calls. A
312 third call to `my_mock.SetNumber(7)` would then match expectation 1. Without
313 `RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)`
314 would match expectation 2 again, producing a failure since the limit of 2 calls
315 was exceeded.
316
317 The `RetiresOnSaturation` clause can be used at most once on an expectation and
318 must be the last clause.
319
320 ### ON_CALL {#ON_CALL}
321
322 `ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
323
324 Defines what happens when the method *`method_name`* of the object
325 *`mock_object`* is called with arguments that match the given matchers
326 *`matchers...`*. Requires a modifier clause to specify the method's behavior.
327 *Does not* set any expectations that the method will be called.
328
329 The parameter *`matchers...`* is a comma-separated list of
330 [matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
331 correspond to each argument of the method *`method_name`*. The `ON_CALL`
332 specification will apply only to calls of *`method_name`* whose arguments match
333 all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if
334 each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
335 See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
336
337 The following chainable clauses can be used to set the method's behavior, and
338 they must be used in the following order:
339
340 ```cpp
341 ON_CALL(mock_object, method_name(matchers...))
342 .With(multi_argument_matcher) // Can be used at most once
343 .WillByDefault(action); // Required
344 ```
345
346 See details for each modifier clause below.
347
348 #### With {#ON_CALL.With}
349
350 `.With(`*`multi_argument_matcher`*`)`
351
352 Restricts the specification to only mock function calls whose arguments as a
353 whole match the multi-argument matcher *`multi_argument_matcher`*.
354
355 GoogleTest passes all of the arguments as one tuple into the matcher. The
356 parameter *`multi_argument_matcher`* must thus be a matcher of type
357 `Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
358 function arguments.
359
360 For example, the following code sets the default behavior when
361 `my_mock.SetPosition()` is called with any two arguments, the first argument
362 being less than the second:
363
364 ```cpp
365 using ::testing::_;
366 using ::testing::Lt;
367 using ::testing::Return;
368 ...
369 ON_CALL(my_mock, SetPosition(_, _))
370 .With(Lt())
371 .WillByDefault(Return(true));
372 ```
373
374 GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
375 matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
376
377 The `With` clause can be used at most once with each `ON_CALL` statement.
378
379 #### WillByDefault {#ON_CALL.WillByDefault}
380
381 `.WillByDefault(`*`action`*`)`
382
383 Specifies the default behavior of a matching mock function call.
384
385 The parameter *`action`* represents the
386 [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
387 call will perform. See the [Actions Reference](actions.md) for a list of
388 built-in actions.
389
390 For example, the following code specifies that by default, a call to
391 `my_mock.Greet()` will return `"hello"`:
392
393 ```cpp
394 using ::testing::Return;
395 ...
396 ON_CALL(my_mock, Greet())
397 .WillByDefault(Return("hello"));
398 ```
399
400 The action specified by `WillByDefault` is superseded by the actions specified
401 on a matching `EXPECT_CALL` statement, if any. See the
402 [`WillOnce`](#EXPECT_CALL.WillOnce) and
403 [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`.
404
405 The `WillByDefault` clause must be used exactly once with each `ON_CALL`
406 statement.
407
408 ## Classes {#classes}
409
410 GoogleTest defines the following classes for working with mocks.
411
412 ### DefaultValue {#DefaultValue}
413
414 `::testing::DefaultValue<T>`
415
416 Allows a user to specify the default value for a type `T` that is both copyable
417 and publicly destructible (i.e. anything that can be used as a function return
418 type). For mock functions with a return type of `T`, this default value is
419 returned from function calls that do not specify an action.
420
421 Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the
422 default value:
423
424 ```cpp
425 // Sets the default value to be returned. T must be copy constructible.
426 DefaultValue<T>::Set(value);
427
428 // Sets a factory. Will be invoked on demand. T must be move constructible.
429 T MakeT();
430 DefaultValue<T>::SetFactory(&MakeT);
431
432 // Unsets the default value.
433 DefaultValue<T>::Clear();
434 ```
435
436 ### NiceMock {#NiceMock}
437
438 `::testing::NiceMock<T>`
439
440 Represents a mock object that suppresses warnings on
441 [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
442 template parameter `T` is any mock class, except for another `NiceMock`,
443 `NaggyMock`, or `StrictMock`.
444
445 Usage of `NiceMock<T>` is analogous to usage of `T`. `NiceMock<T>` is a subclass
446 of `T`, so it can be used wherever an object of type `T` is accepted. In
447 addition, `NiceMock<T>` can be constructed with any arguments that a constructor
448 of `T` accepts.
449
450 For example, the following code suppresses warnings on the mock `my_mock` of
451 type `MockClass` if a method other than `DoSomething()` is called:
452
453 ```cpp
454 using ::testing::NiceMock;
455 ...
456 NiceMock<MockClass> my_mock("some", "args");
457 EXPECT_CALL(my_mock, DoSomething());
458 ... code that uses my_mock ...
459 ```
460
461 `NiceMock<T>` only works for mock methods defined using the `MOCK_METHOD` macro
462 directly in the definition of class `T`. If a mock method is defined in a base
463 class of `T`, a warning might still be generated.
464
465 `NiceMock<T>` might not work correctly if the destructor of `T` is not virtual.
466
467 ### NaggyMock {#NaggyMock}
468
469 `::testing::NaggyMock<T>`
470
471 Represents a mock object that generates warnings on
472 [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
473 template parameter `T` is any mock class, except for another `NiceMock`,
474 `NaggyMock`, or `StrictMock`.
475
476 Usage of `NaggyMock<T>` is analogous to usage of `T`. `NaggyMock<T>` is a
477 subclass of `T`, so it can be used wherever an object of type `T` is accepted.
478 In addition, `NaggyMock<T>` can be constructed with any arguments that a
479 constructor of `T` accepts.
480
481 For example, the following code generates warnings on the mock `my_mock` of type
482 `MockClass` if a method other than `DoSomething()` is called:
483
484 ```cpp
485 using ::testing::NaggyMock;
486 ...
487 NaggyMock<MockClass> my_mock("some", "args");
488 EXPECT_CALL(my_mock, DoSomething());
489 ... code that uses my_mock ...
490 ```
491
492 Mock objects of type `T` by default behave the same way as `NaggyMock<T>`.
493
494 ### StrictMock {#StrictMock}
495
496 `::testing::StrictMock<T>`
497
498 Represents a mock object that generates test failures on
499 [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
500 template parameter `T` is any mock class, except for another `NiceMock`,
501 `NaggyMock`, or `StrictMock`.
502
503 Usage of `StrictMock<T>` is analogous to usage of `T`. `StrictMock<T>` is a
504 subclass of `T`, so it can be used wherever an object of type `T` is accepted.
505 In addition, `StrictMock<T>` can be constructed with any arguments that a
506 constructor of `T` accepts.
507
508 For example, the following code generates a test failure on the mock `my_mock`
509 of type `MockClass` if a method other than `DoSomething()` is called:
510
511 ```cpp
512 using ::testing::StrictMock;
513 ...
514 StrictMock<MockClass> my_mock("some", "args");
515 EXPECT_CALL(my_mock, DoSomething());
516 ... code that uses my_mock ...
517 ```
518
519 `StrictMock<T>` only works for mock methods defined using the `MOCK_METHOD`
520 macro directly in the definition of class `T`. If a mock method is defined in a
521 base class of `T`, a failure might not be generated.
522
523 `StrictMock<T>` might not work correctly if the destructor of `T` is not
524 virtual.
525
526 ### Sequence {#Sequence}
527
528 `::testing::Sequence`
529
530 Represents a chronological sequence of expectations. See the
531 [`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage.
532
533 ### InSequence {#InSequence}
534
535 `::testing::InSequence`
536
537 An object of this type causes all expectations encountered in its scope to be
538 put in an anonymous sequence.
539
540 This allows more convenient expression of multiple expectations in a single
541 sequence:
542
543 ```cpp
544 using ::testing::InSequence;
545 {
546 InSequence seq;
547
548 // The following are expected to occur in the order declared.
549 EXPECT_CALL(...);
550 EXPECT_CALL(...);
551 ...
552 EXPECT_CALL(...);
553 }
554 ```
555
556 The name of the `InSequence` object does not matter.
557
558 ### Expectation {#Expectation}
559
560 `::testing::Expectation`
561
562 Represents a mock function call expectation as created by
563 [`EXPECT_CALL`](#EXPECT_CALL):
564
565 ```cpp
566 using ::testing::Expectation;
567 Expectation my_expectation = EXPECT_CALL(...);
568 ```
569
570 Useful for specifying sequences of expectations; see the
571 [`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.
572
573 ### ExpectationSet {#ExpectationSet}
574
575 `::testing::ExpectationSet`
576
577 Represents a set of mock function call expectations.
578
579 Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set:
580
581 ```cpp
582 using ::testing::ExpectationSet;
583 ExpectationSet my_expectations;
584 my_expectations += EXPECT_CALL(...);
585 ```
586
587 Useful for specifying sequences of expectations; see the
588 [`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.