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