xref: /freebsd/contrib/googletest/docs/gmock_cheat_sheet.md (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1# gMock Cheat Sheet
2
3## Defining a Mock Class
4
5### Mocking a Normal Class {#MockClass}
6
7Given
8
9```cpp
10class Foo {
11 public:
12  virtual ~Foo();
13  virtual int GetSize() const = 0;
14  virtual string Describe(const char* name) = 0;
15  virtual string Describe(int type) = 0;
16  virtual bool Process(Bar elem, int count) = 0;
17};
18```
19
20(note that `~Foo()` **must** be virtual) we can define its mock as
21
22```cpp
23#include <gmock/gmock.h>
24
25class MockFoo : public Foo {
26 public:
27  MOCK_METHOD(int, GetSize, (), (const, override));
28  MOCK_METHOD(string, Describe, (const char* name), (override));
29  MOCK_METHOD(string, Describe, (int type), (override));
30  MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
31};
32```
33
34To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
35which warns on all uninteresting calls, or a "strict" mock, which treats them as
36failures:
37
38```cpp
39using ::testing::NiceMock;
40using ::testing::NaggyMock;
41using ::testing::StrictMock;
42
43NiceMock<MockFoo> nice_foo;      // The type is a subclass of MockFoo.
44NaggyMock<MockFoo> naggy_foo;    // The type is a subclass of MockFoo.
45StrictMock<MockFoo> strict_foo;  // The type is a subclass of MockFoo.
46```
47
48{: .callout .note}
49**Note:** A mock object is currently naggy by default. We may make it nice by
50default in the future.
51
52### Mocking a Class Template {#MockTemplate}
53
54Class templates can be mocked just like any class.
55
56To mock
57
58```cpp
59template <typename Elem>
60class StackInterface {
61 public:
62  virtual ~StackInterface();
63  virtual int GetSize() const = 0;
64  virtual void Push(const Elem& x) = 0;
65};
66```
67
68(note that all member functions that are mocked, including `~StackInterface()`
69**must** be virtual).
70
71```cpp
72template <typename Elem>
73class MockStack : public StackInterface<Elem> {
74 public:
75  MOCK_METHOD(int, GetSize, (), (const, override));
76  MOCK_METHOD(void, Push, (const Elem& x), (override));
77};
78```
79
80### Specifying Calling Conventions for Mock Functions
81
82If your mock function doesn't use the default calling convention, you can
83specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
84For example,
85
86```cpp
87  MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
88  MOCK_METHOD(int, Bar, (double x, double y),
89              (const, Calltype(STDMETHODCALLTYPE)));
90```
91
92where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
93
94## Using Mocks in Tests {#UsingMocks}
95
96The typical work flow is:
97
981.  Import the gMock names you need to use. All gMock symbols are in the
99    `testing` namespace unless they are macros or otherwise noted.
1002.  Create the mock objects.
1013.  Optionally, set the default actions of the mock objects.
1024.  Set your expectations on the mock objects (How will they be called? What
103    will they do?).
1045.  Exercise code that uses the mock objects; if necessary, check the result
105    using googletest assertions.
1066.  When a mock object is destructed, gMock automatically verifies that all
107    expectations on it have been satisfied.
108
109Here's an example:
110
111```cpp
112using ::testing::Return;                          // #1
113
114TEST(BarTest, DoesThis) {
115  MockFoo foo;                                    // #2
116
117  ON_CALL(foo, GetSize())                         // #3
118      .WillByDefault(Return(1));
119  // ... other default actions ...
120
121  EXPECT_CALL(foo, Describe(5))                   // #4
122      .Times(3)
123      .WillRepeatedly(Return("Category 5"));
124  // ... other expectations ...
125
126  EXPECT_EQ(MyProductionFunction(&foo), "good");  // #5
127}                                                 // #6
128```
129
130## Setting Default Actions {#OnCall}
131
132gMock has a **built-in default action** for any function that returns `void`,
133`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
134the default-constructed value, if one exists for the given type.
135
136To customize the default action for functions with return type `T`, use
137[`DefaultValue<T>`](reference/mocking.md#DefaultValue). For example:
138
139```cpp
140  // Sets the default action for return type std::unique_ptr<Buzz> to
141  // creating a new Buzz every time.
142  DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
143      [] { return std::make_unique<Buzz>(AccessLevel::kInternal); });
144
145  // When this fires, the default action of MakeBuzz() will run, which
146  // will return a new Buzz object.
147  EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
148
149  auto buzz1 = mock_buzzer_.MakeBuzz("hello");
150  auto buzz2 = mock_buzzer_.MakeBuzz("hello");
151  EXPECT_NE(buzz1, nullptr);
152  EXPECT_NE(buzz2, nullptr);
153  EXPECT_NE(buzz1, buzz2);
154
155  // Resets the default action for return type std::unique_ptr<Buzz>,
156  // to avoid interfere with other tests.
157  DefaultValue<std::unique_ptr<Buzz>>::Clear();
158```
159
160To customize the default action for a particular method of a specific mock
161object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar
162syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you
163do not require that the mock method is called. See
164[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed
165discussion.
166
167## Setting Expectations {#ExpectCall}
168
169See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference.
170
171## Matchers {#MatcherList}
172
173See the [Matchers Reference](reference/matchers.md).
174
175## Actions {#ActionList}
176
177See the [Actions Reference](reference/actions.md).
178
179## Cardinalities {#CardinalityList}
180
181See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of
182`EXPECT_CALL` in the Mocking Reference.
183
184## Expectation Order
185
186By default, expectations can be matched in *any* order. If some or all
187expectations must be matched in a given order, you can use the
188[`After` clause](reference/mocking.md#EXPECT_CALL.After) or
189[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of
190`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence).
191
192## Verifying and Resetting a Mock
193
194gMock will verify the expectations on a mock object when it is destructed, or
195you can do it earlier:
196
197```cpp
198using ::testing::Mock;
199...
200// Verifies and removes the expectations on mock_obj;
201// returns true if and only if successful.
202Mock::VerifyAndClearExpectations(&mock_obj);
203...
204// Verifies and removes the expectations on mock_obj;
205// also removes the default actions set by ON_CALL();
206// returns true if and only if successful.
207Mock::VerifyAndClear(&mock_obj);
208```
209
210Do not set new expectations after verifying and clearing a mock after its use.
211Setting expectations after code that exercises the mock has undefined behavior.
212See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more
213information.
214
215You can also tell gMock that a mock object can be leaked and doesn't need to be
216verified:
217
218```cpp
219Mock::AllowLeak(&mock_obj);
220```
221
222## Mock Classes
223
224gMock defines a convenient mock class template
225
226```cpp
227class MockFunction<R(A1, ..., An)> {
228 public:
229  MOCK_METHOD(R, Call, (A1, ..., An));
230};
231```
232
233See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of
234it.
235
236## Flags
237
238| Flag                           | Description                               |
239| :----------------------------- | :---------------------------------------- |
240| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
241| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
242