1# gMock Cheat Sheet 2 3## Defining a Mock Class 4 5### Mocking a Normal Class {#MockClass} 6 7Given 8 9```cpp 10class Foo { 11 ... 12 virtual ~Foo(); 13 virtual int GetSize() const = 0; 14 virtual string Describe(const char* name) = 0; 15 virtual string Describe(int type) = 0; 16 virtual bool Process(Bar elem, int count) = 0; 17}; 18``` 19 20(note that `~Foo()` **must** be virtual) we can define its mock as 21 22```cpp 23#include "gmock/gmock.h" 24 25class MockFoo : public Foo { 26 ... 27 MOCK_METHOD(int, GetSize, (), (const, override)); 28 MOCK_METHOD(string, Describe, (const char* name), (override)); 29 MOCK_METHOD(string, Describe, (int type), (override)); 30 MOCK_METHOD(bool, Process, (Bar elem, int count), (override)); 31}; 32``` 33 34To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock, 35which warns on all uninteresting calls, or a "strict" mock, which treats them as 36failures: 37 38```cpp 39using ::testing::NiceMock; 40using ::testing::NaggyMock; 41using ::testing::StrictMock; 42 43NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo. 44NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo. 45StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo. 46``` 47 48{: .callout .note} 49**Note:** A mock object is currently naggy by default. We may make it nice by 50default in the future. 51 52### Mocking a Class Template {#MockTemplate} 53 54Class templates can be mocked just like any class. 55 56To mock 57 58```cpp 59template <typename Elem> 60class StackInterface { 61 ... 62 virtual ~StackInterface(); 63 virtual int GetSize() const = 0; 64 virtual void Push(const Elem& x) = 0; 65}; 66``` 67 68(note that all member functions that are mocked, including `~StackInterface()` 69**must** be virtual). 70 71```cpp 72template <typename Elem> 73class MockStack : public StackInterface<Elem> { 74 ... 75 MOCK_METHOD(int, GetSize, (), (const, override)); 76 MOCK_METHOD(void, Push, (const Elem& x), (override)); 77}; 78``` 79 80### Specifying Calling Conventions for Mock Functions 81 82If your mock function doesn't use the default calling convention, you can 83specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter. 84For example, 85 86```cpp 87 MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE))); 88 MOCK_METHOD(int, Bar, (double x, double y), 89 (const, Calltype(STDMETHODCALLTYPE))); 90``` 91 92where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows. 93 94## Using Mocks in Tests {#UsingMocks} 95 96The typical work flow is: 97 981. Import the gMock names you need to use. All gMock symbols are in the 99 `testing` namespace unless they are macros or otherwise noted. 1002. Create the mock objects. 1013. Optionally, set the default actions of the mock objects. 1024. Set your expectations on the mock objects (How will they be called? What 103 will they do?). 1045. Exercise code that uses the mock objects; if necessary, check the result 105 using googletest assertions. 1066. When a mock object is destructed, gMock automatically verifies that all 107 expectations on it have been satisfied. 108 109Here's an example: 110 111```cpp 112using ::testing::Return; // #1 113 114TEST(BarTest, DoesThis) { 115 MockFoo foo; // #2 116 117 ON_CALL(foo, GetSize()) // #3 118 .WillByDefault(Return(1)); 119 // ... other default actions ... 120 121 EXPECT_CALL(foo, Describe(5)) // #4 122 .Times(3) 123 .WillRepeatedly(Return("Category 5")); 124 // ... other expectations ... 125 126 EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5 127} // #6 128``` 129 130## Setting Default Actions {#OnCall} 131 132gMock has a **built-in default action** for any function that returns `void`, 133`bool`, a numeric value, or a pointer. In C++11, it will additionally returns 134the default-constructed value, if one exists for the given type. 135 136To customize the default action for functions with return type *`T`*: 137 138```cpp 139using ::testing::DefaultValue; 140 141// Sets the default value to be returned. T must be CopyConstructible. 142DefaultValue<T>::Set(value); 143// Sets a factory. Will be invoked on demand. T must be MoveConstructible. 144// T MakeT(); 145DefaultValue<T>::SetFactory(&MakeT); 146// ... use the mocks ... 147// Resets the default value. 148DefaultValue<T>::Clear(); 149``` 150 151Example usage: 152 153```cpp 154 // Sets the default action for return type std::unique_ptr<Buzz> to 155 // creating a new Buzz every time. 156 DefaultValue<std::unique_ptr<Buzz>>::SetFactory( 157 [] { return MakeUnique<Buzz>(AccessLevel::kInternal); }); 158 159 // When this fires, the default action of MakeBuzz() will run, which 160 // will return a new Buzz object. 161 EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber()); 162 163 auto buzz1 = mock_buzzer_.MakeBuzz("hello"); 164 auto buzz2 = mock_buzzer_.MakeBuzz("hello"); 165 EXPECT_NE(buzz1, nullptr); 166 EXPECT_NE(buzz2, nullptr); 167 EXPECT_NE(buzz1, buzz2); 168 169 // Resets the default action for return type std::unique_ptr<Buzz>, 170 // to avoid interfere with other tests. 171 DefaultValue<std::unique_ptr<Buzz>>::Clear(); 172``` 173 174To customize the default action for a particular method of a specific mock 175object, use `ON_CALL()`. `ON_CALL()` has a similar syntax to `EXPECT_CALL()`, 176but it is used for setting default behaviors (when you do not require that the 177mock method is called). See [here](gmock_cook_book.md#UseOnCall) for a more 178detailed discussion. 179 180```cpp 181ON_CALL(mock-object, method(matchers)) 182 .With(multi-argument-matcher) ? 183 .WillByDefault(action); 184``` 185 186## Setting Expectations {#ExpectCall} 187 188`EXPECT_CALL()` sets **expectations** on a mock method (How will it be called? 189What will it do?): 190 191```cpp 192EXPECT_CALL(mock-object, method (matchers)?) 193 .With(multi-argument-matcher) ? 194 .Times(cardinality) ? 195 .InSequence(sequences) * 196 .After(expectations) * 197 .WillOnce(action) * 198 .WillRepeatedly(action) ? 199 .RetiresOnSaturation(); ? 200``` 201 202For each item above, `?` means it can be used at most once, while `*` means it 203can be used any number of times. 204 205In order to pass, `EXPECT_CALL` must be used before the calls are actually made. 206 207The `(matchers)` is a comma-separated list of matchers that correspond to each 208of the arguments of `method`, and sets the expectation only for calls of 209`method` that matches all of the matchers. 210 211If `(matchers)` is omitted, the expectation is the same as if the matchers were 212set to anything matchers (for example, `(_, _, _, _)` for a four-arg method). 213 214If `Times()` is omitted, the cardinality is assumed to be: 215 216* `Times(1)` when there is neither `WillOnce()` nor `WillRepeatedly()`; 217* `Times(n)` when there are `n` `WillOnce()`s but no `WillRepeatedly()`, where 218 `n` >= 1; or 219* `Times(AtLeast(n))` when there are `n` `WillOnce()`s and a 220 `WillRepeatedly()`, where `n` >= 0. 221 222A method with no `EXPECT_CALL()` is free to be invoked *any number of times*, 223and the default action will be taken each time. 224 225## Matchers {#MatcherList} 226 227See the [Matchers Reference](reference/matchers.md). 228 229## Actions {#ActionList} 230 231**Actions** specify what a mock function should do when invoked. 232 233### Returning a Value 234 235| | | 236| :-------------------------------- | :-------------------------------------------- | 237| `Return()` | Return from a `void` mock function. | 238| `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. | 239| `ReturnArg<N>()` | Return the `N`-th (0-based) argument. | 240| `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. | 241| `ReturnNull()` | Return a null pointer. | 242| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. | 243| `ReturnRef(variable)` | Return a reference to `variable`. | 244| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. | 245| `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. | 246 247### Side Effects 248 249| | | 250| :--------------------------------- | :-------------------------------------- | 251| `Assign(&variable, value)` | Assign `value` to variable. | 252| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. | 253| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. | 254| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. | 255| `SetArgReferee<N>(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. | 256| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. | 257| `SetArgumentPointee<N>(value)` | Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0. | 258| `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. | 259| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. | 260| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. | 261 262### Using a Function, Functor, or Lambda as an Action 263 264In the following, by "callable" we mean a free function, `std::function`, 265functor, or lambda. 266 267| | | 268| :---------------------------------- | :------------------------------------- | 269| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. | 270| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. | 271| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. | 272| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. | 273| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. | 274| `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. | 275 276The return value of the invoked function is used as the return value of the 277action. 278 279When defining a callable to be used with `Invoke*()`, you can declare any unused 280parameters as `Unused`: 281 282```cpp 283using ::testing::Invoke; 284double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); } 285... 286EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance)); 287``` 288 289`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of 290`callback`, which must be permanent. The type of `callback` must be a base 291callback type instead of a derived one, e.g. 292 293```cpp 294 BlockingClosure* done = new BlockingClosure; 295 ... Invoke(done) ...; // This won't compile! 296 297 Closure* done2 = new BlockingClosure; 298 ... Invoke(done2) ...; // This works. 299``` 300 301In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference, 302wrap it inside `std::ref()`. For example, 303 304```cpp 305using ::testing::InvokeArgument; 306... 307InvokeArgument<2>(5, string("Hi"), std::ref(foo)) 308``` 309 310calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by 311value, and `foo` by reference. 312 313### Default Action 314 315| Matcher | Description | 316| :------------ | :----------------------------------------------------- | 317| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). | 318 319{: .callout .note} 320**Note:** due to technical reasons, `DoDefault()` cannot be used inside a 321composite action - trying to do so will result in a run-time error. 322 323### Composite Actions 324 325| | | 326| :----------------------------- | :------------------------------------------ | 327| `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. | 328| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. | 329| `WithArg<N>(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. | 330| `WithArgs<N1, N2, ..., Nk>(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. | 331| `WithoutArgs(a)` | Perform action `a` without any arguments. | 332 333### Defining Actions 334 335| | | 336| :--------------------------------- | :-------------------------------------- | 337| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. | 338| `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`. | 339| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. | 340 341The `ACTION*` macros cannot be used inside a function or class. 342 343## Cardinalities {#CardinalityList} 344 345These are used in `Times()` to specify how many times a mock function will be 346called: 347 348| | | 349| :---------------- | :----------------------------------------------------- | 350| `AnyNumber()` | The function can be called any number of times. | 351| `AtLeast(n)` | The call is expected at least `n` times. | 352| `AtMost(n)` | The call is expected at most `n` times. | 353| `Between(m, n)` | The call is expected between `m` and `n` (inclusive) times. | 354| `Exactly(n) or n` | The call is expected exactly `n` times. In particular, the call should never happen when `n` is 0. | 355 356## Expectation Order 357 358By default, the expectations can be matched in *any* order. If some or all 359expectations must be matched in a given order, there are two ways to specify it. 360They can be used either independently or together. 361 362### The After Clause {#AfterClause} 363 364```cpp 365using ::testing::Expectation; 366... 367Expectation init_x = EXPECT_CALL(foo, InitX()); 368Expectation init_y = EXPECT_CALL(foo, InitY()); 369EXPECT_CALL(foo, Bar()) 370 .After(init_x, init_y); 371``` 372 373says that `Bar()` can be called only after both `InitX()` and `InitY()` have 374been called. 375 376If you don't know how many pre-requisites an expectation has when you write it, 377you can use an `ExpectationSet` to collect them: 378 379```cpp 380using ::testing::ExpectationSet; 381... 382ExpectationSet all_inits; 383for (int i = 0; i < element_count; i++) { 384 all_inits += EXPECT_CALL(foo, InitElement(i)); 385} 386EXPECT_CALL(foo, Bar()) 387 .After(all_inits); 388``` 389 390says that `Bar()` can be called only after all elements have been initialized 391(but we don't care about which elements get initialized before the others). 392 393Modifying an `ExpectationSet` after using it in an `.After()` doesn't affect the 394meaning of the `.After()`. 395 396### Sequences {#UsingSequences} 397 398When you have a long chain of sequential expectations, it's easier to specify 399the order using **sequences**, which don't require you to give each expectation 400in the chain a different name. *All expected calls* in the same sequence must 401occur in the order they are specified. 402 403```cpp 404using ::testing::Return; 405using ::testing::Sequence; 406Sequence s1, s2; 407... 408EXPECT_CALL(foo, Reset()) 409 .InSequence(s1, s2) 410 .WillOnce(Return(true)); 411EXPECT_CALL(foo, GetSize()) 412 .InSequence(s1) 413 .WillOnce(Return(1)); 414EXPECT_CALL(foo, Describe(A<const char*>())) 415 .InSequence(s2) 416 .WillOnce(Return("dummy")); 417``` 418 419says that `Reset()` must be called before *both* `GetSize()` *and* `Describe()`, 420and the latter two can occur in any order. 421 422To put many expectations in a sequence conveniently: 423 424```cpp 425using ::testing::InSequence; 426{ 427 InSequence seq; 428 429 EXPECT_CALL(...)...; 430 EXPECT_CALL(...)...; 431 ... 432 EXPECT_CALL(...)...; 433} 434``` 435 436says that all expected calls in the scope of `seq` must occur in strict order. 437The name `seq` is irrelevant. 438 439## Verifying and Resetting a Mock 440 441gMock will verify the expectations on a mock object when it is destructed, or 442you can do it earlier: 443 444```cpp 445using ::testing::Mock; 446... 447// Verifies and removes the expectations on mock_obj; 448// returns true if and only if successful. 449Mock::VerifyAndClearExpectations(&mock_obj); 450... 451// Verifies and removes the expectations on mock_obj; 452// also removes the default actions set by ON_CALL(); 453// returns true if and only if successful. 454Mock::VerifyAndClear(&mock_obj); 455``` 456 457You can also tell gMock that a mock object can be leaked and doesn't need to be 458verified: 459 460```cpp 461Mock::AllowLeak(&mock_obj); 462``` 463 464## Mock Classes 465 466gMock defines a convenient mock class template 467 468```cpp 469class MockFunction<R(A1, ..., An)> { 470 public: 471 MOCK_METHOD(R, Call, (A1, ..., An)); 472}; 473``` 474 475See this [recipe](gmock_cook_book.md#using-check-points) for one application of 476it. 477 478## Flags 479 480| Flag | Description | 481| :----------------------------- | :---------------------------------------- | 482| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. | 483| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. | 484