3 ## Defining a Mock Class
5 ### Mocking a Normal Class {#MockClass}
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;
20 (note that `~Foo()` **must** be virtual) we can define its mock as
23 #include "gmock/gmock.h"
25 class MockFoo : public Foo {
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));
34 To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
35 which warns on all uninteresting calls, or a "strict" mock, which treats them as
39 using ::testing::NiceMock;
40 using ::testing::NaggyMock;
41 using ::testing::StrictMock;
43 NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
44 NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
45 StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
49 **Note:** A mock object is currently naggy by default. We may make it nice by
50 default in the future.
52 ### Mocking a Class Template {#MockTemplate}
54 Class templates can be mocked just like any class.
59 template <typename Elem>
60 class StackInterface {
62 virtual ~StackInterface();
63 virtual int GetSize() const = 0;
64 virtual void Push(const Elem& x) = 0;
68 (note that all member functions that are mocked, including `~StackInterface()`
72 template <typename Elem>
73 class MockStack : public StackInterface<Elem> {
75 MOCK_METHOD(int, GetSize, (), (const, override));
76 MOCK_METHOD(void, Push, (const Elem& x), (override));
80 ### Specifying Calling Conventions for Mock Functions
82 If your mock function doesn't use the default calling convention, you can
83 specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
87 MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
88 MOCK_METHOD(int, Bar, (double x, double y),
89 (const, Calltype(STDMETHODCALLTYPE)));
92 where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
94 ## Using Mocks in Tests {#UsingMocks}
96 The typical work flow is:
98 1. Import the gMock names you need to use. All gMock symbols are in the
99 `testing` namespace unless they are macros or otherwise noted.
100 2. Create the mock objects.
101 3. Optionally, set the default actions of the mock objects.
102 4. Set your expectations on the mock objects (How will they be called? What
104 5. Exercise code that uses the mock objects; if necessary, check the result
105 using googletest assertions.
106 6. When a mock object is destructed, gMock automatically verifies that all
107 expectations on it have been satisfied.
112 using ::testing::Return; // #1
114 TEST(BarTest, DoesThis) {
117 ON_CALL(foo, GetSize()) // #3
118 .WillByDefault(Return(1));
119 // ... other default actions ...
121 EXPECT_CALL(foo, Describe(5)) // #4
123 .WillRepeatedly(Return("Category 5"));
124 // ... other expectations ...
126 EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5
130 ## Setting Default Actions {#OnCall}
132 gMock 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
134 the default-constructed value, if one exists for the given type.
136 To customize the default action for functions with return type `T`, use
137 [`DefaultValue<T>`](reference/mocking.md#DefaultValue). For example:
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 MakeUnique<Buzz>(AccessLevel::kInternal); });
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());
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);
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();
160 To customize the default action for a particular method of a specific mock
161 object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar
162 syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you
163 do not require that the mock method is called. See
164 [Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed
167 ## Setting Expectations {#ExpectCall}
169 See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference.
171 ## Matchers {#MatcherList}
173 See the [Matchers Reference](reference/matchers.md).
175 ## Actions {#ActionList}
177 See the [Actions Reference](reference/actions.md).
179 ## Cardinalities {#CardinalityList}
181 See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of
182 `EXPECT_CALL` in the Mocking Reference.
186 By default, expectations can be matched in *any* order. If some or all
187 expectations 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).
192 ## Verifying and Resetting a Mock
194 gMock will verify the expectations on a mock object when it is destructed, or
195 you can do it earlier:
198 using ::testing::Mock;
200 // Verifies and removes the expectations on mock_obj;
201 // returns true if and only if successful.
202 Mock::VerifyAndClearExpectations(&mock_obj);
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.
207 Mock::VerifyAndClear(&mock_obj);
210 Do not set new expectations after verifying and clearing a mock after its use.
211 Setting expectations after code that exercises the mock has undefined behavior.
212 See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more
215 You can also tell gMock that a mock object can be leaked and doesn't need to be
219 Mock::AllowLeak(&mock_obj);
224 gMock defines a convenient mock class template
227 class MockFunction<R(A1, ..., An)> {
229 MOCK_METHOD(R, Call, (A1, ..., An));
233 See this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of
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. |