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