1# gMock Cheat Sheet 2 3<!-- GOOGLETEST_CM0019 DO NOT DELETE --> 4 5<!-- GOOGLETEST_CM0035 DO NOT DELETE --> 6 7<!-- GOOGLETEST_CM0033 DO NOT DELETE --> 8 9## Defining a Mock Class 10 11### Mocking a Normal Class {#MockClass} 12 13Given 14 15```cpp 16class Foo { 17 ... 18 virtual ~Foo(); 19 virtual int GetSize() const = 0; 20 virtual string Describe(const char* name) = 0; 21 virtual string Describe(int type) = 0; 22 virtual bool Process(Bar elem, int count) = 0; 23}; 24``` 25 26(note that `~Foo()` **must** be virtual) we can define its mock as 27 28```cpp 29#include "gmock/gmock.h" 30 31class MockFoo : public Foo { 32 ... 33 MOCK_METHOD(int, GetSize, (), (const, override)); 34 MOCK_METHOD(string, Describe, (const char* name), (override)); 35 MOCK_METHOD(string, Describe, (int type), (override)); 36 MOCK_METHOD(bool, Process, (Bar elem, int count), (override)); 37}; 38``` 39 40To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock, 41which warns on all uninteresting calls, or a "strict" mock, which treats them as 42failures: 43 44```cpp 45using ::testing::NiceMock; 46using ::testing::NaggyMock; 47using ::testing::StrictMock; 48 49NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. 50NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo. 51StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. 52``` 53 54**Note:** A mock object is currently naggy by default. We may make it nice by 55default in the future. 56 57### Mocking a Class Template {#MockTemplate} 58 59Class templates can be mocked just like any class. 60 61To mock 62 63```cpp 64template <typename Elem> 65class StackInterface { 66 ... 67 virtual ~StackInterface(); 68 virtual int GetSize() const = 0; 69 virtual void Push(const Elem& x) = 0; 70}; 71``` 72 73(note that all member functions that are mocked, including `~StackInterface()` 74**must** be virtual). 75 76```cpp 77template <typename Elem> 78class MockStack : public StackInterface<Elem> { 79 ... 80 MOCK_METHOD(int, GetSize, (), (const, override)); 81 MOCK_METHOD(void, Push, (const Elem& x), (override)); 82}; 83``` 84 85### Specifying Calling Conventions for Mock Functions 86 87If your mock function doesn't use the default calling convention, you can 88specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter. 89For example, 90 91```cpp 92 MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE))); 93 MOCK_METHOD(int, Bar, (double x, double y), 94 (const, Calltype(STDMETHODCALLTYPE))); 95``` 96 97where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. 98 99## Using Mocks in Tests {#UsingMocks} 100 101The typical work flow is: 102 1031. Import the gMock names you need to use. All gMock symbols are in the 104 `testing` namespace unless they are macros or otherwise noted. 1052. Create the mock objects. 1063. Optionally, set the default actions of the mock objects. 1074. Set your expectations on the mock objects (How will they be called? What 108 will they do?). 1095. Exercise code that uses the mock objects; if necessary, check the result 110 using googletest assertions. 1116. When a mock object is destructed, gMock automatically verifies that all 112 expectations on it have been satisfied. 113 114Here's an example: 115 116```cpp 117using ::testing::Return; // #1 118 119TEST(BarTest, DoesThis) { 120 MockFoo foo; // #2 121 122 ON_CALL(foo, GetSize()) // #3 123 .WillByDefault(Return(1)); 124 // ... other default actions ... 125 126 EXPECT_CALL(foo, Describe(5)) // #4 127 .Times(3) 128 .WillRepeatedly(Return("Category 5")); 129 // ... other expectations ... 130 131 EXPECT_EQ("good", MyProductionFunction(&foo)); // #5 132} // #6 133``` 134 135## Setting Default Actions {#OnCall} 136 137gMock has a **built-in default action** for any function that returns `void`, 138`bool`, a numeric value, or a pointer. In C++11, it will additionally returns 139the default-constructed value, if one exists for the given type. 140 141To customize the default action for functions with return type *`T`*: 142 143```cpp 144using ::testing::DefaultValue; 145 146// Sets the default value to be returned. T must be CopyConstructible. 147DefaultValue<T>::Set(value); 148// Sets a factory. Will be invoked on demand. T must be MoveConstructible. 149// T MakeT(); 150DefaultValue<T>::SetFactory(&MakeT); 151// ... use the mocks ... 152// Resets the default value. 153DefaultValue<T>::Clear(); 154``` 155 156Example usage: 157 158```cpp 159 // Sets the default action for return type std::unique_ptr<Buzz> to 160 // creating a new Buzz every time. 161 DefaultValue<std::unique_ptr<Buzz>>::SetFactory( 162 [] { return MakeUnique<Buzz>(AccessLevel::kInternal); }); 163 164 // When this fires, the default action of MakeBuzz() will run, which 165 // will return a new Buzz object. 166 EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); 167 168 auto buzz1 = mock_buzzer_.MakeBuzz("hello"); 169 auto buzz2 = mock_buzzer_.MakeBuzz("hello"); 170 EXPECT_NE(nullptr, buzz1); 171 EXPECT_NE(nullptr, buzz2); 172 EXPECT_NE(buzz1, buzz2); 173 174 // Resets the default action for return type std::unique_ptr<Buzz>, 175 // to avoid interfere with other tests. 176 DefaultValue<std::unique_ptr<Buzz>>::Clear(); 177``` 178 179To customize the default action for a particular method of a specific mock 180object, use `ON_CALL()`. `ON_CALL()` has a similar syntax to `EXPECT_CALL()`, 181but it is used for setting default behaviors (when you do not require that the 182mock method is called). See [here](cook_book.md#UseOnCall) for a more detailed 183discussion. 184 185```cpp 186ON_CALL(mock-object, method(matchers)) 187 .With(multi-argument-matcher) ? 188 .WillByDefault(action); 189``` 190 191## Setting Expectations {#ExpectCall} 192 193`EXPECT_CALL()` sets **expectations** on a mock method (How will it be called? 194What will it do?): 195 196```cpp 197EXPECT_CALL(mock-object, method (matchers)?) 198 .With(multi-argument-matcher) ? 199 .Times(cardinality) ? 200 .InSequence(sequences) * 201 .After(expectations) * 202 .WillOnce(action) * 203 .WillRepeatedly(action) ? 204 .RetiresOnSaturation(); ? 205``` 206 207For each item above, `?` means it can be used at most once, while `*` means it 208can be used any number of times. 209 210In order to pass, `EXPECT_CALL` must be used before the calls are actually made. 211 212The `(matchers)` is a comma-separated list of matchers that correspond to each 213of the arguments of `method`, and sets the expectation only for calls of 214`method` that matches all of the matchers. 215 216If `(matchers)` is omitted, the expectation is the same as if the matchers were 217set to anything matchers (for example, `(_, _, _, _)` for a four-arg method). 218 219If `Times()` is omitted, the cardinality is assumed to be: 220 221* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; 222* `Times(n)` when there are `n` `WillOnce()`s but no `WillRepeatedly()`, where 223 `n` >= 1; or 224* `Times(AtLeast(n))` when there are `n` `WillOnce()`s and a 225 `WillRepeatedly()`, where `n` >= 0. 226 227A method with no `EXPECT_CALL()` is free to be invoked *any number of times*, 228and the default action will be taken each time. 229 230## Matchers {#MatcherList} 231 232<!-- GOOGLETEST_CM0020 DO NOT DELETE --> 233 234A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or 235`EXPECT_CALL()`, or use it to validate a value directly using two macros: 236 237<!-- mdformat off(github rendering does not support multiline tables) --> 238| Macro | Description | 239| :----------------------------------- | :------------------------------------ | 240| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. | 241| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. | 242<!-- mdformat on --> 243 244**Note:** Although equality matching via `EXPECT_THAT(actual_value, 245expected_value)` is supported, prefer to make the comparison explicit via 246`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value, 247expected_value)`. 248 249Built-in matchers (where `argument` is the function argument, e.g. 250`actual_value` in the example above, or when used in the context of 251`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are 252divided into several categories: 253 254### Wildcard 255 256Matcher | Description 257:-------------------------- | :----------------------------------------------- 258`_` | `argument` can be any value of the correct type. 259`A<type>()` or `An<type>()` | `argument` can be any value of type `type`. 260 261### Generic Comparison 262 263<!-- mdformat off(no multiline tables) --> 264| Matcher | Description | 265| :--------------------- | :-------------------------------------------------- | 266| `Eq(value)` or `value` | `argument == value` | 267| `Ge(value)` | `argument >= value` | 268| `Gt(value)` | `argument > value` | 269| `Le(value)` | `argument <= value` | 270| `Lt(value)` | `argument < value` | 271| `Ne(value)` | `argument != value` | 272| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. | 273| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. | 274| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). | 275| `NotNull()` | `argument` is a non-null pointer (raw or smart). | 276| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)| 277| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. | 278| `Ref(variable)` | `argument` is a reference to `variable`. | 279| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. | 280<!-- mdformat on --> 281 282Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or 283destructed later. If the compiler complains that `value` doesn't have a public 284copy constructor, try wrap it in `std::ref()`, e.g. 285`Eq(std::ref(non_copyable_value))`. If you do that, make sure 286`non_copyable_value` is not changed afterwards, or the meaning of your matcher 287will be changed. 288 289`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types 290that can be explicitly converted to Boolean, but are not implicitly converted to 291Boolean. In other cases, you can use the basic 292[`EXPECT_TRUE` and `EXPECT_FALSE`](../../googletest/docs/primer#basic-assertions) 293assertions. 294 295### Floating-Point Matchers {#FpMatchers} 296 297<!-- mdformat off(no multiline tables) --> 298| Matcher | Description | 299| :------------------------------- | :--------------------------------- | 300| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. | 301| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. | 302| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. | 303| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. | 304| `IsNan()` | `argument` is any floating-point type with a NaN value. | 305<!-- mdformat on --> 306 307The above matchers use ULP-based comparison (the same as used in googletest). 308They automatically pick a reasonable error bound based on the absolute value of 309the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard, 310which requires comparing two NaNs for equality to return false. The 311`NanSensitive*` version instead treats two NaNs as equal, which is often what a 312user wants. 313 314<!-- mdformat off(no multiline tables) --> 315| Matcher | Description | 316| :------------------------------------------------ | :----------------------- | 317| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | 318| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. | 319| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. | 320| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. | 321<!-- mdformat on --> 322 323### String Matchers 324 325The `argument` can be either a C string or a C++ string object: 326 327<!-- mdformat off(no multiline tables) --> 328| Matcher | Description | 329| :---------------------- | :------------------------------------------------- | 330| `ContainsRegex(string)` | `argument` matches the given regular expression. | 331| `EndsWith(suffix)` | `argument` ends with string `suffix`. | 332| `HasSubstr(string)` | `argument` contains `string` as a sub-string. | 333| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. | 334| `StartsWith(prefix)` | `argument` starts with string `prefix`. | 335| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. | 336| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. | 337| `StrEq(string)` | `argument` is equal to `string`. | 338| `StrNe(string)` | `argument` is not equal to `string`. | 339<!-- mdformat on --> 340 341`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They 342use the regular expression syntax defined 343[here](../../googletest/docs/advanced.md#regular-expression-syntax). All of 344these matchers, except `ContainsRegex()` and `MatchesRegex()` work for wide 345strings as well. 346 347### Container Matchers 348 349Most STL-style containers support `==`, so you can use `Eq(expected_container)` 350or simply `expected_container` to match a container exactly. If you want to 351write the elements in-line, match them more flexibly, or get more informative 352messages, you can use: 353 354<!-- mdformat off(no multiline tables) --> 355| Matcher | Description | 356| :---------------------------------------- | :------------------------------- | 357| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. | 358| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. | 359| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. | 360| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. | 361| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. | 362| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | 363| `IsEmpty()` | `argument` is an empty container (`container.empty()`). | 364| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. | 365| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. | 366| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. | 367| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. | 368| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. | 369| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. | 370| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. | 371| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. | 372| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. | 373<!-- mdformat on --> 374 375**Notes:** 376 377* These matchers can also match: 378 1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`), 379 and 380 2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer, 381 int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)). 382* The array being matched may be multi-dimensional (i.e. its elements can be 383 arrays). 384* `m` in `Pointwise(m, ...)` should be a matcher for `::std::tuple<T, U>` 385 where `T` and `U` are the element type of the actual container and the 386 expected container, respectively. For example, to compare two `Foo` 387 containers where `Foo` doesn't support `operator==`, one might write: 388 389 ```cpp 390 using ::std::get; 391 MATCHER(FooEq, "") { 392 return std::get<0>(arg).Equals(std::get<1>(arg)); 393 } 394 ... 395 EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos)); 396 ``` 397 398### Member Matchers 399 400<!-- mdformat off(no multiline tables) --> 401| Matcher | Description | 402| :------------------------------ | :----------------------------------------- | 403| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | 404| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. | 405| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. | 406| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with `m...`. A compatible object is any that supports the `std::tuple_size<Obj>`+`get<I>(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. | 407| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. | 408<!-- mdformat on --> 409 410### Matching the Result of a Function, Functor, or Callback 411 412<!-- mdformat off(no multiline tables) --> 413| Matcher | Description | 414| :--------------- | :------------------------------------------------ | 415| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. | 416<!-- mdformat on --> 417 418### Pointer Matchers 419 420<!-- mdformat off(no multiline tables) --> 421| Matcher | Description | 422| :------------------------ | :---------------------------------------------- | 423| `Address(m)` | the result of `std::addressof(argument)` matches `m`. | 424| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. | 425| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. | 426| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. | 427<!-- mdformat on --> 428 429<!-- GOOGLETEST_CM0026 DO NOT DELETE --> 430 431<!-- GOOGLETEST_CM0027 DO NOT DELETE --> 432 433### Multi-argument Matchers {#MultiArgMatchers} 434 435Technically, all matchers match a *single* value. A "multi-argument" matcher is 436just one that matches a *tuple*. The following matchers can be used to match a 437tuple `(x, y)`: 438 439Matcher | Description 440:------ | :---------- 441`Eq()` | `x == y` 442`Ge()` | `x >= y` 443`Gt()` | `x > y` 444`Le()` | `x <= y` 445`Lt()` | `x < y` 446`Ne()` | `x != y` 447 448You can use the following selectors to pick a subset of the arguments (or 449reorder them) to participate in the matching: 450 451<!-- mdformat off(no multiline tables) --> 452| Matcher | Description | 453| :------------------------- | :---------------------------------------------- | 454| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. | 455| `Args<N1, N2, ..., Nk>(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. | 456<!-- mdformat on --> 457 458### Composite Matchers 459 460You can make a matcher from one or more other matchers: 461 462<!-- mdformat off(no multiline tables) --> 463| Matcher | Description | 464| :------------------------------- | :-------------------------------------- | 465| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. | 466| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | 467| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. | 468| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. | 469| `Not(m)` | `argument` doesn't match matcher `m`. | 470<!-- mdformat on --> 471 472<!-- GOOGLETEST_CM0028 DO NOT DELETE --> 473 474### Adapters for Matchers 475 476<!-- mdformat off(no multiline tables) --> 477| Matcher | Description | 478| :---------------------- | :------------------------------------ | 479| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. | 480| `SafeMatcherCast<T>(m)` | [safely casts](cook_book.md#casting-matchers) matcher `m` to type `Matcher<T>`. | 481| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. | 482<!-- mdformat on --> 483 484`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`, 485which must be a permanent callback. 486 487### Using Matchers as Predicates {#MatchersAsPredicatesCheat} 488 489<!-- mdformat off(no multiline tables) --> 490| Matcher | Description | 491| :---------------------------- | :------------------------------------------ | 492| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. | 493| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. | 494| `Value(value, m)` | evaluates to `true` if `value` matches `m`. | 495<!-- mdformat on --> 496 497### Defining Matchers 498 499<!-- mdformat off(no multiline tables) --> 500| Matcher | Description | 501| :----------------------------------- | :------------------------------------ | 502| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. | 503| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. | 504| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. | 505<!-- mdformat on --> 506 507**Notes:** 508 5091. The `MATCHER*` macros cannot be used inside a function or class. 5102. The matcher body must be *purely functional* (i.e. it cannot have any side 511 effect, and the result must not depend on anything other than the value 512 being matched and the matcher parameters). 5133. You can use `PrintToString(x)` to convert a value `x` of any type to a 514 string. 515 516## Actions {#ActionList} 517 518**Actions** specify what a mock function should do when invoked. 519 520### Returning a Value 521 522<!-- mdformat off(no multiline tables) --> 523| | | 524| :-------------------------------- | :-------------------------------------------- | 525| `Return()` | Return from a `void` mock function. | 526| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed. | 527| `ReturnArg<N>()` | Return the `N`-th (0-based) argument. | 528| `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | 529| `ReturnNull()` | Return a null pointer. | 530| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | 531| `ReturnRef(variable)` | Return a reference to `variable`. | 532| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | 533| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. | 534<!-- mdformat on --> 535 536### Side Effects 537 538<!-- mdformat off(no multiline tables) --> 539| | | 540| :--------------------------------- | :-------------------------------------- | 541| `Assign(&variable, value)` | Assign `value` to variable. | 542| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | 543| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | 544| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | 545| `SetArgReferee<N>(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. | 546| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. | 547| `SetArgumentPointee<N>(value)` | Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0. | 548| `SetArrayArgument<N>(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. | 549| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. | 550| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. | 551<!-- mdformat on --> 552 553### Using a Function, Functor, or Lambda as an Action 554 555In the following, by "callable" we mean a free function, `std::function`, 556functor, or lambda. 557 558<!-- mdformat off(no multiline tables) --> 559| | | 560| :---------------------------------- | :------------------------------------- | 561| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. | 562| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | 563| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | 564| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | 565| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. | 566| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. | 567<!-- mdformat on --> 568 569The return value of the invoked function is used as the return value of the 570action. 571 572When defining a callable to be used with `Invoke*()`, you can declare any unused 573parameters as `Unused`: 574 575```cpp 576using ::testing::Invoke; 577double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } 578... 579EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); 580``` 581 582`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of 583`callback`, which must be permanent. The type of `callback` must be a base 584callback type instead of a derived one, e.g. 585 586```cpp 587 BlockingClosure* done = new BlockingClosure; 588 ... Invoke(done) ...; // This won't compile! 589 590 Closure* done2 = new BlockingClosure; 591 ... Invoke(done2) ...; // This works. 592``` 593 594In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, 595wrap it inside `std::ref()`. For example, 596 597```cpp 598using ::testing::InvokeArgument; 599... 600InvokeArgument<2>(5, string("Hi"), std::ref(foo)) 601``` 602 603calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by 604value, and `foo` by reference. 605 606### Default Action 607 608<!-- mdformat off(no multiline tables) --> 609| Matcher | Description | 610| :------------ | :----------------------------------------------------- | 611| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | 612<!-- mdformat on --> 613 614**Note:** due to technical reasons, `DoDefault()` cannot be used inside a 615composite action - trying to do so will result in a run-time error. 616 617<!-- GOOGLETEST_CM0032 DO NOT DELETE --> 618 619### Composite Actions 620 621<!-- mdformat off(no multiline tables) --> 622| | | 623| :----------------------------- | :------------------------------------------ | 624| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. | 625| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | 626| `WithArg<N>(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | 627| `WithArgs<N1, N2, ..., Nk>(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | 628| `WithoutArgs(a)` | Perform action `a` without any arguments. | 629<!-- mdformat on --> 630 631### Defining Actions 632 633<!-- mdformat off(no multiline tables) --> 634| | | 635| :--------------------------------- | :-------------------------------------- | 636| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | 637| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. | 638| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | 639<!-- mdformat on --> 640 641The `ACTION*` macros cannot be used inside a function or class. 642 643## Cardinalities {#CardinalityList} 644 645These are used in `Times()` to specify how many times a mock function will be 646called: 647 648<!-- mdformat off(no multiline tables) --> 649| | | 650| :---------------- | :----------------------------------------------------- | 651| `AnyNumber()` | The function can be called any number of times. | 652| `AtLeast(n)` | The call is expected at least `n` times. | 653| `AtMost(n)` | The call is expected at most `n` times. | 654| `Between(m, n)` | The call is expected between `m` and `n` (inclusive) times. | 655| `Exactly(n) or n` | The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0. | 656<!-- mdformat on --> 657 658## Expectation Order 659 660By default, the expectations can be matched in *any* order. If some or all 661expectations must be matched in a given order, there are two ways to specify it. 662They can be used either independently or together. 663 664### The After Clause {#AfterClause} 665 666```cpp 667using ::testing::Expectation; 668... 669Expectation init_x = EXPECT_CALL(foo, InitX()); 670Expectation init_y = EXPECT_CALL(foo, InitY()); 671EXPECT_CALL(foo, Bar()) 672 .After(init_x, init_y); 673``` 674 675says that `Bar()` can be called only after both `InitX()` and `InitY()` have 676been called. 677 678If you don't know how many pre-requisites an expectation has when you write it, 679you can use an `ExpectationSet` to collect them: 680 681```cpp 682using ::testing::ExpectationSet; 683... 684ExpectationSet all_inits; 685for (int i = 0; i < element_count; i++) { 686 all_inits += EXPECT_CALL(foo, InitElement(i)); 687} 688EXPECT_CALL(foo, Bar()) 689 .After(all_inits); 690``` 691 692says that `Bar()` can be called only after all elements have been initialized 693(but we don't care about which elements get initialized before the others). 694 695Modifying an `ExpectationSet` after using it in an `.After()` doesn't affect the 696meaning of the `.After()`. 697 698### Sequences {#UsingSequences} 699 700When you have a long chain of sequential expectations, it's easier to specify 701the order using **sequences**, which don't require you to given each expectation 702in the chain a different name. *All expected calls* in the same sequence must 703occur in the order they are specified. 704 705```cpp 706using ::testing::Return; 707using ::testing::Sequence; 708Sequence s1, s2; 709... 710EXPECT_CALL(foo, Reset()) 711 .InSequence(s1, s2) 712 .WillOnce(Return(true)); 713EXPECT_CALL(foo, GetSize()) 714 .InSequence(s1) 715 .WillOnce(Return(1)); 716EXPECT_CALL(foo, Describe(A<const char*>())) 717 .InSequence(s2) 718 .WillOnce(Return("dummy")); 719``` 720 721says that `Reset()` must be called before *both* `GetSize()` *and* `Describe()`, 722and the latter two can occur in any order. 723 724To put many expectations in a sequence conveniently: 725 726```cpp 727using ::testing::InSequence; 728{ 729 InSequence seq; 730 731 EXPECT_CALL(...)...; 732 EXPECT_CALL(...)...; 733 ... 734 EXPECT_CALL(...)...; 735} 736``` 737 738says that all expected calls in the scope of `seq` must occur in strict order. 739The name `seq` is irrelevant. 740 741## Verifying and Resetting a Mock 742 743gMock will verify the expectations on a mock object when it is destructed, or 744you can do it earlier: 745 746```cpp 747using ::testing::Mock; 748... 749// Verifies and removes the expectations on mock_obj; 750// returns true if and only if successful. 751Mock::VerifyAndClearExpectations(&mock_obj); 752... 753// Verifies and removes the expectations on mock_obj; 754// also removes the default actions set by ON_CALL(); 755// returns true if and only if successful. 756Mock::VerifyAndClear(&mock_obj); 757``` 758 759You can also tell gMock that a mock object can be leaked and doesn't need to be 760verified: 761 762```cpp 763Mock::AllowLeak(&mock_obj); 764``` 765 766## Mock Classes 767 768gMock defines a convenient mock class template 769 770```cpp 771class MockFunction<R(A1, ..., An)> { 772 public: 773 MOCK_METHOD(R, Call, (A1, ..., An)); 774}; 775``` 776 777See this [recipe](cook_book.md#using-check-points) for one application of it. 778 779## Flags 780 781<!-- mdformat off(no multiline tables) --> 782| Flag | Description | 783| :----------------------------- | :---------------------------------------- | 784| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | 785| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | 786<!-- mdformat on --> 787