xref: /freebsd/contrib/googletest/docs/gmock_for_dummies.md (revision 5ca8c28cd8c725b81781201cfdb5f9969396f934)
128f6c2f2SEnji Cooper# gMock for Dummies
228f6c2f2SEnji Cooper
328f6c2f2SEnji Cooper## What Is gMock?
428f6c2f2SEnji Cooper
528f6c2f2SEnji CooperWhen you write a prototype or test, often it's not feasible or wise to rely on
628f6c2f2SEnji Cooperreal objects entirely. A **mock object** implements the same interface as a real
728f6c2f2SEnji Cooperobject (so it can be used as one), but lets you specify at run time how it will
828f6c2f2SEnji Cooperbe used and what it should do (which methods will be called? in which order? how
928f6c2f2SEnji Coopermany times? with what arguments? what will they return? etc).
1028f6c2f2SEnji Cooper
1128f6c2f2SEnji CooperIt is easy to confuse the term *fake objects* with mock objects. Fakes and mocks
1228f6c2f2SEnji Cooperactually mean very different things in the Test-Driven Development (TDD)
1328f6c2f2SEnji Coopercommunity:
1428f6c2f2SEnji Cooper
1528f6c2f2SEnji Cooper*   **Fake** objects have working implementations, but usually take some
1628f6c2f2SEnji Cooper    shortcut (perhaps to make the operations less expensive), which makes them
1728f6c2f2SEnji Cooper    not suitable for production. An in-memory file system would be an example of
1828f6c2f2SEnji Cooper    a fake.
1928f6c2f2SEnji Cooper*   **Mocks** are objects pre-programmed with *expectations*, which form a
2028f6c2f2SEnji Cooper    specification of the calls they are expected to receive.
2128f6c2f2SEnji Cooper
2228f6c2f2SEnji CooperIf all this seems too abstract for you, don't worry - the most important thing
2328f6c2f2SEnji Cooperto remember is that a mock allows you to check the *interaction* between itself
2428f6c2f2SEnji Cooperand code that uses it. The difference between fakes and mocks shall become much
2528f6c2f2SEnji Cooperclearer once you start to use mocks.
2628f6c2f2SEnji Cooper
2728f6c2f2SEnji Cooper**gMock** is a library (sometimes we also call it a "framework" to make it sound
2828f6c2f2SEnji Coopercool) for creating mock classes and using them. It does to C++ what
2928f6c2f2SEnji CooperjMock/EasyMock does to Java (well, more or less).
3028f6c2f2SEnji Cooper
3128f6c2f2SEnji CooperWhen using gMock,
3228f6c2f2SEnji Cooper
3328f6c2f2SEnji Cooper1.  first, you use some simple macros to describe the interface you want to
3428f6c2f2SEnji Cooper    mock, and they will expand to the implementation of your mock class;
3528f6c2f2SEnji Cooper2.  next, you create some mock objects and specify its expectations and behavior
3628f6c2f2SEnji Cooper    using an intuitive syntax;
3728f6c2f2SEnji Cooper3.  then you exercise code that uses the mock objects. gMock will catch any
3828f6c2f2SEnji Cooper    violation to the expectations as soon as it arises.
3928f6c2f2SEnji Cooper
4028f6c2f2SEnji Cooper## Why gMock?
4128f6c2f2SEnji Cooper
4228f6c2f2SEnji CooperWhile mock objects help you remove unnecessary dependencies in tests and make
4328f6c2f2SEnji Cooperthem fast and reliable, using mocks manually in C++ is *hard*:
4428f6c2f2SEnji Cooper
4528f6c2f2SEnji Cooper*   Someone has to implement the mocks. The job is usually tedious and
4628f6c2f2SEnji Cooper    error-prone. No wonder people go great distance to avoid it.
4728f6c2f2SEnji Cooper*   The quality of those manually written mocks is a bit, uh, unpredictable. You
4828f6c2f2SEnji Cooper    may see some really polished ones, but you may also see some that were
4928f6c2f2SEnji Cooper    hacked up in a hurry and have all sorts of ad hoc restrictions.
5028f6c2f2SEnji Cooper*   The knowledge you gained from using one mock doesn't transfer to the next
5128f6c2f2SEnji Cooper    one.
5228f6c2f2SEnji Cooper
5328f6c2f2SEnji CooperIn contrast, Java and Python programmers have some fine mock frameworks (jMock,
5428f6c2f2SEnji CooperEasyMock, etc), which automate the creation of mocks. As a result, mocking is a
5528f6c2f2SEnji Cooperproven effective technique and widely adopted practice in those communities.
5628f6c2f2SEnji CooperHaving the right tool absolutely makes the difference.
5728f6c2f2SEnji Cooper
5828f6c2f2SEnji CoopergMock was built to help C++ programmers. It was inspired by jMock and EasyMock,
5928f6c2f2SEnji Cooperbut designed with C++'s specifics in mind. It is your friend if any of the
6028f6c2f2SEnji Cooperfollowing problems is bothering you:
6128f6c2f2SEnji Cooper
6228f6c2f2SEnji Cooper*   You are stuck with a sub-optimal design and wish you had done more
6328f6c2f2SEnji Cooper    prototyping before it was too late, but prototyping in C++ is by no means
6428f6c2f2SEnji Cooper    "rapid".
6528f6c2f2SEnji Cooper*   Your tests are slow as they depend on too many libraries or use expensive
6628f6c2f2SEnji Cooper    resources (e.g. a database).
6728f6c2f2SEnji Cooper*   Your tests are brittle as some resources they use are unreliable (e.g. the
6828f6c2f2SEnji Cooper    network).
6928f6c2f2SEnji Cooper*   You want to test how your code handles a failure (e.g. a file checksum
7028f6c2f2SEnji Cooper    error), but it's not easy to cause one.
7128f6c2f2SEnji Cooper*   You need to make sure that your module interacts with other modules in the
7228f6c2f2SEnji Cooper    right way, but it's hard to observe the interaction; therefore you resort to
7328f6c2f2SEnji Cooper    observing the side effects at the end of the action, but it's awkward at
7428f6c2f2SEnji Cooper    best.
7528f6c2f2SEnji Cooper*   You want to "mock out" your dependencies, except that they don't have mock
7628f6c2f2SEnji Cooper    implementations yet; and, frankly, you aren't thrilled by some of those
7728f6c2f2SEnji Cooper    hand-written mocks.
7828f6c2f2SEnji Cooper
7928f6c2f2SEnji CooperWe encourage you to use gMock as
8028f6c2f2SEnji Cooper
8128f6c2f2SEnji Cooper*   a *design* tool, for it lets you experiment with your interface design early
8228f6c2f2SEnji Cooper    and often. More iterations lead to better designs!
8328f6c2f2SEnji Cooper*   a *testing* tool to cut your tests' outbound dependencies and probe the
8428f6c2f2SEnji Cooper    interaction between your module and its collaborators.
8528f6c2f2SEnji Cooper
8628f6c2f2SEnji Cooper## Getting Started
8728f6c2f2SEnji Cooper
8828f6c2f2SEnji CoopergMock is bundled with googletest.
8928f6c2f2SEnji Cooper
9028f6c2f2SEnji Cooper## A Case for Mock Turtles
9128f6c2f2SEnji Cooper
9228f6c2f2SEnji CooperLet's look at an example. Suppose you are developing a graphics program that
93*5ca8c28cSEnji Cooperrelies on a [LOGO](https://en.wikipedia.org/wiki/Logo_programming_language)-like
9428f6c2f2SEnji CooperAPI for drawing. How would you test that it does the right thing? Well, you can
9528f6c2f2SEnji Cooperrun it and compare the screen with a golden screen snapshot, but let's admit it:
9628f6c2f2SEnji Coopertests like this are expensive to run and fragile (What if you just upgraded to a
9728f6c2f2SEnji Coopershiny new graphics card that has better anti-aliasing? Suddenly you have to
9828f6c2f2SEnji Cooperupdate all your golden images.). It would be too painful if all your tests are
9928f6c2f2SEnji Cooperlike this. Fortunately, you learned about
100*5ca8c28cSEnji Cooper[Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) and know the right thing
10128f6c2f2SEnji Cooperto do: instead of having your application talk to the system API directly, wrap
10228f6c2f2SEnji Cooperthe API in an interface (say, `Turtle`) and code to that interface:
10328f6c2f2SEnji Cooper
10428f6c2f2SEnji Cooper```cpp
10528f6c2f2SEnji Cooperclass Turtle {
10628f6c2f2SEnji Cooper  ...
10728f6c2f2SEnji Cooper  virtual ~Turtle() {}
10828f6c2f2SEnji Cooper  virtual void PenUp() = 0;
10928f6c2f2SEnji Cooper  virtual void PenDown() = 0;
11028f6c2f2SEnji Cooper  virtual void Forward(int distance) = 0;
11128f6c2f2SEnji Cooper  virtual void Turn(int degrees) = 0;
11228f6c2f2SEnji Cooper  virtual void GoTo(int x, int y) = 0;
11328f6c2f2SEnji Cooper  virtual int GetX() const = 0;
11428f6c2f2SEnji Cooper  virtual int GetY() const = 0;
11528f6c2f2SEnji Cooper};
11628f6c2f2SEnji Cooper```
11728f6c2f2SEnji Cooper
11828f6c2f2SEnji Cooper(Note that the destructor of `Turtle` **must** be virtual, as is the case for
11928f6c2f2SEnji Cooper**all** classes you intend to inherit from - otherwise the destructor of the
12028f6c2f2SEnji Cooperderived class will not be called when you delete an object through a base
12128f6c2f2SEnji Cooperpointer, and you'll get corrupted program states like memory leaks.)
12228f6c2f2SEnji Cooper
12328f6c2f2SEnji CooperYou can control whether the turtle's movement will leave a trace using `PenUp()`
12428f6c2f2SEnji Cooperand `PenDown()`, and control its movement using `Forward()`, `Turn()`, and
12528f6c2f2SEnji Cooper`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the
12628f6c2f2SEnji Cooperturtle.
12728f6c2f2SEnji Cooper
12828f6c2f2SEnji CooperYour program will normally use a real implementation of this interface. In
12928f6c2f2SEnji Coopertests, you can use a mock implementation instead. This allows you to easily
13028f6c2f2SEnji Coopercheck what drawing primitives your program is calling, with what arguments, and
13128f6c2f2SEnji Cooperin which order. Tests written this way are much more robust (they won't break
13228f6c2f2SEnji Cooperbecause your new machine does anti-aliasing differently), easier to read and
13328f6c2f2SEnji Coopermaintain (the intent of a test is expressed in the code, not in some binary
13428f6c2f2SEnji Cooperimages), and run *much, much faster*.
13528f6c2f2SEnji Cooper
13628f6c2f2SEnji Cooper## Writing the Mock Class
13728f6c2f2SEnji Cooper
13828f6c2f2SEnji CooperIf you are lucky, the mocks you need to use have already been implemented by
13928f6c2f2SEnji Coopersome nice people. If, however, you find yourself in the position to write a mock
14028f6c2f2SEnji Cooperclass, relax - gMock turns this task into a fun game! (Well, almost.)
14128f6c2f2SEnji Cooper
14228f6c2f2SEnji Cooper### How to Define It
14328f6c2f2SEnji Cooper
14428f6c2f2SEnji CooperUsing the `Turtle` interface as example, here are the simple steps you need to
14528f6c2f2SEnji Cooperfollow:
14628f6c2f2SEnji Cooper
14728f6c2f2SEnji Cooper*   Derive a class `MockTurtle` from `Turtle`.
14828f6c2f2SEnji Cooper*   Take a *virtual* function of `Turtle` (while it's possible to
14928f6c2f2SEnji Cooper    [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods),
15028f6c2f2SEnji Cooper    it's much more involved).
15128f6c2f2SEnji Cooper*   In the `public:` section of the child class, write `MOCK_METHOD();`
15228f6c2f2SEnji Cooper*   Now comes the fun part: you take the function signature, cut-and-paste it
15328f6c2f2SEnji Cooper    into the macro, and add two commas - one between the return type and the
15428f6c2f2SEnji Cooper    name, another between the name and the argument list.
15528f6c2f2SEnji Cooper*   If you're mocking a const method, add a 4th parameter containing `(const)`
15628f6c2f2SEnji Cooper    (the parentheses are required).
15728f6c2f2SEnji Cooper*   Since you're overriding a virtual method, we suggest adding the `override`
15828f6c2f2SEnji Cooper    keyword. For const methods the 4th parameter becomes `(const, override)`,
15928f6c2f2SEnji Cooper    for non-const methods just `(override)`. This isn't mandatory.
16028f6c2f2SEnji Cooper*   Repeat until all virtual functions you want to mock are done. (It goes
16128f6c2f2SEnji Cooper    without saying that *all* pure virtual methods in your abstract class must
16228f6c2f2SEnji Cooper    be either mocked or overridden.)
16328f6c2f2SEnji Cooper
16428f6c2f2SEnji CooperAfter the process, you should have something like:
16528f6c2f2SEnji Cooper
16628f6c2f2SEnji Cooper```cpp
16728f6c2f2SEnji Cooper#include <gmock/gmock.h>  // Brings in gMock.
16828f6c2f2SEnji Cooper
16928f6c2f2SEnji Cooperclass MockTurtle : public Turtle {
17028f6c2f2SEnji Cooper public:
17128f6c2f2SEnji Cooper  ...
17228f6c2f2SEnji Cooper  MOCK_METHOD(void, PenUp, (), (override));
17328f6c2f2SEnji Cooper  MOCK_METHOD(void, PenDown, (), (override));
17428f6c2f2SEnji Cooper  MOCK_METHOD(void, Forward, (int distance), (override));
17528f6c2f2SEnji Cooper  MOCK_METHOD(void, Turn, (int degrees), (override));
17628f6c2f2SEnji Cooper  MOCK_METHOD(void, GoTo, (int x, int y), (override));
17728f6c2f2SEnji Cooper  MOCK_METHOD(int, GetX, (), (const, override));
17828f6c2f2SEnji Cooper  MOCK_METHOD(int, GetY, (), (const, override));
17928f6c2f2SEnji Cooper};
18028f6c2f2SEnji Cooper```
18128f6c2f2SEnji Cooper
18228f6c2f2SEnji CooperYou don't need to define these mock methods somewhere else - the `MOCK_METHOD`
18328f6c2f2SEnji Coopermacro will generate the definitions for you. It's that simple!
18428f6c2f2SEnji Cooper
18528f6c2f2SEnji Cooper### Where to Put It
18628f6c2f2SEnji Cooper
18728f6c2f2SEnji CooperWhen you define a mock class, you need to decide where to put its definition.
18828f6c2f2SEnji CooperSome people put it in a `_test.cc`. This is fine when the interface being mocked
18928f6c2f2SEnji Cooper(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of
19028f6c2f2SEnji Cooper`Foo` changes it, your test could break. (You can't really expect `Foo`'s
19128f6c2f2SEnji Coopermaintainer to fix every test that uses `Foo`, can you?)
19228f6c2f2SEnji Cooper
19328f6c2f2SEnji CooperGenerally, you should not mock classes you don't own. If you must mock such a
19428f6c2f2SEnji Cooperclass owned by others, define the mock class in `Foo`'s Bazel package (usually
19528f6c2f2SEnji Cooperthe same directory or a `testing` sub-directory), and put it in a `.h` and a
19628f6c2f2SEnji Cooper`cc_library` with `testonly=True`. Then everyone can reference them from their
19728f6c2f2SEnji Coopertests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and
19828f6c2f2SEnji Cooperonly tests that depend on the changed methods need to be fixed.
19928f6c2f2SEnji Cooper
20028f6c2f2SEnji CooperAnother way to do it: you can introduce a thin layer `FooAdaptor` on top of
20128f6c2f2SEnji Cooper`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb
20228f6c2f2SEnji Cooperchanges in `Foo` much more easily. While this is more work initially, carefully
20328f6c2f2SEnji Cooperchoosing the adaptor interface can make your code easier to write and more
20428f6c2f2SEnji Cooperreadable (a net win in the long run), as you can choose `FooAdaptor` to fit your
20528f6c2f2SEnji Cooperspecific domain much better than `Foo` does.
20628f6c2f2SEnji Cooper
20728f6c2f2SEnji Cooper## Using Mocks in Tests
20828f6c2f2SEnji Cooper
20928f6c2f2SEnji CooperOnce you have a mock class, using it is easy. The typical work flow is:
21028f6c2f2SEnji Cooper
21128f6c2f2SEnji Cooper1.  Import the gMock names from the `testing` namespace such that you can use
21228f6c2f2SEnji Cooper    them unqualified (You only have to do it once per file). Remember that
21328f6c2f2SEnji Cooper    namespaces are a good idea.
21428f6c2f2SEnji Cooper2.  Create some mock objects.
21528f6c2f2SEnji Cooper3.  Specify your expectations on them (How many times will a method be called?
21628f6c2f2SEnji Cooper    With what arguments? What should it do? etc.).
21728f6c2f2SEnji Cooper4.  Exercise some code that uses the mocks; optionally, check the result using
21828f6c2f2SEnji Cooper    googletest assertions. If a mock method is called more than expected or with
21928f6c2f2SEnji Cooper    wrong arguments, you'll get an error immediately.
22028f6c2f2SEnji Cooper5.  When a mock is destructed, gMock will automatically check whether all
22128f6c2f2SEnji Cooper    expectations on it have been satisfied.
22228f6c2f2SEnji Cooper
22328f6c2f2SEnji CooperHere's an example:
22428f6c2f2SEnji Cooper
22528f6c2f2SEnji Cooper```cpp
22628f6c2f2SEnji Cooper#include "path/to/mock-turtle.h"
22728f6c2f2SEnji Cooper#include <gmock/gmock.h>
22828f6c2f2SEnji Cooper#include <gtest/gtest.h>
22928f6c2f2SEnji Cooper
23028f6c2f2SEnji Cooperusing ::testing::AtLeast;                         // #1
23128f6c2f2SEnji Cooper
23228f6c2f2SEnji CooperTEST(PainterTest, CanDrawSomething) {
23328f6c2f2SEnji Cooper  MockTurtle turtle;                              // #2
23428f6c2f2SEnji Cooper  EXPECT_CALL(turtle, PenDown())                  // #3
23528f6c2f2SEnji Cooper      .Times(AtLeast(1));
23628f6c2f2SEnji Cooper
23728f6c2f2SEnji Cooper  Painter painter(&turtle);                       // #4
23828f6c2f2SEnji Cooper
23928f6c2f2SEnji Cooper  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));      // #5
24028f6c2f2SEnji Cooper}
24128f6c2f2SEnji Cooper```
24228f6c2f2SEnji Cooper
24328f6c2f2SEnji CooperAs you might have guessed, this test checks that `PenDown()` is called at least
24428f6c2f2SEnji Cooperonce. If the `painter` object didn't call this method, your test will fail with
24528f6c2f2SEnji Coopera message like this:
24628f6c2f2SEnji Cooper
24728f6c2f2SEnji Cooper```text
24828f6c2f2SEnji Cooperpath/to/my_test.cc:119: Failure
24928f6c2f2SEnji CooperActual function call count doesn't match this expectation:
25028f6c2f2SEnji CooperActually: never called;
25128f6c2f2SEnji CooperExpected: called at least once.
25228f6c2f2SEnji CooperStack trace:
25328f6c2f2SEnji Cooper...
25428f6c2f2SEnji Cooper```
25528f6c2f2SEnji Cooper
25628f6c2f2SEnji Cooper**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on
25728f6c2f2SEnji Cooperthe line number to jump right to the failed expectation.
25828f6c2f2SEnji Cooper
25928f6c2f2SEnji Cooper**Tip 2:** If your mock objects are never deleted, the final verification won't
26028f6c2f2SEnji Cooperhappen. Therefore it's a good idea to turn on the heap checker in your tests
26128f6c2f2SEnji Cooperwhen you allocate mocks on the heap. You get that automatically if you use the
26228f6c2f2SEnji Cooper`gtest_main` library already.
26328f6c2f2SEnji Cooper
264*5ca8c28cSEnji Cooper###### Expectation Ordering
265*5ca8c28cSEnji Cooper
26628f6c2f2SEnji Cooper**Important note:** gMock requires expectations to be set **before** the mock
26728f6c2f2SEnji Cooperfunctions are called, otherwise the behavior is **undefined**. Do not alternate
26828f6c2f2SEnji Cooperbetween calls to `EXPECT_CALL()` and calls to the mock functions, and do not set
26928f6c2f2SEnji Cooperany expectations on a mock after passing the mock to an API.
27028f6c2f2SEnji Cooper
27128f6c2f2SEnji CooperThis means `EXPECT_CALL()` should be read as expecting that a call will occur
27228f6c2f2SEnji Cooper*in the future*, not that a call has occurred. Why does gMock work like that?
27328f6c2f2SEnji CooperWell, specifying the expectation beforehand allows gMock to report a violation
27428f6c2f2SEnji Cooperas soon as it rises, when the context (stack trace, etc) is still available.
27528f6c2f2SEnji CooperThis makes debugging much easier.
27628f6c2f2SEnji Cooper
27728f6c2f2SEnji CooperAdmittedly, this test is contrived and doesn't do much. You can easily achieve
27828f6c2f2SEnji Cooperthe same effect without using gMock. However, as we shall reveal soon, gMock
27928f6c2f2SEnji Cooperallows you to do *so much more* with the mocks.
28028f6c2f2SEnji Cooper
28128f6c2f2SEnji Cooper## Setting Expectations
28228f6c2f2SEnji Cooper
28328f6c2f2SEnji CooperThe key to using a mock object successfully is to set the *right expectations*
28428f6c2f2SEnji Cooperon it. If you set the expectations too strict, your test will fail as the result
28528f6c2f2SEnji Cooperof unrelated changes. If you set them too loose, bugs can slip through. You want
28628f6c2f2SEnji Cooperto do it just right such that your test can catch exactly the kind of bugs you
28728f6c2f2SEnji Cooperintend it to catch. gMock provides the necessary means for you to do it "just
28828f6c2f2SEnji Cooperright."
28928f6c2f2SEnji Cooper
29028f6c2f2SEnji Cooper### General Syntax
29128f6c2f2SEnji Cooper
29228f6c2f2SEnji CooperIn gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock
29328f6c2f2SEnji Coopermethod. The general syntax is:
29428f6c2f2SEnji Cooper
29528f6c2f2SEnji Cooper```cpp
29628f6c2f2SEnji CooperEXPECT_CALL(mock_object, method(matchers))
29728f6c2f2SEnji Cooper    .Times(cardinality)
29828f6c2f2SEnji Cooper    .WillOnce(action)
29928f6c2f2SEnji Cooper    .WillRepeatedly(action);
30028f6c2f2SEnji Cooper```
30128f6c2f2SEnji Cooper
30228f6c2f2SEnji CooperThe macro has two arguments: first the mock object, and then the method and its
30328f6c2f2SEnji Cooperarguments. Note that the two are separated by a comma (`,`), not a period (`.`).
30428f6c2f2SEnji Cooper(Why using a comma? The answer is that it was necessary for technical reasons.)
30528f6c2f2SEnji CooperIf the method is not overloaded, the macro can also be called without matchers:
30628f6c2f2SEnji Cooper
30728f6c2f2SEnji Cooper```cpp
30828f6c2f2SEnji CooperEXPECT_CALL(mock_object, non-overloaded-method)
30928f6c2f2SEnji Cooper    .Times(cardinality)
31028f6c2f2SEnji Cooper    .WillOnce(action)
31128f6c2f2SEnji Cooper    .WillRepeatedly(action);
31228f6c2f2SEnji Cooper```
31328f6c2f2SEnji Cooper
31428f6c2f2SEnji CooperThis syntax allows the test writer to specify "called with any arguments"
31528f6c2f2SEnji Cooperwithout explicitly specifying the number or types of arguments. To avoid
31628f6c2f2SEnji Cooperunintended ambiguity, this syntax may only be used for methods that are not
31728f6c2f2SEnji Cooperoverloaded.
31828f6c2f2SEnji Cooper
31928f6c2f2SEnji CooperEither form of the macro can be followed by some optional *clauses* that provide
32028f6c2f2SEnji Coopermore information about the expectation. We'll discuss how each clause works in
32128f6c2f2SEnji Cooperthe coming sections.
32228f6c2f2SEnji Cooper
32328f6c2f2SEnji CooperThis syntax is designed to make an expectation read like English. For example,
32428f6c2f2SEnji Cooperyou can probably guess that
32528f6c2f2SEnji Cooper
32628f6c2f2SEnji Cooper```cpp
32728f6c2f2SEnji Cooperusing ::testing::Return;
32828f6c2f2SEnji Cooper...
32928f6c2f2SEnji CooperEXPECT_CALL(turtle, GetX())
33028f6c2f2SEnji Cooper    .Times(5)
33128f6c2f2SEnji Cooper    .WillOnce(Return(100))
33228f6c2f2SEnji Cooper    .WillOnce(Return(150))
33328f6c2f2SEnji Cooper    .WillRepeatedly(Return(200));
33428f6c2f2SEnji Cooper```
33528f6c2f2SEnji Cooper
33628f6c2f2SEnji Coopersays that the `turtle` object's `GetX()` method will be called five times, it
33728f6c2f2SEnji Cooperwill return 100 the first time, 150 the second time, and then 200 every time.
33828f6c2f2SEnji CooperSome people like to call this style of syntax a Domain-Specific Language (DSL).
33928f6c2f2SEnji Cooper
34028f6c2f2SEnji Cooper{: .callout .note}
34128f6c2f2SEnji Cooper**Note:** Why do we use a macro to do this? Well it serves two purposes: first
34228f6c2f2SEnji Cooperit makes expectations easily identifiable (either by `grep` or by a human
34328f6c2f2SEnji Cooperreader), and second it allows gMock to include the source file location of a
34428f6c2f2SEnji Cooperfailed expectation in messages, making debugging easier.
34528f6c2f2SEnji Cooper
34628f6c2f2SEnji Cooper### Matchers: What Arguments Do We Expect?
34728f6c2f2SEnji Cooper
34828f6c2f2SEnji CooperWhen a mock function takes arguments, we may specify what arguments we are
34928f6c2f2SEnji Cooperexpecting, for example:
35028f6c2f2SEnji Cooper
35128f6c2f2SEnji Cooper```cpp
35228f6c2f2SEnji Cooper// Expects the turtle to move forward by 100 units.
35328f6c2f2SEnji CooperEXPECT_CALL(turtle, Forward(100));
35428f6c2f2SEnji Cooper```
35528f6c2f2SEnji Cooper
35628f6c2f2SEnji CooperOftentimes you do not want to be too specific. Remember that talk about tests
35728f6c2f2SEnji Cooperbeing too rigid? Over specification leads to brittle tests and obscures the
35828f6c2f2SEnji Cooperintent of tests. Therefore we encourage you to specify only what's necessary—no
35928f6c2f2SEnji Coopermore, no less. If you aren't interested in the value of an argument, write `_`
36028f6c2f2SEnji Cooperas the argument, which means "anything goes":
36128f6c2f2SEnji Cooper
36228f6c2f2SEnji Cooper```cpp
36328f6c2f2SEnji Cooperusing ::testing::_;
36428f6c2f2SEnji Cooper...
36528f6c2f2SEnji Cooper// Expects that the turtle jumps to somewhere on the x=50 line.
36628f6c2f2SEnji CooperEXPECT_CALL(turtle, GoTo(50, _));
36728f6c2f2SEnji Cooper```
36828f6c2f2SEnji Cooper
36928f6c2f2SEnji Cooper`_` is an instance of what we call **matchers**. A matcher is like a predicate
37028f6c2f2SEnji Cooperand can test whether an argument is what we'd expect. You can use a matcher
37128f6c2f2SEnji Cooperinside `EXPECT_CALL()` wherever a function argument is expected. `_` is a
37228f6c2f2SEnji Cooperconvenient way of saying "any value".
37328f6c2f2SEnji Cooper
37428f6c2f2SEnji CooperIn the above examples, `100` and `50` are also matchers; implicitly, they are
37528f6c2f2SEnji Cooperthe same as `Eq(100)` and `Eq(50)`, which specify that the argument must be
37628f6c2f2SEnji Cooperequal (using `operator==`) to the matcher argument. There are many
37728f6c2f2SEnji Cooper[built-in matchers](reference/matchers.md) for common types (as well as
37828f6c2f2SEnji Cooper[custom matchers](gmock_cook_book.md#NewMatchers)); for example:
37928f6c2f2SEnji Cooper
38028f6c2f2SEnji Cooper```cpp
38128f6c2f2SEnji Cooperusing ::testing::Ge;
38228f6c2f2SEnji Cooper...
38328f6c2f2SEnji Cooper// Expects the turtle moves forward by at least 100.
38428f6c2f2SEnji CooperEXPECT_CALL(turtle, Forward(Ge(100)));
38528f6c2f2SEnji Cooper```
38628f6c2f2SEnji Cooper
38728f6c2f2SEnji CooperIf you don't care about *any* arguments, rather than specify `_` for each of
38828f6c2f2SEnji Cooperthem you may instead omit the parameter list:
38928f6c2f2SEnji Cooper
39028f6c2f2SEnji Cooper```cpp
39128f6c2f2SEnji Cooper// Expects the turtle to move forward.
39228f6c2f2SEnji CooperEXPECT_CALL(turtle, Forward);
39328f6c2f2SEnji Cooper// Expects the turtle to jump somewhere.
39428f6c2f2SEnji CooperEXPECT_CALL(turtle, GoTo);
39528f6c2f2SEnji Cooper```
39628f6c2f2SEnji Cooper
39728f6c2f2SEnji CooperThis works for all non-overloaded methods; if a method is overloaded, you need
39828f6c2f2SEnji Cooperto help gMock resolve which overload is expected by specifying the number of
39928f6c2f2SEnji Cooperarguments and possibly also the
40028f6c2f2SEnji Cooper[types of the arguments](gmock_cook_book.md#SelectOverload).
40128f6c2f2SEnji Cooper
40228f6c2f2SEnji Cooper### Cardinalities: How Many Times Will It Be Called?
40328f6c2f2SEnji Cooper
40428f6c2f2SEnji CooperThe first clause we can specify following an `EXPECT_CALL()` is `Times()`. We
40528f6c2f2SEnji Coopercall its argument a **cardinality** as it tells *how many times* the call should
40628f6c2f2SEnji Cooperoccur. It allows us to repeat an expectation many times without actually writing
40728f6c2f2SEnji Cooperit as many times. More importantly, a cardinality can be "fuzzy", just like a
40828f6c2f2SEnji Coopermatcher can be. This allows a user to express the intent of a test exactly.
40928f6c2f2SEnji Cooper
41028f6c2f2SEnji CooperAn interesting special case is when we say `Times(0)`. You may have guessed - it
41128f6c2f2SEnji Coopermeans that the function shouldn't be called with the given arguments at all, and
41228f6c2f2SEnji CoopergMock will report a googletest failure whenever the function is (wrongfully)
41328f6c2f2SEnji Coopercalled.
41428f6c2f2SEnji Cooper
41528f6c2f2SEnji CooperWe've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the
41628f6c2f2SEnji Cooperlist of built-in cardinalities you can use, see
41728f6c2f2SEnji Cooper[here](gmock_cheat_sheet.md#CardinalityList).
41828f6c2f2SEnji Cooper
41928f6c2f2SEnji CooperThe `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer
42028f6c2f2SEnji Cooperthe cardinality for you.** The rules are easy to remember:
42128f6c2f2SEnji Cooper
42228f6c2f2SEnji Cooper*   If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the
42328f6c2f2SEnji Cooper    `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
42428f6c2f2SEnji Cooper*   If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >=
42528f6c2f2SEnji Cooper    1, the cardinality is `Times(n)`.
42628f6c2f2SEnji Cooper*   If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >=
42728f6c2f2SEnji Cooper    0, the cardinality is `Times(AtLeast(n))`.
42828f6c2f2SEnji Cooper
42928f6c2f2SEnji Cooper**Quick quiz:** what do you think will happen if a function is expected to be
43028f6c2f2SEnji Coopercalled twice but actually called four times?
43128f6c2f2SEnji Cooper
43228f6c2f2SEnji Cooper### Actions: What Should It Do?
43328f6c2f2SEnji Cooper
43428f6c2f2SEnji CooperRemember that a mock object doesn't really have a working implementation? We as
43528f6c2f2SEnji Cooperusers have to tell it what to do when a method is invoked. This is easy in
43628f6c2f2SEnji CoopergMock.
43728f6c2f2SEnji Cooper
43828f6c2f2SEnji CooperFirst, if the return type of a mock function is a built-in type or a pointer,
43928f6c2f2SEnji Cooperthe function has a **default action** (a `void` function will just return, a
44028f6c2f2SEnji Cooper`bool` function will return `false`, and other functions will return 0). In
44128f6c2f2SEnji Cooperaddition, in C++ 11 and above, a mock function whose return type is
44228f6c2f2SEnji Cooperdefault-constructible (i.e. has a default constructor) has a default action of
44328f6c2f2SEnji Cooperreturning a default-constructed value. If you don't say anything, this behavior
44428f6c2f2SEnji Cooperwill be used.
44528f6c2f2SEnji Cooper
44628f6c2f2SEnji CooperSecond, if a mock function doesn't have a default action, or the default action
44728f6c2f2SEnji Cooperdoesn't suit you, you can specify the action to be taken each time the
44828f6c2f2SEnji Cooperexpectation matches using a series of `WillOnce()` clauses followed by an
44928f6c2f2SEnji Cooperoptional `WillRepeatedly()`. For example,
45028f6c2f2SEnji Cooper
45128f6c2f2SEnji Cooper```cpp
45228f6c2f2SEnji Cooperusing ::testing::Return;
45328f6c2f2SEnji Cooper...
45428f6c2f2SEnji CooperEXPECT_CALL(turtle, GetX())
45528f6c2f2SEnji Cooper     .WillOnce(Return(100))
45628f6c2f2SEnji Cooper     .WillOnce(Return(200))
45728f6c2f2SEnji Cooper     .WillOnce(Return(300));
45828f6c2f2SEnji Cooper```
45928f6c2f2SEnji Cooper
46028f6c2f2SEnji Coopersays that `turtle.GetX()` will be called *exactly three times* (gMock inferred
46128f6c2f2SEnji Cooperthis from how many `WillOnce()` clauses we've written, since we didn't
46228f6c2f2SEnji Cooperexplicitly write `Times()`), and will return 100, 200, and 300 respectively.
46328f6c2f2SEnji Cooper
46428f6c2f2SEnji Cooper```cpp
46528f6c2f2SEnji Cooperusing ::testing::Return;
46628f6c2f2SEnji Cooper...
46728f6c2f2SEnji CooperEXPECT_CALL(turtle, GetY())
46828f6c2f2SEnji Cooper     .WillOnce(Return(100))
46928f6c2f2SEnji Cooper     .WillOnce(Return(200))
47028f6c2f2SEnji Cooper     .WillRepeatedly(Return(300));
47128f6c2f2SEnji Cooper```
47228f6c2f2SEnji Cooper
47328f6c2f2SEnji Coopersays that `turtle.GetY()` will be called *at least twice* (gMock knows this as
47428f6c2f2SEnji Cooperwe've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no
47528f6c2f2SEnji Cooperexplicit `Times()`), will return 100 and 200 respectively the first two times,
47628f6c2f2SEnji Cooperand 300 from the third time on.
47728f6c2f2SEnji Cooper
47828f6c2f2SEnji CooperOf course, if you explicitly write a `Times()`, gMock will not try to infer the
47928f6c2f2SEnji Coopercardinality itself. What if the number you specified is larger than there are
48028f6c2f2SEnji Cooper`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do
48128f6c2f2SEnji Cooperthe *default* action for the function every time (unless, of course, you have a
48228f6c2f2SEnji Cooper`WillRepeatedly()`.).
48328f6c2f2SEnji Cooper
48428f6c2f2SEnji CooperWhat can we do inside `WillOnce()` besides `Return()`? You can return a
48528f6c2f2SEnji Cooperreference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function,
48628f6c2f2SEnji Cooperamong [others](gmock_cook_book.md#using-actions).
48728f6c2f2SEnji Cooper
48828f6c2f2SEnji Cooper**Important note:** The `EXPECT_CALL()` statement evaluates the action clause
48928f6c2f2SEnji Cooperonly once, even though the action may be performed many times. Therefore you
49028f6c2f2SEnji Coopermust be careful about side effects. The following may not do what you want:
49128f6c2f2SEnji Cooper
49228f6c2f2SEnji Cooper```cpp
49328f6c2f2SEnji Cooperusing ::testing::Return;
49428f6c2f2SEnji Cooper...
49528f6c2f2SEnji Cooperint n = 100;
49628f6c2f2SEnji CooperEXPECT_CALL(turtle, GetX())
49728f6c2f2SEnji Cooper    .Times(4)
49828f6c2f2SEnji Cooper    .WillRepeatedly(Return(n++));
49928f6c2f2SEnji Cooper```
50028f6c2f2SEnji Cooper
50128f6c2f2SEnji CooperInstead of returning 100, 101, 102, ..., consecutively, this mock function will
50228f6c2f2SEnji Cooperalways return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)`
50328f6c2f2SEnji Cooperwill create a new `Foo` object when the `EXPECT_CALL()` is executed, and will
50428f6c2f2SEnji Cooperreturn the same pointer every time. If you want the side effect to happen every
50528f6c2f2SEnji Coopertime, you need to define a custom action, which we'll teach in the
50628f6c2f2SEnji Cooper[cook book](gmock_cook_book.md).
50728f6c2f2SEnji Cooper
50828f6c2f2SEnji CooperTime for another quiz! What do you think the following means?
50928f6c2f2SEnji Cooper
51028f6c2f2SEnji Cooper```cpp
51128f6c2f2SEnji Cooperusing ::testing::Return;
51228f6c2f2SEnji Cooper...
51328f6c2f2SEnji CooperEXPECT_CALL(turtle, GetY())
51428f6c2f2SEnji Cooper    .Times(4)
51528f6c2f2SEnji Cooper    .WillOnce(Return(100));
51628f6c2f2SEnji Cooper```
51728f6c2f2SEnji Cooper
51828f6c2f2SEnji CooperObviously `turtle.GetY()` is expected to be called four times. But if you think
51928f6c2f2SEnji Cooperit will return 100 every time, think twice! Remember that one `WillOnce()`
52028f6c2f2SEnji Cooperclause will be consumed each time the function is invoked and the default action
52128f6c2f2SEnji Cooperwill be taken afterwards. So the right answer is that `turtle.GetY()` will
52228f6c2f2SEnji Cooperreturn 100 the first time, but **return 0 from the second time on**, as
52328f6c2f2SEnji Cooperreturning 0 is the default action for `int` functions.
52428f6c2f2SEnji Cooper
52528f6c2f2SEnji Cooper### Using Multiple Expectations {#MultiExpectations}
52628f6c2f2SEnji Cooper
52728f6c2f2SEnji CooperSo far we've only shown examples where you have a single expectation. More
52828f6c2f2SEnji Cooperrealistically, you'll specify expectations on multiple mock methods which may be
52928f6c2f2SEnji Cooperfrom multiple mock objects.
53028f6c2f2SEnji Cooper
53128f6c2f2SEnji CooperBy default, when a mock method is invoked, gMock will search the expectations in
53228f6c2f2SEnji Cooperthe **reverse order** they are defined, and stop when an active expectation that
53328f6c2f2SEnji Coopermatches the arguments is found (you can think of it as "newer rules override
53428f6c2f2SEnji Cooperolder ones."). If the matching expectation cannot take any more calls, you will
53528f6c2f2SEnji Cooperget an upper-bound-violated failure. Here's an example:
53628f6c2f2SEnji Cooper
53728f6c2f2SEnji Cooper```cpp
53828f6c2f2SEnji Cooperusing ::testing::_;
53928f6c2f2SEnji Cooper...
54028f6c2f2SEnji CooperEXPECT_CALL(turtle, Forward(_));  // #1
54128f6c2f2SEnji CooperEXPECT_CALL(turtle, Forward(10))  // #2
54228f6c2f2SEnji Cooper    .Times(2);
54328f6c2f2SEnji Cooper```
54428f6c2f2SEnji Cooper
54528f6c2f2SEnji CooperIf `Forward(10)` is called three times in a row, the third time it will be an
54628f6c2f2SEnji Coopererror, as the last matching expectation (#2) has been saturated. If, however,
54728f6c2f2SEnji Cooperthe third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK,
54828f6c2f2SEnji Cooperas now #1 will be the matching expectation.
54928f6c2f2SEnji Cooper
55028f6c2f2SEnji Cooper{: .callout .note}
55128f6c2f2SEnji Cooper**Note:** Why does gMock search for a match in the *reverse* order of the
55228f6c2f2SEnji Cooperexpectations? The reason is that this allows a user to set up the default
55328f6c2f2SEnji Cooperexpectations in a mock object's constructor or the test fixture's set-up phase
55428f6c2f2SEnji Cooperand then customize the mock by writing more specific expectations in the test
55528f6c2f2SEnji Cooperbody. So, if you have two expectations on the same method, you want to put the
55628f6c2f2SEnji Cooperone with more specific matchers **after** the other, or the more specific rule
55728f6c2f2SEnji Cooperwould be shadowed by the more general one that comes after it.
55828f6c2f2SEnji Cooper
55928f6c2f2SEnji Cooper{: .callout .tip}
56028f6c2f2SEnji Cooper**Tip:** It is very common to start with a catch-all expectation for a method
56128f6c2f2SEnji Cooperand `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if
56228f6c2f2SEnji Cooperoverloaded). This makes any calls to the method expected. This is not necessary
56328f6c2f2SEnji Cooperfor methods that are not mentioned at all (these are "uninteresting"), but is
56428f6c2f2SEnji Cooperuseful for methods that have some expectations, but for which other calls are
56528f6c2f2SEnji Cooperok. See
56628f6c2f2SEnji Cooper[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected).
56728f6c2f2SEnji Cooper
56828f6c2f2SEnji Cooper### Ordered vs Unordered Calls {#OrderedCalls}
56928f6c2f2SEnji Cooper
57028f6c2f2SEnji CooperBy default, an expectation can match a call even though an earlier expectation
57128f6c2f2SEnji Cooperhasn't been satisfied. In other words, the calls don't have to occur in the
57228f6c2f2SEnji Cooperorder the expectations are specified.
57328f6c2f2SEnji Cooper
57428f6c2f2SEnji CooperSometimes, you may want all the expected calls to occur in a strict order. To
57528f6c2f2SEnji Coopersay this in gMock is easy:
57628f6c2f2SEnji Cooper
57728f6c2f2SEnji Cooper```cpp
57828f6c2f2SEnji Cooperusing ::testing::InSequence;
57928f6c2f2SEnji Cooper...
58028f6c2f2SEnji CooperTEST(FooTest, DrawsLineSegment) {
58128f6c2f2SEnji Cooper  ...
58228f6c2f2SEnji Cooper  {
58328f6c2f2SEnji Cooper    InSequence seq;
58428f6c2f2SEnji Cooper
58528f6c2f2SEnji Cooper    EXPECT_CALL(turtle, PenDown());
58628f6c2f2SEnji Cooper    EXPECT_CALL(turtle, Forward(100));
58728f6c2f2SEnji Cooper    EXPECT_CALL(turtle, PenUp());
58828f6c2f2SEnji Cooper  }
58928f6c2f2SEnji Cooper  Foo();
59028f6c2f2SEnji Cooper}
59128f6c2f2SEnji Cooper```
59228f6c2f2SEnji Cooper
59328f6c2f2SEnji CooperBy creating an object of type `InSequence`, all expectations in its scope are
59428f6c2f2SEnji Cooperput into a *sequence* and have to occur *sequentially*. Since we are just
59528f6c2f2SEnji Cooperrelying on the constructor and destructor of this object to do the actual work,
59628f6c2f2SEnji Cooperits name is really irrelevant.
59728f6c2f2SEnji Cooper
59828f6c2f2SEnji CooperIn this example, we test that `Foo()` calls the three expected functions in the
59928f6c2f2SEnji Cooperorder as written. If a call is made out-of-order, it will be an error.
60028f6c2f2SEnji Cooper
60128f6c2f2SEnji Cooper(What if you care about the relative order of some of the calls, but not all of
60228f6c2f2SEnji Cooperthem? Can you specify an arbitrary partial order? The answer is ... yes! The
60328f6c2f2SEnji Cooperdetails can be found [here](gmock_cook_book.md#OrderedCalls).)
60428f6c2f2SEnji Cooper
60528f6c2f2SEnji Cooper### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
60628f6c2f2SEnji Cooper
60728f6c2f2SEnji CooperNow let's do a quick quiz to see how well you can use this mock stuff already.
60828f6c2f2SEnji CooperHow would you test that the turtle is asked to go to the origin *exactly twice*
60928f6c2f2SEnji Cooper(you want to ignore any other instructions it receives)?
61028f6c2f2SEnji Cooper
61128f6c2f2SEnji CooperAfter you've come up with your answer, take a look at ours and compare notes
61228f6c2f2SEnji Cooper(solve it yourself first - don't cheat!):
61328f6c2f2SEnji Cooper
61428f6c2f2SEnji Cooper```cpp
61528f6c2f2SEnji Cooperusing ::testing::_;
61628f6c2f2SEnji Cooperusing ::testing::AnyNumber;
61728f6c2f2SEnji Cooper...
61828f6c2f2SEnji CooperEXPECT_CALL(turtle, GoTo(_, _))  // #1
61928f6c2f2SEnji Cooper     .Times(AnyNumber());
62028f6c2f2SEnji CooperEXPECT_CALL(turtle, GoTo(0, 0))  // #2
62128f6c2f2SEnji Cooper     .Times(2);
62228f6c2f2SEnji Cooper```
62328f6c2f2SEnji Cooper
62428f6c2f2SEnji CooperSuppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will
62528f6c2f2SEnji Coopersee that the arguments match expectation #2 (remember that we always pick the
62628f6c2f2SEnji Cooperlast matching expectation). Now, since we said that there should be only two
62728f6c2f2SEnji Coopersuch calls, gMock will report an error immediately. This is basically what we've
62828f6c2f2SEnji Coopertold you in the [Using Multiple Expectations](#MultiExpectations) section above.
62928f6c2f2SEnji Cooper
63028f6c2f2SEnji CooperThis example shows that **expectations in gMock are "sticky" by default**, in
63128f6c2f2SEnji Cooperthe sense that they remain active even after we have reached their invocation
63228f6c2f2SEnji Cooperupper bounds. This is an important rule to remember, as it affects the meaning
63328f6c2f2SEnji Cooperof the spec, and is **different** to how it's done in many other mocking
63428f6c2f2SEnji Cooperframeworks (Why'd we do that? Because we think our rule makes the common cases
63528f6c2f2SEnji Coopereasier to express and understand.).
63628f6c2f2SEnji Cooper
63728f6c2f2SEnji CooperSimple? Let's see if you've really understood it: what does the following code
63828f6c2f2SEnji Coopersay?
63928f6c2f2SEnji Cooper
64028f6c2f2SEnji Cooper```cpp
64128f6c2f2SEnji Cooperusing ::testing::Return;
64228f6c2f2SEnji Cooper...
64328f6c2f2SEnji Cooperfor (int i = n; i > 0; i--) {
64428f6c2f2SEnji Cooper  EXPECT_CALL(turtle, GetX())
64528f6c2f2SEnji Cooper      .WillOnce(Return(10*i));
64628f6c2f2SEnji Cooper}
64728f6c2f2SEnji Cooper```
64828f6c2f2SEnji Cooper
64928f6c2f2SEnji CooperIf you think it says that `turtle.GetX()` will be called `n` times and will
65028f6c2f2SEnji Cooperreturn 10, 20, 30, ..., consecutively, think twice! The problem is that, as we
65128f6c2f2SEnji Coopersaid, expectations are sticky. So, the second time `turtle.GetX()` is called,
65228f6c2f2SEnji Cooperthe last (latest) `EXPECT_CALL()` statement will match, and will immediately
65328f6c2f2SEnji Cooperlead to an "upper bound violated" error - this piece of code is not very useful!
65428f6c2f2SEnji Cooper
65528f6c2f2SEnji CooperOne correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is
65628f6c2f2SEnji Cooperto explicitly say that the expectations are *not* sticky. In other words, they
65728f6c2f2SEnji Coopershould *retire* as soon as they are saturated:
65828f6c2f2SEnji Cooper
65928f6c2f2SEnji Cooper```cpp
66028f6c2f2SEnji Cooperusing ::testing::Return;
66128f6c2f2SEnji Cooper...
66228f6c2f2SEnji Cooperfor (int i = n; i > 0; i--) {
66328f6c2f2SEnji Cooper  EXPECT_CALL(turtle, GetX())
66428f6c2f2SEnji Cooper      .WillOnce(Return(10*i))
66528f6c2f2SEnji Cooper      .RetiresOnSaturation();
66628f6c2f2SEnji Cooper}
66728f6c2f2SEnji Cooper```
66828f6c2f2SEnji Cooper
66928f6c2f2SEnji CooperAnd, there's a better way to do it: in this case, we expect the calls to occur
67028f6c2f2SEnji Cooperin a specific order, and we line up the actions to match the order. Since the
67128f6c2f2SEnji Cooperorder is important here, we should make it explicit using a sequence:
67228f6c2f2SEnji Cooper
67328f6c2f2SEnji Cooper```cpp
67428f6c2f2SEnji Cooperusing ::testing::InSequence;
67528f6c2f2SEnji Cooperusing ::testing::Return;
67628f6c2f2SEnji Cooper...
67728f6c2f2SEnji Cooper{
67828f6c2f2SEnji Cooper  InSequence s;
67928f6c2f2SEnji Cooper
68028f6c2f2SEnji Cooper  for (int i = 1; i <= n; i++) {
68128f6c2f2SEnji Cooper    EXPECT_CALL(turtle, GetX())
68228f6c2f2SEnji Cooper        .WillOnce(Return(10*i))
68328f6c2f2SEnji Cooper        .RetiresOnSaturation();
68428f6c2f2SEnji Cooper  }
68528f6c2f2SEnji Cooper}
68628f6c2f2SEnji Cooper```
68728f6c2f2SEnji Cooper
68828f6c2f2SEnji CooperBy the way, the other situation where an expectation may *not* be sticky is when
68928f6c2f2SEnji Cooperit's in a sequence - as soon as another expectation that comes after it in the
69028f6c2f2SEnji Coopersequence has been used, it automatically retires (and will never be used to
69128f6c2f2SEnji Coopermatch any call).
69228f6c2f2SEnji Cooper
69328f6c2f2SEnji Cooper### Uninteresting Calls
69428f6c2f2SEnji Cooper
69528f6c2f2SEnji CooperA mock object may have many methods, and not all of them are that interesting.
69628f6c2f2SEnji CooperFor example, in some tests we may not care about how many times `GetX()` and
69728f6c2f2SEnji Cooper`GetY()` get called.
69828f6c2f2SEnji Cooper
69928f6c2f2SEnji CooperIn gMock, if you are not interested in a method, just don't say anything about
70028f6c2f2SEnji Cooperit. If a call to this method occurs, you'll see a warning in the test output,
70128f6c2f2SEnji Cooperbut it won't be a failure. This is called "naggy" behavior; to change, see
70228f6c2f2SEnji Cooper[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy).
703