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