1*481dde66SAndroid Build Coastguard Worker# gMock for Dummies 2*481dde66SAndroid Build Coastguard Worker 3*481dde66SAndroid Build Coastguard Worker## What Is gMock? 4*481dde66SAndroid Build Coastguard Worker 5*481dde66SAndroid Build Coastguard WorkerWhen you write a prototype or test, often it's not feasible or wise to rely on 6*481dde66SAndroid Build Coastguard Workerreal objects entirely. A **mock object** implements the same interface as a real 7*481dde66SAndroid Build Coastguard Workerobject (so it can be used as one), but lets you specify at run time how it will 8*481dde66SAndroid Build Coastguard Workerbe used and what it should do (which methods will be called? in which order? how 9*481dde66SAndroid Build Coastguard Workermany times? with what arguments? what will they return? etc). 10*481dde66SAndroid Build Coastguard Worker 11*481dde66SAndroid Build Coastguard WorkerIt is easy to confuse the term *fake objects* with mock objects. Fakes and mocks 12*481dde66SAndroid Build Coastguard Workeractually mean very different things in the Test-Driven Development (TDD) 13*481dde66SAndroid Build Coastguard Workercommunity: 14*481dde66SAndroid Build Coastguard Worker 15*481dde66SAndroid Build Coastguard Worker* **Fake** objects have working implementations, but usually take some 16*481dde66SAndroid Build Coastguard Worker shortcut (perhaps to make the operations less expensive), which makes them 17*481dde66SAndroid Build Coastguard Worker not suitable for production. An in-memory file system would be an example of 18*481dde66SAndroid Build Coastguard Worker a fake. 19*481dde66SAndroid Build Coastguard Worker* **Mocks** are objects pre-programmed with *expectations*, which form a 20*481dde66SAndroid Build Coastguard Worker specification of the calls they are expected to receive. 21*481dde66SAndroid Build Coastguard Worker 22*481dde66SAndroid Build Coastguard WorkerIf all this seems too abstract for you, don't worry - the most important thing 23*481dde66SAndroid Build Coastguard Workerto remember is that a mock allows you to check the *interaction* between itself 24*481dde66SAndroid Build Coastguard Workerand code that uses it. The difference between fakes and mocks shall become much 25*481dde66SAndroid Build Coastguard Workerclearer once you start to use mocks. 26*481dde66SAndroid Build Coastguard Worker 27*481dde66SAndroid Build Coastguard Worker**gMock** is a library (sometimes we also call it a "framework" to make it sound 28*481dde66SAndroid Build Coastguard Workercool) for creating mock classes and using them. It does to C++ what 29*481dde66SAndroid Build Coastguard WorkerjMock/EasyMock does to Java (well, more or less). 30*481dde66SAndroid Build Coastguard Worker 31*481dde66SAndroid Build Coastguard WorkerWhen using gMock, 32*481dde66SAndroid Build Coastguard Worker 33*481dde66SAndroid Build Coastguard Worker1. first, you use some simple macros to describe the interface you want to 34*481dde66SAndroid Build Coastguard Worker mock, and they will expand to the implementation of your mock class; 35*481dde66SAndroid Build Coastguard Worker2. next, you create some mock objects and specify its expectations and behavior 36*481dde66SAndroid Build Coastguard Worker using an intuitive syntax; 37*481dde66SAndroid Build Coastguard Worker3. then you exercise code that uses the mock objects. gMock will catch any 38*481dde66SAndroid Build Coastguard Worker violation to the expectations as soon as it arises. 39*481dde66SAndroid Build Coastguard Worker 40*481dde66SAndroid Build Coastguard Worker## Why gMock? 41*481dde66SAndroid Build Coastguard Worker 42*481dde66SAndroid Build Coastguard WorkerWhile mock objects help you remove unnecessary dependencies in tests and make 43*481dde66SAndroid Build Coastguard Workerthem fast and reliable, using mocks manually in C++ is *hard*: 44*481dde66SAndroid Build Coastguard Worker 45*481dde66SAndroid Build Coastguard Worker* Someone has to implement the mocks. The job is usually tedious and 46*481dde66SAndroid Build Coastguard Worker error-prone. No wonder people go great distance to avoid it. 47*481dde66SAndroid Build Coastguard Worker* The quality of those manually written mocks is a bit, uh, unpredictable. You 48*481dde66SAndroid Build Coastguard Worker may see some really polished ones, but you may also see some that were 49*481dde66SAndroid Build Coastguard Worker hacked up in a hurry and have all sorts of ad hoc restrictions. 50*481dde66SAndroid Build Coastguard Worker* The knowledge you gained from using one mock doesn't transfer to the next 51*481dde66SAndroid Build Coastguard Worker one. 52*481dde66SAndroid Build Coastguard Worker 53*481dde66SAndroid Build Coastguard WorkerIn contrast, Java and Python programmers have some fine mock frameworks (jMock, 54*481dde66SAndroid Build Coastguard WorkerEasyMock, etc), which automate the creation of mocks. As a result, mocking is a 55*481dde66SAndroid Build Coastguard Workerproven effective technique and widely adopted practice in those communities. 56*481dde66SAndroid Build Coastguard WorkerHaving the right tool absolutely makes the difference. 57*481dde66SAndroid Build Coastguard Worker 58*481dde66SAndroid Build Coastguard WorkergMock was built to help C++ programmers. It was inspired by jMock and EasyMock, 59*481dde66SAndroid Build Coastguard Workerbut designed with C++'s specifics in mind. It is your friend if any of the 60*481dde66SAndroid Build Coastguard Workerfollowing problems is bothering you: 61*481dde66SAndroid Build Coastguard Worker 62*481dde66SAndroid Build Coastguard Worker* You are stuck with a sub-optimal design and wish you had done more 63*481dde66SAndroid Build Coastguard Worker prototyping before it was too late, but prototyping in C++ is by no means 64*481dde66SAndroid Build Coastguard Worker "rapid". 65*481dde66SAndroid Build Coastguard Worker* Your tests are slow as they depend on too many libraries or use expensive 66*481dde66SAndroid Build Coastguard Worker resources (e.g. a database). 67*481dde66SAndroid Build Coastguard Worker* Your tests are brittle as some resources they use are unreliable (e.g. the 68*481dde66SAndroid Build Coastguard Worker network). 69*481dde66SAndroid Build Coastguard Worker* You want to test how your code handles a failure (e.g. a file checksum 70*481dde66SAndroid Build Coastguard Worker error), but it's not easy to cause one. 71*481dde66SAndroid Build Coastguard Worker* You need to make sure that your module interacts with other modules in the 72*481dde66SAndroid Build Coastguard Worker right way, but it's hard to observe the interaction; therefore you resort to 73*481dde66SAndroid Build Coastguard Worker observing the side effects at the end of the action, but it's awkward at 74*481dde66SAndroid Build Coastguard Worker best. 75*481dde66SAndroid Build Coastguard Worker* You want to "mock out" your dependencies, except that they don't have mock 76*481dde66SAndroid Build Coastguard Worker implementations yet; and, frankly, you aren't thrilled by some of those 77*481dde66SAndroid Build Coastguard Worker hand-written mocks. 78*481dde66SAndroid Build Coastguard Worker 79*481dde66SAndroid Build Coastguard WorkerWe encourage you to use gMock as 80*481dde66SAndroid Build Coastguard Worker 81*481dde66SAndroid Build Coastguard Worker* a *design* tool, for it lets you experiment with your interface design early 82*481dde66SAndroid Build Coastguard Worker and often. More iterations lead to better designs! 83*481dde66SAndroid Build Coastguard Worker* a *testing* tool to cut your tests' outbound dependencies and probe the 84*481dde66SAndroid Build Coastguard Worker interaction between your module and its collaborators. 85*481dde66SAndroid Build Coastguard Worker 86*481dde66SAndroid Build Coastguard Worker## Getting Started 87*481dde66SAndroid Build Coastguard Worker 88*481dde66SAndroid Build Coastguard WorkergMock is bundled with googletest. 89*481dde66SAndroid Build Coastguard Worker 90*481dde66SAndroid Build Coastguard Worker## A Case for Mock Turtles 91*481dde66SAndroid Build Coastguard Worker 92*481dde66SAndroid Build Coastguard WorkerLet's look at an example. Suppose you are developing a graphics program that 93*481dde66SAndroid Build Coastguard Workerrelies on a [LOGO](https://en.wikipedia.org/wiki/Logo_programming_language)-like 94*481dde66SAndroid Build Coastguard WorkerAPI for drawing. How would you test that it does the right thing? Well, you can 95*481dde66SAndroid Build Coastguard Workerrun it and compare the screen with a golden screen snapshot, but let's admit it: 96*481dde66SAndroid Build Coastguard Workertests like this are expensive to run and fragile (What if you just upgraded to a 97*481dde66SAndroid Build Coastguard Workershiny new graphics card that has better anti-aliasing? Suddenly you have to 98*481dde66SAndroid Build Coastguard Workerupdate all your golden images.). It would be too painful if all your tests are 99*481dde66SAndroid Build Coastguard Workerlike this. Fortunately, you learned about 100*481dde66SAndroid Build Coastguard Worker[Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and know the right thing 101*481dde66SAndroid Build Coastguard Workerto do: instead of having your application talk to the system API directly, wrap 102*481dde66SAndroid Build Coastguard Workerthe API in an interface (say, `Turtle`) and code to that interface: 103*481dde66SAndroid Build Coastguard Worker 104*481dde66SAndroid Build Coastguard Worker```cpp 105*481dde66SAndroid Build Coastguard Workerclass Turtle { 106*481dde66SAndroid Build Coastguard Worker ... 107*481dde66SAndroid Build Coastguard Worker virtual ~Turtle() {} 108*481dde66SAndroid Build Coastguard Worker virtual void PenUp() = 0; 109*481dde66SAndroid Build Coastguard Worker virtual void PenDown() = 0; 110*481dde66SAndroid Build Coastguard Worker virtual void Forward(int distance) = 0; 111*481dde66SAndroid Build Coastguard Worker virtual void Turn(int degrees) = 0; 112*481dde66SAndroid Build Coastguard Worker virtual void GoTo(int x, int y) = 0; 113*481dde66SAndroid Build Coastguard Worker virtual int GetX() const = 0; 114*481dde66SAndroid Build Coastguard Worker virtual int GetY() const = 0; 115*481dde66SAndroid Build Coastguard Worker}; 116*481dde66SAndroid Build Coastguard Worker``` 117*481dde66SAndroid Build Coastguard Worker 118*481dde66SAndroid Build Coastguard Worker(Note that the destructor of `Turtle` **must** be virtual, as is the case for 119*481dde66SAndroid Build Coastguard Worker**all** classes you intend to inherit from - otherwise the destructor of the 120*481dde66SAndroid Build Coastguard Workerderived class will not be called when you delete an object through a base 121*481dde66SAndroid Build Coastguard Workerpointer, and you'll get corrupted program states like memory leaks.) 122*481dde66SAndroid Build Coastguard Worker 123*481dde66SAndroid Build Coastguard WorkerYou can control whether the turtle's movement will leave a trace using `PenUp()` 124*481dde66SAndroid Build Coastguard Workerand `PenDown()`, and control its movement using `Forward()`, `Turn()`, and 125*481dde66SAndroid Build Coastguard Worker`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the 126*481dde66SAndroid Build Coastguard Workerturtle. 127*481dde66SAndroid Build Coastguard Worker 128*481dde66SAndroid Build Coastguard WorkerYour program will normally use a real implementation of this interface. In 129*481dde66SAndroid Build Coastguard Workertests, you can use a mock implementation instead. This allows you to easily 130*481dde66SAndroid Build Coastguard Workercheck what drawing primitives your program is calling, with what arguments, and 131*481dde66SAndroid Build Coastguard Workerin which order. Tests written this way are much more robust (they won't break 132*481dde66SAndroid Build Coastguard Workerbecause your new machine does anti-aliasing differently), easier to read and 133*481dde66SAndroid Build Coastguard Workermaintain (the intent of a test is expressed in the code, not in some binary 134*481dde66SAndroid Build Coastguard Workerimages), and run *much, much faster*. 135*481dde66SAndroid Build Coastguard Worker 136*481dde66SAndroid Build Coastguard Worker## Writing the Mock Class 137*481dde66SAndroid Build Coastguard Worker 138*481dde66SAndroid Build Coastguard WorkerIf you are lucky, the mocks you need to use have already been implemented by 139*481dde66SAndroid Build Coastguard Workersome nice people. If, however, you find yourself in the position to write a mock 140*481dde66SAndroid Build Coastguard Workerclass, relax - gMock turns this task into a fun game! (Well, almost.) 141*481dde66SAndroid Build Coastguard Worker 142*481dde66SAndroid Build Coastguard Worker### How to Define It 143*481dde66SAndroid Build Coastguard Worker 144*481dde66SAndroid Build Coastguard WorkerUsing the `Turtle` interface as example, here are the simple steps you need to 145*481dde66SAndroid Build Coastguard Workerfollow: 146*481dde66SAndroid Build Coastguard Worker 147*481dde66SAndroid Build Coastguard Worker* Derive a class `MockTurtle` from `Turtle`. 148*481dde66SAndroid Build Coastguard Worker* Take a *virtual* function of `Turtle` (while it's possible to 149*481dde66SAndroid Build Coastguard Worker [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods), 150*481dde66SAndroid Build Coastguard Worker it's much more involved). 151*481dde66SAndroid Build Coastguard Worker* In the `public:` section of the child class, write `MOCK_METHOD();` 152*481dde66SAndroid Build Coastguard Worker* Now comes the fun part: you take the function signature, cut-and-paste it 153*481dde66SAndroid Build Coastguard Worker into the macro, and add two commas - one between the return type and the 154*481dde66SAndroid Build Coastguard Worker name, another between the name and the argument list. 155*481dde66SAndroid Build Coastguard Worker* If you're mocking a const method, add a 4th parameter containing `(const)` 156*481dde66SAndroid Build Coastguard Worker (the parentheses are required). 157*481dde66SAndroid Build Coastguard Worker* Since you're overriding a virtual method, we suggest adding the `override` 158*481dde66SAndroid Build Coastguard Worker keyword. For const methods the 4th parameter becomes `(const, override)`, 159*481dde66SAndroid Build Coastguard Worker for non-const methods just `(override)`. This isn't mandatory. 160*481dde66SAndroid Build Coastguard Worker* Repeat until all virtual functions you want to mock are done. (It goes 161*481dde66SAndroid Build Coastguard Worker without saying that *all* pure virtual methods in your abstract class must 162*481dde66SAndroid Build Coastguard Worker be either mocked or overridden.) 163*481dde66SAndroid Build Coastguard Worker 164*481dde66SAndroid Build Coastguard WorkerAfter the process, you should have something like: 165*481dde66SAndroid Build Coastguard Worker 166*481dde66SAndroid Build Coastguard Worker```cpp 167*481dde66SAndroid Build Coastguard Worker#include <gmock/gmock.h> // Brings in gMock. 168*481dde66SAndroid Build Coastguard Worker 169*481dde66SAndroid Build Coastguard Workerclass MockTurtle : public Turtle { 170*481dde66SAndroid Build Coastguard Worker public: 171*481dde66SAndroid Build Coastguard Worker ... 172*481dde66SAndroid Build Coastguard Worker MOCK_METHOD(void, PenUp, (), (override)); 173*481dde66SAndroid Build Coastguard Worker MOCK_METHOD(void, PenDown, (), (override)); 174*481dde66SAndroid Build Coastguard Worker MOCK_METHOD(void, Forward, (int distance), (override)); 175*481dde66SAndroid Build Coastguard Worker MOCK_METHOD(void, Turn, (int degrees), (override)); 176*481dde66SAndroid Build Coastguard Worker MOCK_METHOD(void, GoTo, (int x, int y), (override)); 177*481dde66SAndroid Build Coastguard Worker MOCK_METHOD(int, GetX, (), (const, override)); 178*481dde66SAndroid Build Coastguard Worker MOCK_METHOD(int, GetY, (), (const, override)); 179*481dde66SAndroid Build Coastguard Worker}; 180*481dde66SAndroid Build Coastguard Worker``` 181*481dde66SAndroid Build Coastguard Worker 182*481dde66SAndroid Build Coastguard WorkerYou don't need to define these mock methods somewhere else - the `MOCK_METHOD` 183*481dde66SAndroid Build Coastguard Workermacro will generate the definitions for you. It's that simple! 184*481dde66SAndroid Build Coastguard Worker 185*481dde66SAndroid Build Coastguard Worker### Where to Put It 186*481dde66SAndroid Build Coastguard Worker 187*481dde66SAndroid Build Coastguard WorkerWhen you define a mock class, you need to decide where to put its definition. 188*481dde66SAndroid Build Coastguard WorkerSome people put it in a `_test.cc`. This is fine when the interface being mocked 189*481dde66SAndroid Build Coastguard Worker(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of 190*481dde66SAndroid Build Coastguard Worker`Foo` changes it, your test could break. (You can't really expect `Foo`'s 191*481dde66SAndroid Build Coastguard Workermaintainer to fix every test that uses `Foo`, can you?) 192*481dde66SAndroid Build Coastguard Worker 193*481dde66SAndroid Build Coastguard WorkerGenerally, you should not mock classes you don't own. If you must mock such a 194*481dde66SAndroid Build Coastguard Workerclass owned by others, define the mock class in `Foo`'s Bazel package (usually 195*481dde66SAndroid Build Coastguard Workerthe same directory or a `testing` sub-directory), and put it in a `.h` and a 196*481dde66SAndroid Build Coastguard Worker`cc_library` with `testonly=True`. Then everyone can reference them from their 197*481dde66SAndroid Build Coastguard Workertests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and 198*481dde66SAndroid Build Coastguard Workeronly tests that depend on the changed methods need to be fixed. 199*481dde66SAndroid Build Coastguard Worker 200*481dde66SAndroid Build Coastguard WorkerAnother way to do it: you can introduce a thin layer `FooAdaptor` on top of 201*481dde66SAndroid Build Coastguard Worker`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb 202*481dde66SAndroid Build Coastguard Workerchanges in `Foo` much more easily. While this is more work initially, carefully 203*481dde66SAndroid Build Coastguard Workerchoosing the adaptor interface can make your code easier to write and more 204*481dde66SAndroid Build Coastguard Workerreadable (a net win in the long run), as you can choose `FooAdaptor` to fit your 205*481dde66SAndroid Build Coastguard Workerspecific domain much better than `Foo` does. 206*481dde66SAndroid Build Coastguard Worker 207*481dde66SAndroid Build Coastguard Worker## Using Mocks in Tests 208*481dde66SAndroid Build Coastguard Worker 209*481dde66SAndroid Build Coastguard WorkerOnce you have a mock class, using it is easy. The typical work flow is: 210*481dde66SAndroid Build Coastguard Worker 211*481dde66SAndroid Build Coastguard Worker1. Import the gMock names from the `testing` namespace such that you can use 212*481dde66SAndroid Build Coastguard Worker them unqualified (You only have to do it once per file). Remember that 213*481dde66SAndroid Build Coastguard Worker namespaces are a good idea. 214*481dde66SAndroid Build Coastguard Worker2. Create some mock objects. 215*481dde66SAndroid Build Coastguard Worker3. Specify your expectations on them (How many times will a method be called? 216*481dde66SAndroid Build Coastguard Worker With what arguments? What should it do? etc.). 217*481dde66SAndroid Build Coastguard Worker4. Exercise some code that uses the mocks; optionally, check the result using 218*481dde66SAndroid Build Coastguard Worker googletest assertions. If a mock method is called more than expected or with 219*481dde66SAndroid Build Coastguard Worker wrong arguments, you'll get an error immediately. 220*481dde66SAndroid Build Coastguard Worker5. When a mock is destructed, gMock will automatically check whether all 221*481dde66SAndroid Build Coastguard Worker expectations on it have been satisfied. 222*481dde66SAndroid Build Coastguard Worker 223*481dde66SAndroid Build Coastguard WorkerHere's an example: 224*481dde66SAndroid Build Coastguard Worker 225*481dde66SAndroid Build Coastguard Worker```cpp 226*481dde66SAndroid Build Coastguard Worker#include "path/to/mock-turtle.h" 227*481dde66SAndroid Build Coastguard Worker#include <gmock/gmock.h> 228*481dde66SAndroid Build Coastguard Worker#include <gtest/gtest.h> 229*481dde66SAndroid Build Coastguard Worker 230*481dde66SAndroid Build Coastguard Workerusing ::testing::AtLeast; // #1 231*481dde66SAndroid Build Coastguard Worker 232*481dde66SAndroid Build Coastguard WorkerTEST(PainterTest, CanDrawSomething) { 233*481dde66SAndroid Build Coastguard Worker MockTurtle turtle; // #2 234*481dde66SAndroid Build Coastguard Worker EXPECT_CALL(turtle, PenDown()) // #3 235*481dde66SAndroid Build Coastguard Worker .Times(AtLeast(1)); 236*481dde66SAndroid Build Coastguard Worker 237*481dde66SAndroid Build Coastguard Worker Painter painter(&turtle); // #4 238*481dde66SAndroid Build Coastguard Worker 239*481dde66SAndroid Build Coastguard Worker EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); // #5 240*481dde66SAndroid Build Coastguard Worker} 241*481dde66SAndroid Build Coastguard Worker``` 242*481dde66SAndroid Build Coastguard Worker 243*481dde66SAndroid Build Coastguard WorkerAs you might have guessed, this test checks that `PenDown()` is called at least 244*481dde66SAndroid Build Coastguard Workeronce. If the `painter` object didn't call this method, your test will fail with 245*481dde66SAndroid Build Coastguard Workera message like this: 246*481dde66SAndroid Build Coastguard Worker 247*481dde66SAndroid Build Coastguard Worker```text 248*481dde66SAndroid Build Coastguard Workerpath/to/my_test.cc:119: Failure 249*481dde66SAndroid Build Coastguard WorkerActual function call count doesn't match this expectation: 250*481dde66SAndroid Build Coastguard WorkerActually: never called; 251*481dde66SAndroid Build Coastguard WorkerExpected: called at least once. 252*481dde66SAndroid Build Coastguard WorkerStack trace: 253*481dde66SAndroid Build Coastguard Worker... 254*481dde66SAndroid Build Coastguard Worker``` 255*481dde66SAndroid Build Coastguard Worker 256*481dde66SAndroid Build Coastguard Worker**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on 257*481dde66SAndroid Build Coastguard Workerthe line number to jump right to the failed expectation. 258*481dde66SAndroid Build Coastguard Worker 259*481dde66SAndroid Build Coastguard Worker**Tip 2:** If your mock objects are never deleted, the final verification won't 260*481dde66SAndroid Build Coastguard Workerhappen. Therefore it's a good idea to turn on the heap checker in your tests 261*481dde66SAndroid Build Coastguard Workerwhen you allocate mocks on the heap. You get that automatically if you use the 262*481dde66SAndroid Build Coastguard Worker`gtest_main` library already. 263*481dde66SAndroid Build Coastguard Worker 264*481dde66SAndroid Build Coastguard Worker###### Expectation Ordering 265*481dde66SAndroid Build Coastguard Worker 266*481dde66SAndroid Build Coastguard Worker**Important note:** gMock requires expectations to be set **before** the mock 267*481dde66SAndroid Build Coastguard Workerfunctions are called, otherwise the behavior is **undefined**. Do not alternate 268*481dde66SAndroid Build Coastguard Workerbetween calls to `EXPECT_CALL()` and calls to the mock functions, and do not set 269*481dde66SAndroid Build Coastguard Workerany expectations on a mock after passing the mock to an API. 270*481dde66SAndroid Build Coastguard Worker 271*481dde66SAndroid Build Coastguard WorkerThis means `EXPECT_CALL()` should be read as expecting that a call will occur 272*481dde66SAndroid Build Coastguard Worker*in the future*, not that a call has occurred. Why does gMock work like that? 273*481dde66SAndroid Build Coastguard WorkerWell, specifying the expectation beforehand allows gMock to report a violation 274*481dde66SAndroid Build Coastguard Workeras soon as it rises, when the context (stack trace, etc) is still available. 275*481dde66SAndroid Build Coastguard WorkerThis makes debugging much easier. 276*481dde66SAndroid Build Coastguard Worker 277*481dde66SAndroid Build Coastguard WorkerAdmittedly, this test is contrived and doesn't do much. You can easily achieve 278*481dde66SAndroid Build Coastguard Workerthe same effect without using gMock. However, as we shall reveal soon, gMock 279*481dde66SAndroid Build Coastguard Workerallows you to do *so much more* with the mocks. 280*481dde66SAndroid Build Coastguard Worker 281*481dde66SAndroid Build Coastguard Worker## Setting Expectations 282*481dde66SAndroid Build Coastguard Worker 283*481dde66SAndroid Build Coastguard WorkerThe key to using a mock object successfully is to set the *right expectations* 284*481dde66SAndroid Build Coastguard Workeron it. If you set the expectations too strict, your test will fail as the result 285*481dde66SAndroid Build Coastguard Workerof unrelated changes. If you set them too loose, bugs can slip through. You want 286*481dde66SAndroid Build Coastguard Workerto do it just right such that your test can catch exactly the kind of bugs you 287*481dde66SAndroid Build Coastguard Workerintend it to catch. gMock provides the necessary means for you to do it "just 288*481dde66SAndroid Build Coastguard Workerright." 289*481dde66SAndroid Build Coastguard Worker 290*481dde66SAndroid Build Coastguard Worker### General Syntax 291*481dde66SAndroid Build Coastguard Worker 292*481dde66SAndroid Build Coastguard WorkerIn gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock 293*481dde66SAndroid Build Coastguard Workermethod. The general syntax is: 294*481dde66SAndroid Build Coastguard Worker 295*481dde66SAndroid Build Coastguard Worker```cpp 296*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(mock_object, method(matchers)) 297*481dde66SAndroid Build Coastguard Worker .Times(cardinality) 298*481dde66SAndroid Build Coastguard Worker .WillOnce(action) 299*481dde66SAndroid Build Coastguard Worker .WillRepeatedly(action); 300*481dde66SAndroid Build Coastguard Worker``` 301*481dde66SAndroid Build Coastguard Worker 302*481dde66SAndroid Build Coastguard WorkerThe macro has two arguments: first the mock object, and then the method and its 303*481dde66SAndroid Build Coastguard Workerarguments. Note that the two are separated by a comma (`,`), not a period (`.`). 304*481dde66SAndroid Build Coastguard Worker(Why using a comma? The answer is that it was necessary for technical reasons.) 305*481dde66SAndroid Build Coastguard WorkerIf the method is not overloaded, the macro can also be called without matchers: 306*481dde66SAndroid Build Coastguard Worker 307*481dde66SAndroid Build Coastguard Worker```cpp 308*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(mock_object, non-overloaded-method) 309*481dde66SAndroid Build Coastguard Worker .Times(cardinality) 310*481dde66SAndroid Build Coastguard Worker .WillOnce(action) 311*481dde66SAndroid Build Coastguard Worker .WillRepeatedly(action); 312*481dde66SAndroid Build Coastguard Worker``` 313*481dde66SAndroid Build Coastguard Worker 314*481dde66SAndroid Build Coastguard WorkerThis syntax allows the test writer to specify "called with any arguments" 315*481dde66SAndroid Build Coastguard Workerwithout explicitly specifying the number or types of arguments. To avoid 316*481dde66SAndroid Build Coastguard Workerunintended ambiguity, this syntax may only be used for methods that are not 317*481dde66SAndroid Build Coastguard Workeroverloaded. 318*481dde66SAndroid Build Coastguard Worker 319*481dde66SAndroid Build Coastguard WorkerEither form of the macro can be followed by some optional *clauses* that provide 320*481dde66SAndroid Build Coastguard Workermore information about the expectation. We'll discuss how each clause works in 321*481dde66SAndroid Build Coastguard Workerthe coming sections. 322*481dde66SAndroid Build Coastguard Worker 323*481dde66SAndroid Build Coastguard WorkerThis syntax is designed to make an expectation read like English. For example, 324*481dde66SAndroid Build Coastguard Workeryou can probably guess that 325*481dde66SAndroid Build Coastguard Worker 326*481dde66SAndroid Build Coastguard Worker```cpp 327*481dde66SAndroid Build Coastguard Workerusing ::testing::Return; 328*481dde66SAndroid Build Coastguard Worker... 329*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GetX()) 330*481dde66SAndroid Build Coastguard Worker .Times(5) 331*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(100)) 332*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(150)) 333*481dde66SAndroid Build Coastguard Worker .WillRepeatedly(Return(200)); 334*481dde66SAndroid Build Coastguard Worker``` 335*481dde66SAndroid Build Coastguard Worker 336*481dde66SAndroid Build Coastguard Workersays that the `turtle` object's `GetX()` method will be called five times, it 337*481dde66SAndroid Build Coastguard Workerwill return 100 the first time, 150 the second time, and then 200 every time. 338*481dde66SAndroid Build Coastguard WorkerSome people like to call this style of syntax a Domain-Specific Language (DSL). 339*481dde66SAndroid Build Coastguard Worker 340*481dde66SAndroid Build Coastguard Worker{: .callout .note} 341*481dde66SAndroid Build Coastguard Worker**Note:** Why do we use a macro to do this? Well it serves two purposes: first 342*481dde66SAndroid Build Coastguard Workerit makes expectations easily identifiable (either by `grep` or by a human 343*481dde66SAndroid Build Coastguard Workerreader), and second it allows gMock to include the source file location of a 344*481dde66SAndroid Build Coastguard Workerfailed expectation in messages, making debugging easier. 345*481dde66SAndroid Build Coastguard Worker 346*481dde66SAndroid Build Coastguard Worker### Matchers: What Arguments Do We Expect? 347*481dde66SAndroid Build Coastguard Worker 348*481dde66SAndroid Build Coastguard WorkerWhen a mock function takes arguments, we may specify what arguments we are 349*481dde66SAndroid Build Coastguard Workerexpecting, for example: 350*481dde66SAndroid Build Coastguard Worker 351*481dde66SAndroid Build Coastguard Worker```cpp 352*481dde66SAndroid Build Coastguard Worker// Expects the turtle to move forward by 100 units. 353*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, Forward(100)); 354*481dde66SAndroid Build Coastguard Worker``` 355*481dde66SAndroid Build Coastguard Worker 356*481dde66SAndroid Build Coastguard WorkerOftentimes you do not want to be too specific. Remember that talk about tests 357*481dde66SAndroid Build Coastguard Workerbeing too rigid? Over specification leads to brittle tests and obscures the 358*481dde66SAndroid Build Coastguard Workerintent of tests. Therefore we encourage you to specify only what's necessary—no 359*481dde66SAndroid Build Coastguard Workermore, no less. If you aren't interested in the value of an argument, write `_` 360*481dde66SAndroid Build Coastguard Workeras the argument, which means "anything goes": 361*481dde66SAndroid Build Coastguard Worker 362*481dde66SAndroid Build Coastguard Worker```cpp 363*481dde66SAndroid Build Coastguard Workerusing ::testing::_; 364*481dde66SAndroid Build Coastguard Worker... 365*481dde66SAndroid Build Coastguard Worker// Expects that the turtle jumps to somewhere on the x=50 line. 366*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GoTo(50, _)); 367*481dde66SAndroid Build Coastguard Worker``` 368*481dde66SAndroid Build Coastguard Worker 369*481dde66SAndroid Build Coastguard Worker`_` is an instance of what we call **matchers**. A matcher is like a predicate 370*481dde66SAndroid Build Coastguard Workerand can test whether an argument is what we'd expect. You can use a matcher 371*481dde66SAndroid Build Coastguard Workerinside `EXPECT_CALL()` wherever a function argument is expected. `_` is a 372*481dde66SAndroid Build Coastguard Workerconvenient way of saying "any value". 373*481dde66SAndroid Build Coastguard Worker 374*481dde66SAndroid Build Coastguard WorkerIn the above examples, `100` and `50` are also matchers; implicitly, they are 375*481dde66SAndroid Build Coastguard Workerthe same as `Eq(100)` and `Eq(50)`, which specify that the argument must be 376*481dde66SAndroid Build Coastguard Workerequal (using `operator==`) to the matcher argument. There are many 377*481dde66SAndroid Build Coastguard Worker[built-in matchers](reference/matchers.md) for common types (as well as 378*481dde66SAndroid Build Coastguard Worker[custom matchers](gmock_cook_book.md#NewMatchers)); for example: 379*481dde66SAndroid Build Coastguard Worker 380*481dde66SAndroid Build Coastguard Worker```cpp 381*481dde66SAndroid Build Coastguard Workerusing ::testing::Ge; 382*481dde66SAndroid Build Coastguard Worker... 383*481dde66SAndroid Build Coastguard Worker// Expects the turtle moves forward by at least 100. 384*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, Forward(Ge(100))); 385*481dde66SAndroid Build Coastguard Worker``` 386*481dde66SAndroid Build Coastguard Worker 387*481dde66SAndroid Build Coastguard WorkerIf you don't care about *any* arguments, rather than specify `_` for each of 388*481dde66SAndroid Build Coastguard Workerthem you may instead omit the parameter list: 389*481dde66SAndroid Build Coastguard Worker 390*481dde66SAndroid Build Coastguard Worker```cpp 391*481dde66SAndroid Build Coastguard Worker// Expects the turtle to move forward. 392*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, Forward); 393*481dde66SAndroid Build Coastguard Worker// Expects the turtle to jump somewhere. 394*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GoTo); 395*481dde66SAndroid Build Coastguard Worker``` 396*481dde66SAndroid Build Coastguard Worker 397*481dde66SAndroid Build Coastguard WorkerThis works for all non-overloaded methods; if a method is overloaded, you need 398*481dde66SAndroid Build Coastguard Workerto help gMock resolve which overload is expected by specifying the number of 399*481dde66SAndroid Build Coastguard Workerarguments and possibly also the 400*481dde66SAndroid Build Coastguard Worker[types of the arguments](gmock_cook_book.md#SelectOverload). 401*481dde66SAndroid Build Coastguard Worker 402*481dde66SAndroid Build Coastguard Worker### Cardinalities: How Many Times Will It Be Called? 403*481dde66SAndroid Build Coastguard Worker 404*481dde66SAndroid Build Coastguard WorkerThe first clause we can specify following an `EXPECT_CALL()` is `Times()`. We 405*481dde66SAndroid Build Coastguard Workercall its argument a **cardinality** as it tells *how many times* the call should 406*481dde66SAndroid Build Coastguard Workeroccur. It allows us to repeat an expectation many times without actually writing 407*481dde66SAndroid Build Coastguard Workerit as many times. More importantly, a cardinality can be "fuzzy", just like a 408*481dde66SAndroid Build Coastguard Workermatcher can be. This allows a user to express the intent of a test exactly. 409*481dde66SAndroid Build Coastguard Worker 410*481dde66SAndroid Build Coastguard WorkerAn interesting special case is when we say `Times(0)`. You may have guessed - it 411*481dde66SAndroid Build Coastguard Workermeans that the function shouldn't be called with the given arguments at all, and 412*481dde66SAndroid Build Coastguard WorkergMock will report a googletest failure whenever the function is (wrongfully) 413*481dde66SAndroid Build Coastguard Workercalled. 414*481dde66SAndroid Build Coastguard Worker 415*481dde66SAndroid Build Coastguard WorkerWe've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the 416*481dde66SAndroid Build Coastguard Workerlist of built-in cardinalities you can use, see 417*481dde66SAndroid Build Coastguard Worker[here](gmock_cheat_sheet.md#CardinalityList). 418*481dde66SAndroid Build Coastguard Worker 419*481dde66SAndroid Build Coastguard WorkerThe `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer 420*481dde66SAndroid Build Coastguard Workerthe cardinality for you.** The rules are easy to remember: 421*481dde66SAndroid Build Coastguard Worker 422*481dde66SAndroid Build Coastguard Worker* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the 423*481dde66SAndroid Build Coastguard Worker `EXPECT_CALL()`, the inferred cardinality is `Times(1)`. 424*481dde66SAndroid Build Coastguard Worker* If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >= 425*481dde66SAndroid Build Coastguard Worker 1, the cardinality is `Times(n)`. 426*481dde66SAndroid Build Coastguard Worker* If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >= 427*481dde66SAndroid Build Coastguard Worker 0, the cardinality is `Times(AtLeast(n))`. 428*481dde66SAndroid Build Coastguard Worker 429*481dde66SAndroid Build Coastguard Worker**Quick quiz:** what do you think will happen if a function is expected to be 430*481dde66SAndroid Build Coastguard Workercalled twice but actually called four times? 431*481dde66SAndroid Build Coastguard Worker 432*481dde66SAndroid Build Coastguard Worker### Actions: What Should It Do? 433*481dde66SAndroid Build Coastguard Worker 434*481dde66SAndroid Build Coastguard WorkerRemember that a mock object doesn't really have a working implementation? We as 435*481dde66SAndroid Build Coastguard Workerusers have to tell it what to do when a method is invoked. This is easy in 436*481dde66SAndroid Build Coastguard WorkergMock. 437*481dde66SAndroid Build Coastguard Worker 438*481dde66SAndroid Build Coastguard WorkerFirst, if the return type of a mock function is a built-in type or a pointer, 439*481dde66SAndroid Build Coastguard Workerthe function has a **default action** (a `void` function will just return, a 440*481dde66SAndroid Build Coastguard Worker`bool` function will return `false`, and other functions will return 0). In 441*481dde66SAndroid Build Coastguard Workeraddition, in C++ 11 and above, a mock function whose return type is 442*481dde66SAndroid Build Coastguard Workerdefault-constructible (i.e. has a default constructor) has a default action of 443*481dde66SAndroid Build Coastguard Workerreturning a default-constructed value. If you don't say anything, this behavior 444*481dde66SAndroid Build Coastguard Workerwill be used. 445*481dde66SAndroid Build Coastguard Worker 446*481dde66SAndroid Build Coastguard WorkerSecond, if a mock function doesn't have a default action, or the default action 447*481dde66SAndroid Build Coastguard Workerdoesn't suit you, you can specify the action to be taken each time the 448*481dde66SAndroid Build Coastguard Workerexpectation matches using a series of `WillOnce()` clauses followed by an 449*481dde66SAndroid Build Coastguard Workeroptional `WillRepeatedly()`. For example, 450*481dde66SAndroid Build Coastguard Worker 451*481dde66SAndroid Build Coastguard Worker```cpp 452*481dde66SAndroid Build Coastguard Workerusing ::testing::Return; 453*481dde66SAndroid Build Coastguard Worker... 454*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GetX()) 455*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(100)) 456*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(200)) 457*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(300)); 458*481dde66SAndroid Build Coastguard Worker``` 459*481dde66SAndroid Build Coastguard Worker 460*481dde66SAndroid Build Coastguard Workersays that `turtle.GetX()` will be called *exactly three times* (gMock inferred 461*481dde66SAndroid Build Coastguard Workerthis from how many `WillOnce()` clauses we've written, since we didn't 462*481dde66SAndroid Build Coastguard Workerexplicitly write `Times()`), and will return 100, 200, and 300 respectively. 463*481dde66SAndroid Build Coastguard Worker 464*481dde66SAndroid Build Coastguard Worker```cpp 465*481dde66SAndroid Build Coastguard Workerusing ::testing::Return; 466*481dde66SAndroid Build Coastguard Worker... 467*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GetY()) 468*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(100)) 469*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(200)) 470*481dde66SAndroid Build Coastguard Worker .WillRepeatedly(Return(300)); 471*481dde66SAndroid Build Coastguard Worker``` 472*481dde66SAndroid Build Coastguard Worker 473*481dde66SAndroid Build Coastguard Workersays that `turtle.GetY()` will be called *at least twice* (gMock knows this as 474*481dde66SAndroid Build Coastguard Workerwe've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no 475*481dde66SAndroid Build Coastguard Workerexplicit `Times()`), will return 100 and 200 respectively the first two times, 476*481dde66SAndroid Build Coastguard Workerand 300 from the third time on. 477*481dde66SAndroid Build Coastguard Worker 478*481dde66SAndroid Build Coastguard WorkerOf course, if you explicitly write a `Times()`, gMock will not try to infer the 479*481dde66SAndroid Build Coastguard Workercardinality itself. What if the number you specified is larger than there are 480*481dde66SAndroid Build Coastguard Worker`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do 481*481dde66SAndroid Build Coastguard Workerthe *default* action for the function every time (unless, of course, you have a 482*481dde66SAndroid Build Coastguard Worker`WillRepeatedly()`.). 483*481dde66SAndroid Build Coastguard Worker 484*481dde66SAndroid Build Coastguard WorkerWhat can we do inside `WillOnce()` besides `Return()`? You can return a 485*481dde66SAndroid Build Coastguard Workerreference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function, 486*481dde66SAndroid Build Coastguard Workeramong [others](gmock_cook_book.md#using-actions). 487*481dde66SAndroid Build Coastguard Worker 488*481dde66SAndroid Build Coastguard Worker**Important note:** The `EXPECT_CALL()` statement evaluates the action clause 489*481dde66SAndroid Build Coastguard Workeronly once, even though the action may be performed many times. Therefore you 490*481dde66SAndroid Build Coastguard Workermust be careful about side effects. The following may not do what you want: 491*481dde66SAndroid Build Coastguard Worker 492*481dde66SAndroid Build Coastguard Worker```cpp 493*481dde66SAndroid Build Coastguard Workerusing ::testing::Return; 494*481dde66SAndroid Build Coastguard Worker... 495*481dde66SAndroid Build Coastguard Workerint n = 100; 496*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GetX()) 497*481dde66SAndroid Build Coastguard Worker .Times(4) 498*481dde66SAndroid Build Coastguard Worker .WillRepeatedly(Return(n++)); 499*481dde66SAndroid Build Coastguard Worker``` 500*481dde66SAndroid Build Coastguard Worker 501*481dde66SAndroid Build Coastguard WorkerInstead of returning 100, 101, 102, ..., consecutively, this mock function will 502*481dde66SAndroid Build Coastguard Workeralways return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)` 503*481dde66SAndroid Build Coastguard Workerwill create a new `Foo` object when the `EXPECT_CALL()` is executed, and will 504*481dde66SAndroid Build Coastguard Workerreturn the same pointer every time. If you want the side effect to happen every 505*481dde66SAndroid Build Coastguard Workertime, you need to define a custom action, which we'll teach in the 506*481dde66SAndroid Build Coastguard Worker[cook book](gmock_cook_book.md). 507*481dde66SAndroid Build Coastguard Worker 508*481dde66SAndroid Build Coastguard WorkerTime for another quiz! What do you think the following means? 509*481dde66SAndroid Build Coastguard Worker 510*481dde66SAndroid Build Coastguard Worker```cpp 511*481dde66SAndroid Build Coastguard Workerusing ::testing::Return; 512*481dde66SAndroid Build Coastguard Worker... 513*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GetY()) 514*481dde66SAndroid Build Coastguard Worker .Times(4) 515*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(100)); 516*481dde66SAndroid Build Coastguard Worker``` 517*481dde66SAndroid Build Coastguard Worker 518*481dde66SAndroid Build Coastguard WorkerObviously `turtle.GetY()` is expected to be called four times. But if you think 519*481dde66SAndroid Build Coastguard Workerit will return 100 every time, think twice! Remember that one `WillOnce()` 520*481dde66SAndroid Build Coastguard Workerclause will be consumed each time the function is invoked and the default action 521*481dde66SAndroid Build Coastguard Workerwill be taken afterwards. So the right answer is that `turtle.GetY()` will 522*481dde66SAndroid Build Coastguard Workerreturn 100 the first time, but **return 0 from the second time on**, as 523*481dde66SAndroid Build Coastguard Workerreturning 0 is the default action for `int` functions. 524*481dde66SAndroid Build Coastguard Worker 525*481dde66SAndroid Build Coastguard Worker### Using Multiple Expectations {#MultiExpectations} 526*481dde66SAndroid Build Coastguard Worker 527*481dde66SAndroid Build Coastguard WorkerSo far we've only shown examples where you have a single expectation. More 528*481dde66SAndroid Build Coastguard Workerrealistically, you'll specify expectations on multiple mock methods which may be 529*481dde66SAndroid Build Coastguard Workerfrom multiple mock objects. 530*481dde66SAndroid Build Coastguard Worker 531*481dde66SAndroid Build Coastguard WorkerBy default, when a mock method is invoked, gMock will search the expectations in 532*481dde66SAndroid Build Coastguard Workerthe **reverse order** they are defined, and stop when an active expectation that 533*481dde66SAndroid Build Coastguard Workermatches the arguments is found (you can think of it as "newer rules override 534*481dde66SAndroid Build Coastguard Workerolder ones."). If the matching expectation cannot take any more calls, you will 535*481dde66SAndroid Build Coastguard Workerget an upper-bound-violated failure. Here's an example: 536*481dde66SAndroid Build Coastguard Worker 537*481dde66SAndroid Build Coastguard Worker```cpp 538*481dde66SAndroid Build Coastguard Workerusing ::testing::_; 539*481dde66SAndroid Build Coastguard Worker... 540*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, Forward(_)); // #1 541*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, Forward(10)) // #2 542*481dde66SAndroid Build Coastguard Worker .Times(2); 543*481dde66SAndroid Build Coastguard Worker``` 544*481dde66SAndroid Build Coastguard Worker 545*481dde66SAndroid Build Coastguard WorkerIf `Forward(10)` is called three times in a row, the third time it will be an 546*481dde66SAndroid Build Coastguard Workererror, as the last matching expectation (#2) has been saturated. If, however, 547*481dde66SAndroid Build Coastguard Workerthe third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK, 548*481dde66SAndroid Build Coastguard Workeras now #1 will be the matching expectation. 549*481dde66SAndroid Build Coastguard Worker 550*481dde66SAndroid Build Coastguard Worker{: .callout .note} 551*481dde66SAndroid Build Coastguard Worker**Note:** Why does gMock search for a match in the *reverse* order of the 552*481dde66SAndroid Build Coastguard Workerexpectations? The reason is that this allows a user to set up the default 553*481dde66SAndroid Build Coastguard Workerexpectations in a mock object's constructor or the test fixture's set-up phase 554*481dde66SAndroid Build Coastguard Workerand then customize the mock by writing more specific expectations in the test 555*481dde66SAndroid Build Coastguard Workerbody. So, if you have two expectations on the same method, you want to put the 556*481dde66SAndroid Build Coastguard Workerone with more specific matchers **after** the other, or the more specific rule 557*481dde66SAndroid Build Coastguard Workerwould be shadowed by the more general one that comes after it. 558*481dde66SAndroid Build Coastguard Worker 559*481dde66SAndroid Build Coastguard Worker{: .callout .tip} 560*481dde66SAndroid Build Coastguard Worker**Tip:** It is very common to start with a catch-all expectation for a method 561*481dde66SAndroid Build Coastguard Workerand `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if 562*481dde66SAndroid Build Coastguard Workeroverloaded). This makes any calls to the method expected. This is not necessary 563*481dde66SAndroid Build Coastguard Workerfor methods that are not mentioned at all (these are "uninteresting"), but is 564*481dde66SAndroid Build Coastguard Workeruseful for methods that have some expectations, but for which other calls are 565*481dde66SAndroid Build Coastguard Workerok. See 566*481dde66SAndroid Build Coastguard Worker[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected). 567*481dde66SAndroid Build Coastguard Worker 568*481dde66SAndroid Build Coastguard Worker### Ordered vs Unordered Calls {#OrderedCalls} 569*481dde66SAndroid Build Coastguard Worker 570*481dde66SAndroid Build Coastguard WorkerBy default, an expectation can match a call even though an earlier expectation 571*481dde66SAndroid Build Coastguard Workerhasn't been satisfied. In other words, the calls don't have to occur in the 572*481dde66SAndroid Build Coastguard Workerorder the expectations are specified. 573*481dde66SAndroid Build Coastguard Worker 574*481dde66SAndroid Build Coastguard WorkerSometimes, you may want all the expected calls to occur in a strict order. To 575*481dde66SAndroid Build Coastguard Workersay this in gMock is easy: 576*481dde66SAndroid Build Coastguard Worker 577*481dde66SAndroid Build Coastguard Worker```cpp 578*481dde66SAndroid Build Coastguard Workerusing ::testing::InSequence; 579*481dde66SAndroid Build Coastguard Worker... 580*481dde66SAndroid Build Coastguard WorkerTEST(FooTest, DrawsLineSegment) { 581*481dde66SAndroid Build Coastguard Worker ... 582*481dde66SAndroid Build Coastguard Worker { 583*481dde66SAndroid Build Coastguard Worker InSequence seq; 584*481dde66SAndroid Build Coastguard Worker 585*481dde66SAndroid Build Coastguard Worker EXPECT_CALL(turtle, PenDown()); 586*481dde66SAndroid Build Coastguard Worker EXPECT_CALL(turtle, Forward(100)); 587*481dde66SAndroid Build Coastguard Worker EXPECT_CALL(turtle, PenUp()); 588*481dde66SAndroid Build Coastguard Worker } 589*481dde66SAndroid Build Coastguard Worker Foo(); 590*481dde66SAndroid Build Coastguard Worker} 591*481dde66SAndroid Build Coastguard Worker``` 592*481dde66SAndroid Build Coastguard Worker 593*481dde66SAndroid Build Coastguard WorkerBy creating an object of type `InSequence`, all expectations in its scope are 594*481dde66SAndroid Build Coastguard Workerput into a *sequence* and have to occur *sequentially*. Since we are just 595*481dde66SAndroid Build Coastguard Workerrelying on the constructor and destructor of this object to do the actual work, 596*481dde66SAndroid Build Coastguard Workerits name is really irrelevant. 597*481dde66SAndroid Build Coastguard Worker 598*481dde66SAndroid Build Coastguard WorkerIn this example, we test that `Foo()` calls the three expected functions in the 599*481dde66SAndroid Build Coastguard Workerorder as written. If a call is made out-of-order, it will be an error. 600*481dde66SAndroid Build Coastguard Worker 601*481dde66SAndroid Build Coastguard Worker(What if you care about the relative order of some of the calls, but not all of 602*481dde66SAndroid Build Coastguard Workerthem? Can you specify an arbitrary partial order? The answer is ... yes! The 603*481dde66SAndroid Build Coastguard Workerdetails can be found [here](gmock_cook_book.md#OrderedCalls).) 604*481dde66SAndroid Build Coastguard Worker 605*481dde66SAndroid Build Coastguard Worker### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations} 606*481dde66SAndroid Build Coastguard Worker 607*481dde66SAndroid Build Coastguard WorkerNow let's do a quick quiz to see how well you can use this mock stuff already. 608*481dde66SAndroid Build Coastguard WorkerHow would you test that the turtle is asked to go to the origin *exactly twice* 609*481dde66SAndroid Build Coastguard Worker(you want to ignore any other instructions it receives)? 610*481dde66SAndroid Build Coastguard Worker 611*481dde66SAndroid Build Coastguard WorkerAfter you've come up with your answer, take a look at ours and compare notes 612*481dde66SAndroid Build Coastguard Worker(solve it yourself first - don't cheat!): 613*481dde66SAndroid Build Coastguard Worker 614*481dde66SAndroid Build Coastguard Worker```cpp 615*481dde66SAndroid Build Coastguard Workerusing ::testing::_; 616*481dde66SAndroid Build Coastguard Workerusing ::testing::AnyNumber; 617*481dde66SAndroid Build Coastguard Worker... 618*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GoTo(_, _)) // #1 619*481dde66SAndroid Build Coastguard Worker .Times(AnyNumber()); 620*481dde66SAndroid Build Coastguard WorkerEXPECT_CALL(turtle, GoTo(0, 0)) // #2 621*481dde66SAndroid Build Coastguard Worker .Times(2); 622*481dde66SAndroid Build Coastguard Worker``` 623*481dde66SAndroid Build Coastguard Worker 624*481dde66SAndroid Build Coastguard WorkerSuppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will 625*481dde66SAndroid Build Coastguard Workersee that the arguments match expectation #2 (remember that we always pick the 626*481dde66SAndroid Build Coastguard Workerlast matching expectation). Now, since we said that there should be only two 627*481dde66SAndroid Build Coastguard Workersuch calls, gMock will report an error immediately. This is basically what we've 628*481dde66SAndroid Build Coastguard Workertold you in the [Using Multiple Expectations](#MultiExpectations) section above. 629*481dde66SAndroid Build Coastguard Worker 630*481dde66SAndroid Build Coastguard WorkerThis example shows that **expectations in gMock are "sticky" by default**, in 631*481dde66SAndroid Build Coastguard Workerthe sense that they remain active even after we have reached their invocation 632*481dde66SAndroid Build Coastguard Workerupper bounds. This is an important rule to remember, as it affects the meaning 633*481dde66SAndroid Build Coastguard Workerof the spec, and is **different** to how it's done in many other mocking 634*481dde66SAndroid Build Coastguard Workerframeworks (Why'd we do that? Because we think our rule makes the common cases 635*481dde66SAndroid Build Coastguard Workereasier to express and understand.). 636*481dde66SAndroid Build Coastguard Worker 637*481dde66SAndroid Build Coastguard WorkerSimple? Let's see if you've really understood it: what does the following code 638*481dde66SAndroid Build Coastguard Workersay? 639*481dde66SAndroid Build Coastguard Worker 640*481dde66SAndroid Build Coastguard Worker```cpp 641*481dde66SAndroid Build Coastguard Workerusing ::testing::Return; 642*481dde66SAndroid Build Coastguard Worker... 643*481dde66SAndroid Build Coastguard Workerfor (int i = n; i > 0; i--) { 644*481dde66SAndroid Build Coastguard Worker EXPECT_CALL(turtle, GetX()) 645*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(10*i)); 646*481dde66SAndroid Build Coastguard Worker} 647*481dde66SAndroid Build Coastguard Worker``` 648*481dde66SAndroid Build Coastguard Worker 649*481dde66SAndroid Build Coastguard WorkerIf you think it says that `turtle.GetX()` will be called `n` times and will 650*481dde66SAndroid Build Coastguard Workerreturn 10, 20, 30, ..., consecutively, think twice! The problem is that, as we 651*481dde66SAndroid Build Coastguard Workersaid, expectations are sticky. So, the second time `turtle.GetX()` is called, 652*481dde66SAndroid Build Coastguard Workerthe last (latest) `EXPECT_CALL()` statement will match, and will immediately 653*481dde66SAndroid Build Coastguard Workerlead to an "upper bound violated" error - this piece of code is not very useful! 654*481dde66SAndroid Build Coastguard Worker 655*481dde66SAndroid Build Coastguard WorkerOne correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is 656*481dde66SAndroid Build Coastguard Workerto explicitly say that the expectations are *not* sticky. In other words, they 657*481dde66SAndroid Build Coastguard Workershould *retire* as soon as they are saturated: 658*481dde66SAndroid Build Coastguard Worker 659*481dde66SAndroid Build Coastguard Worker```cpp 660*481dde66SAndroid Build Coastguard Workerusing ::testing::Return; 661*481dde66SAndroid Build Coastguard Worker... 662*481dde66SAndroid Build Coastguard Workerfor (int i = n; i > 0; i--) { 663*481dde66SAndroid Build Coastguard Worker EXPECT_CALL(turtle, GetX()) 664*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(10*i)) 665*481dde66SAndroid Build Coastguard Worker .RetiresOnSaturation(); 666*481dde66SAndroid Build Coastguard Worker} 667*481dde66SAndroid Build Coastguard Worker``` 668*481dde66SAndroid Build Coastguard Worker 669*481dde66SAndroid Build Coastguard WorkerAnd, there's a better way to do it: in this case, we expect the calls to occur 670*481dde66SAndroid Build Coastguard Workerin a specific order, and we line up the actions to match the order. Since the 671*481dde66SAndroid Build Coastguard Workerorder is important here, we should make it explicit using a sequence: 672*481dde66SAndroid Build Coastguard Worker 673*481dde66SAndroid Build Coastguard Worker```cpp 674*481dde66SAndroid Build Coastguard Workerusing ::testing::InSequence; 675*481dde66SAndroid Build Coastguard Workerusing ::testing::Return; 676*481dde66SAndroid Build Coastguard Worker... 677*481dde66SAndroid Build Coastguard Worker{ 678*481dde66SAndroid Build Coastguard Worker InSequence s; 679*481dde66SAndroid Build Coastguard Worker 680*481dde66SAndroid Build Coastguard Worker for (int i = 1; i <= n; i++) { 681*481dde66SAndroid Build Coastguard Worker EXPECT_CALL(turtle, GetX()) 682*481dde66SAndroid Build Coastguard Worker .WillOnce(Return(10*i)) 683*481dde66SAndroid Build Coastguard Worker .RetiresOnSaturation(); 684*481dde66SAndroid Build Coastguard Worker } 685*481dde66SAndroid Build Coastguard Worker} 686*481dde66SAndroid Build Coastguard Worker``` 687*481dde66SAndroid Build Coastguard Worker 688*481dde66SAndroid Build Coastguard WorkerBy the way, the other situation where an expectation may *not* be sticky is when 689*481dde66SAndroid Build Coastguard Workerit's in a sequence - as soon as another expectation that comes after it in the 690*481dde66SAndroid Build Coastguard Workersequence has been used, it automatically retires (and will never be used to 691*481dde66SAndroid Build Coastguard Workermatch any call). 692*481dde66SAndroid Build Coastguard Worker 693*481dde66SAndroid Build Coastguard Worker### Uninteresting Calls 694*481dde66SAndroid Build Coastguard Worker 695*481dde66SAndroid Build Coastguard WorkerA mock object may have many methods, and not all of them are that interesting. 696*481dde66SAndroid Build Coastguard WorkerFor example, in some tests we may not care about how many times `GetX()` and 697*481dde66SAndroid Build Coastguard Worker`GetY()` get called. 698*481dde66SAndroid Build Coastguard Worker 699*481dde66SAndroid Build Coastguard WorkerIn gMock, if you are not interested in a method, just don't say anything about 700*481dde66SAndroid Build Coastguard Workerit. If a call to this method occurs, you'll see a warning in the test output, 701*481dde66SAndroid Build Coastguard Workerbut it won't be a failure. This is called "naggy" behavior; to change, see 702*481dde66SAndroid Build Coastguard Worker[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy). 703