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