3 This page lists the facilities provided by GoogleTest for creating and working
4 with mock objects. To use them, include the header
9 GoogleTest defines the following macros for working with mocks.
11 ### MOCK_METHOD {#MOCK_METHOD}
13 `MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \
14 `MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`),
17 Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and
18 return type *`return_type`* within a mock class.
20 The parameters of `MOCK_METHOD` mirror the method declaration. The optional
21 fourth parameter *`specs...`* is a comma-separated list of qualifiers. The
22 following qualifiers are accepted:
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. |
32 Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments
33 correctly if they are not appropriately surrounded by parentheses. See the
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!
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));
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));
55 `MOCK_METHOD` must be used in the `public:` section of a mock class definition,
56 regardless of whether the method being mocked is `public`, `protected`, or
57 `private` in the base class.
59 ### EXPECT_CALL {#EXPECT_CALL}
61 `EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
63 Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the
64 method *`method_name`* of the object *`mock_object`* is called with arguments
65 that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any
66 code that exercises the mock object.
68 The parameter *`matchers...`* is a comma-separated list of
69 [matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
70 correspond to each argument of the method *`method_name`*. The expectation will
71 apply only to calls of *`method_name`* whose arguments match all of the
72 matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if
73 each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
74 See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
76 The following chainable clauses can be used to modify the expectation, and they
77 must be used in the following order:
80 EXPECT_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
90 See details for each modifier clause below.
92 #### With {#EXPECT_CALL.With}
94 `.With(`*`multi_argument_matcher`*`)`
96 Restricts the expectation to apply only to mock function calls whose arguments
97 as a whole match the multi-argument matcher *`multi_argument_matcher`*.
99 GoogleTest passes all of the arguments as one tuple into the matcher. The
100 parameter *`multi_argument_matcher`* must thus be a matcher of type
101 `Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
104 For example, the following code sets the expectation that
105 `my_mock.SetPosition()` is called with any two arguments, the first argument
106 being less than the second:
112 EXPECT_CALL(my_mock, SetPosition(_, _))
116 GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
117 matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
119 The `With` clause can be used at most once on an expectation and must be the
122 #### Times {#EXPECT_CALL.Times}
124 `.Times(`*`cardinality`*`)`
126 Specifies how many times the mock function call is expected.
128 The parameter *`cardinality`* represents the number of expected calls and can be
129 one of the following, all defined in the `::testing` namespace:
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. |
139 If the `Times` clause is omitted, GoogleTest infers the cardinality as follows:
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))`.
149 The `Times` clause can be used at most once on an expectation.
151 #### InSequence {#EXPECT_CALL.InSequence}
153 `.InSequence(`*`sequences...`*`)`
155 Specifies that the mock function call is expected in a certain sequence.
157 The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects.
158 Expected calls assigned to the same sequence are expected to occur in the order
159 the expectations are declared.
161 For example, the following code sets the expectation that the `Reset()` method
162 of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()`
163 and `Describe()` can occur in any order relative to each other:
166 using ::testing::Sequence;
169 EXPECT_CALL(my_mock, Reset())
171 EXPECT_CALL(my_mock, GetSize())
173 EXPECT_CALL(my_mock, Describe())
177 The `InSequence` clause can be used any number of times on an expectation.
179 See also the [`InSequence` class](#InSequence).
181 #### After {#EXPECT_CALL.After}
183 `.After(`*`expectations...`*`)`
185 Specifies that the mock function call is expected to occur after one or more
188 The parameter *`expectations...`* can be up to five
189 [`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects.
190 The mock function call is expected to occur after all of the given expectations.
192 For example, the following code sets the expectation that the `Describe()`
193 method of `my_mock` is called only after both `InitX()` and `InitY()` have been
197 using ::testing::Expectation;
199 Expectation init_x = EXPECT_CALL(my_mock, InitX());
200 Expectation init_y = EXPECT_CALL(my_mock, InitY());
201 EXPECT_CALL(my_mock, Describe())
202 .After(init_x, init_y);
205 The `ExpectationSet` object is helpful when the number of prerequisites for an
206 expectation is large or variable, for example:
209 using ::testing::ExpectationSet;
211 ExpectationSet all_inits;
212 // Collect all expectations of InitElement() calls
213 for (int i = 0; i < element_count; i++) {
214 all_inits += EXPECT_CALL(my_mock, InitElement(i));
216 EXPECT_CALL(my_mock, Describe())
217 .After(all_inits); // Expect Describe() call after all InitElement() calls
220 The `After` clause can be used any number of times on an expectation.
222 #### WillOnce {#EXPECT_CALL.WillOnce}
224 `.WillOnce(`*`action`*`)`
226 Specifies the mock function's actual behavior when invoked, for a single
227 matching function call.
229 The parameter *`action`* represents the
230 [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
231 call will perform. See the [Actions Reference](actions.md) for a list of
234 The use of `WillOnce` implicitly sets a cardinality on the expectation when
235 `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
237 Each matching function call will perform the next action in the order declared.
238 For example, the following code specifies that `my_mock.GetNumber()` is expected
239 to be called exactly 3 times and will return `1`, `2`, and `3` respectively on
240 the first, second, and third calls:
243 using ::testing::Return;
245 EXPECT_CALL(my_mock, GetNumber())
248 .WillOnce(Return(3));
251 The `WillOnce` clause can be used any number of times on an expectation.
253 #### WillRepeatedly {#EXPECT_CALL.WillRepeatedly}
255 `.WillRepeatedly(`*`action`*`)`
257 Specifies the mock function's actual behavior when invoked, for all subsequent
258 matching function calls. Takes effect after the actions specified in the
259 [`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed.
261 The parameter *`action`* represents the
262 [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
263 call will perform. See the [Actions Reference](actions.md) for a list of
266 The use of `WillRepeatedly` implicitly sets a cardinality on the expectation
267 when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
269 If any `WillOnce` clauses have been specified, matching function calls will
270 perform those actions before the action specified by `WillRepeatedly`. See the
274 using ::testing::Return;
276 EXPECT_CALL(my_mock, GetName())
277 .WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls
279 EXPECT_CALL(my_mock, GetNumber())
280 .WillOnce(Return(42)) // Return 42 on the first call
281 .WillRepeatedly(Return(7)); // Return 7 on all subsequent calls
284 The `WillRepeatedly` clause can be used at most once on an expectation.
286 #### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation}
288 `.RetiresOnSaturation()`
290 Indicates that the expectation will no longer be active after the expected
291 number of matching function calls has been reached.
293 The `RetiresOnSaturation` clause is only meaningful for expectations with an
294 upper-bounded cardinality. The expectation will *retire* (no longer match any
295 function calls) after it has been *saturated* (the upper bound has been
296 reached). See the following example:
300 using ::testing::AnyNumber;
302 EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1
304 EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2
306 .RetiresOnSaturation();
309 In the above example, the first two calls to `my_mock.SetNumber(7)` match
310 expectation 2, which then becomes inactive and no longer matches any calls. A
311 third call to `my_mock.SetNumber(7)` would then match expectation 1. Without
312 `RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)`
313 would match expectation 2 again, producing a failure since the limit of 2 calls
316 The `RetiresOnSaturation` clause can be used at most once on an expectation and
317 must be the last clause.
319 ### ON_CALL {#ON_CALL}
321 `ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
323 Defines what happens when the method *`method_name`* of the object
324 *`mock_object`* is called with arguments that match the given matchers
325 *`matchers...`*. Requires a modifier clause to specify the method's behavior.
326 *Does not* set any expectations that the method will be called.
328 The parameter *`matchers...`* is a comma-separated list of
329 [matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
330 correspond to each argument of the method *`method_name`*. The `ON_CALL`
331 specification will apply only to calls of *`method_name`* whose arguments match
332 all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if
333 each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
334 See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
336 The following chainable clauses can be used to set the method's behavior, and
337 they must be used in the following order:
340 ON_CALL(mock_object, method_name(matchers...))
341 .With(multi_argument_matcher) // Can be used at most once
342 .WillByDefault(action); // Required
345 See details for each modifier clause below.
347 #### With {#ON_CALL.With}
349 `.With(`*`multi_argument_matcher`*`)`
351 Restricts the specification to only mock function calls whose arguments as a
352 whole match the multi-argument matcher *`multi_argument_matcher`*.
354 GoogleTest passes all of the arguments as one tuple into the matcher. The
355 parameter *`multi_argument_matcher`* must thus be a matcher of type
356 `Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
359 For example, the following code sets the default behavior when
360 `my_mock.SetPosition()` is called with any two arguments, the first argument
361 being less than the second:
366 using ::testing::Return;
368 ON_CALL(my_mock, SetPosition(_, _))
370 .WillByDefault(Return(true));
373 GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
374 matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
376 The `With` clause can be used at most once with each `ON_CALL` statement.
378 #### WillByDefault {#ON_CALL.WillByDefault}
380 `.WillByDefault(`*`action`*`)`
382 Specifies the default behavior of a matching mock function call.
384 The parameter *`action`* represents the
385 [action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
386 call will perform. See the [Actions Reference](actions.md) for a list of
389 For example, the following code specifies that by default, a call to
390 `my_mock.Greet()` will return `"hello"`:
393 using ::testing::Return;
395 ON_CALL(my_mock, Greet())
396 .WillByDefault(Return("hello"));
399 The action specified by `WillByDefault` is superseded by the actions specified
400 on a matching `EXPECT_CALL` statement, if any. See the
401 [`WillOnce`](#EXPECT_CALL.WillOnce) and
402 [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`.
404 The `WillByDefault` clause must be used exactly once with each `ON_CALL`
407 ## Classes {#classes}
409 GoogleTest defines the following classes for working with mocks.
411 ### DefaultValue {#DefaultValue}
413 `::testing::DefaultValue<T>`
415 Allows a user to specify the default value for a type `T` that is both copyable
416 and publicly destructible (i.e. anything that can be used as a function return
417 type). For mock functions with a return type of `T`, this default value is
418 returned from function calls that do not specify an action.
420 Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the
424 // Sets the default value to be returned. T must be copy constructible.
425 DefaultValue<T>::Set(value);
427 // Sets a factory. Will be invoked on demand. T must be move constructible.
429 DefaultValue<T>::SetFactory(&MakeT);
431 // Unsets the default value.
432 DefaultValue<T>::Clear();
435 ### NiceMock {#NiceMock}
437 `::testing::NiceMock<T>`
439 Represents a mock object that suppresses warnings on
440 [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
441 template parameter `T` is any mock class, except for another `NiceMock`,
442 `NaggyMock`, or `StrictMock`.
444 Usage of `NiceMock<T>` is analogous to usage of `T`. `NiceMock<T>` is a subclass
445 of `T`, so it can be used wherever an object of type `T` is accepted. In
446 addition, `NiceMock<T>` can be constructed with any arguments that a constructor
449 For example, the following code suppresses warnings on the mock `my_mock` of
450 type `MockClass` if a method other than `DoSomething()` is called:
453 using ::testing::NiceMock;
455 NiceMock<MockClass> my_mock("some", "args");
456 EXPECT_CALL(my_mock, DoSomething());
457 ... code that uses my_mock ...
460 `NiceMock<T>` only works for mock methods defined using the `MOCK_METHOD` macro
461 directly in the definition of class `T`. If a mock method is defined in a base
462 class of `T`, a warning might still be generated.
464 `NiceMock<T>` might not work correctly if the destructor of `T` is not virtual.
466 ### NaggyMock {#NaggyMock}
468 `::testing::NaggyMock<T>`
470 Represents a mock object that generates warnings on
471 [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
472 template parameter `T` is any mock class, except for another `NiceMock`,
473 `NaggyMock`, or `StrictMock`.
475 Usage of `NaggyMock<T>` is analogous to usage of `T`. `NaggyMock<T>` is a
476 subclass of `T`, so it can be used wherever an object of type `T` is accepted.
477 In addition, `NaggyMock<T>` can be constructed with any arguments that a
478 constructor of `T` accepts.
480 For example, the following code generates warnings on the mock `my_mock` of type
481 `MockClass` if a method other than `DoSomething()` is called:
484 using ::testing::NaggyMock;
486 NaggyMock<MockClass> my_mock("some", "args");
487 EXPECT_CALL(my_mock, DoSomething());
488 ... code that uses my_mock ...
491 Mock objects of type `T` by default behave the same way as `NaggyMock<T>`.
493 ### StrictMock {#StrictMock}
495 `::testing::StrictMock<T>`
497 Represents a mock object that generates test failures on
498 [uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
499 template parameter `T` is any mock class, except for another `NiceMock`,
500 `NaggyMock`, or `StrictMock`.
502 Usage of `StrictMock<T>` is analogous to usage of `T`. `StrictMock<T>` is a
503 subclass of `T`, so it can be used wherever an object of type `T` is accepted.
504 In addition, `StrictMock<T>` can be constructed with any arguments that a
505 constructor of `T` accepts.
507 For example, the following code generates a test failure on the mock `my_mock`
508 of type `MockClass` if a method other than `DoSomething()` is called:
511 using ::testing::StrictMock;
513 StrictMock<MockClass> my_mock("some", "args");
514 EXPECT_CALL(my_mock, DoSomething());
515 ... code that uses my_mock ...
518 `StrictMock<T>` only works for mock methods defined using the `MOCK_METHOD`
519 macro directly in the definition of class `T`. If a mock method is defined in a
520 base class of `T`, a failure might not be generated.
522 `StrictMock<T>` might not work correctly if the destructor of `T` is not
525 ### Sequence {#Sequence}
527 `::testing::Sequence`
529 Represents a chronological sequence of expectations. See the
530 [`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage.
532 ### InSequence {#InSequence}
534 `::testing::InSequence`
536 An object of this type causes all expectations encountered in its scope to be
537 put in an anonymous sequence.
539 This allows more convenient expression of multiple expectations in a single
543 using ::testing::InSequence;
547 // The following are expected to occur in the order declared.
555 The name of the `InSequence` object does not matter.
557 ### Expectation {#Expectation}
559 `::testing::Expectation`
561 Represents a mock function call expectation as created by
562 [`EXPECT_CALL`](#EXPECT_CALL):
565 using ::testing::Expectation;
566 Expectation my_expectation = EXPECT_CALL(...);
569 Useful for specifying sequences of expectations; see the
570 [`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.
572 ### ExpectationSet {#ExpectationSet}
574 `::testing::ExpectationSet`
576 Represents a set of mock function call expectations.
578 Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set:
581 using ::testing::ExpectationSet;
582 ExpectationSet my_expectations;
583 my_expectations += EXPECT_CALL(...);
586 Useful for specifying sequences of expectations; see the
587 [`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.