# gMock Cookbook
<!-- GOOGLETEST_CM0012 DO NOT DELETE -->
You can find recipes for using gMock here. If you haven't yet, please read
[this](for_dummies.md) first to make sure you understand the basics.
**Note:** gMock lives in the `testing` name space. For readability, it is
recommended to write `using ::testing::Foo;` once in your file before using the
name `Foo` defined by gMock. We omit such `using` statements in this section for
brevity, but you should do it in your own code.
## Creating Mock Classes
Mock classes are defined as normal classes, using the `MOCK_METHOD` macro to
generate mocked methods. The macro gets 3 or 4 parameters:
```cpp
class MyMock {
public:
MOCK_METHOD(ReturnType, MethodName, (Args...));
MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...));
};
```
The first 3 parameters are simply the method declaration, split into 3 parts.
The 4th parameter accepts a closed list of qualifiers, which affect the
generated method:
* **`const`** - Makes the mocked method a `const` method. Required if
overriding a `const` method.
* **`override`** - Marks the method with `override`. Recommended if overriding
a `virtual` method.
* **`noexcept`** - Marks the method with `noexcept`. Required if overriding a
`noexcept` method.
* **`Calltype(...)`** - Sets the call type for the method (e.g. to
`STDMETHODCALLTYPE`), useful in Windows.
### Dealing with unprotected commas
Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent
`MOCK_METHOD` from parsing its arguments correctly:
```cpp {.bad}
class MockFoo {
public:
MOCK_METHOD(std::pair<bool, int>, GetPair, ()); // Won't compile!
MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool)); // Won't compile!
};
```
Solution 1 - wrap with parentheses:
```cpp {.good}
class MockFoo {
public:
MOCK_METHOD((std::pair<bool, int>), GetPair, ());
MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool));
};
```
Note that wrapping a return or argument type with parentheses is, in general,
invalid C++. `MOCK_METHOD` removes the parentheses.
Solution 2 - define an alias:
```cpp {.good}
class MockFoo {
public:
using BoolAndInt = std::pair<bool, int>;
MOCK_METHOD(BoolAndInt, GetPair, ());
using MapIntDouble = std::map<int, double>;
MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool));
};
```
### Mocking Private or Protected Methods
You must always put a mock method definition (`MOCK_METHOD`) in a `public:`
section of the mock class, regardless of the method being mocked being `public`,
`protected`, or `private` in the base class. This allows `ON_CALL` and
`EXPECT_CALL` to reference the mock function from outside of the mock class.
(Yes, C++ allows a subclass to change the access level of a virtual function in
the base class.) Example:
```cpp
class Foo {
public:
...
virtual bool Transform(Gadget* g) = 0;
protected:
virtual void Resume();
private:
virtual int GetTimeOut();
};
class MockFoo : public Foo {
public:
...
MOCK_METHOD(bool, Transform, (Gadget* g), (override));
// The following must be in the public section, even though the
// methods are protected or private in the base class.
MOCK_METHOD(void, Resume, (), (override));
MOCK_METHOD(int, GetTimeOut, (), (override));
};
```
### Mocking Overloaded Methods
You can mock overloaded functions as usual. No special attention is required:
```cpp
class Foo {
...
// Must be virtual as we'll inherit from Foo.
virtual ~Foo();
// Overloaded on the types and/or numbers of arguments.
virtual int Add(Element x);
virtual int Add(int times, Element x);
// Overloaded on the const-ness of this object.
virtual Bar& GetBar();
virtual const Bar& GetBar() const;
};
class MockFoo : public Foo {
...
MOCK_METHOD(int, Add, (Element x), (override));
MOCK_METHOD(int, Add, (int times, Element x), (override));
MOCK_METHOD(Bar&, GetBar, (), (override));
MOCK_METHOD(const Bar&, GetBar, (), (const, override));
};
```
**Note:** if you don't mock all versions of the overloaded method, the compiler
will give you a warning about some methods in the base class being hidden. To
fix that, use `using` to bring them in scope:
```cpp
class MockFoo : public Foo {
...
using Foo::Add;
MOCK_METHOD(int, Add, (Element x), (override));
// We don't want to mock int Add(int times, Element x);
...
};
```
### Mocking Class Templates
You can mock class templates just like any class.
```cpp
template <typename Elem>
class StackInterface {
...
// Must be virtual as we'll inherit from StackInterface.
virtual ~StackInterface();
virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0;
};
template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
MOCK_METHOD(int, GetSize, (), (override));
MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```
### Mocking Non-virtual Methods {#MockingNonVirtualMethods}
gMock can mock non-virtual functions to be used in Hi-perf dependency
injection.<!-- GOOGLETEST_CM0017 DO NOT DELETE -->
In this case, instead of sharing a common base class with the real class, your
mock class will be *unrelated* to the real class, but contain methods with the
same signatures. The syntax for mocking non-virtual methods is the *same* as
mocking virtual methods (just don't add `override`):
```cpp
// A simple packet stream class. None of its members is virtual.
class ConcretePacketStream {
public:
void AppendPacket(Packet* new_packet);
const Packet* GetPacket(size_t packet_number) const;
size_t NumberOfPackets() const;
...
};
// A mock packet stream class. It inherits from no other, but defines
// GetPacket() and NumberOfPackets().
class MockPacketStream {
public:
MOCK_METHOD(const Packet*, GetPacket, (size_t packet_number), (const));
MOCK_METHOD(size_t, NumberOfPackets, (), (const));
...
};
```
Note that the mock class doesn't define `AppendPacket()`, unlike the real class.
That's fine as long as the test doesn't need to call it.
Next, you need a way to say that you want to use `ConcretePacketStream` in
production code, and use `MockPacketStream` in tests. Since the functions are
not virtual and the two classes are unrelated, you must specify your choice at
*compile time* (as opposed to run time).
One way to do it is to templatize your code that needs to use a packet stream.
More specifically, you will give your code a template type argument for the type
of the packet stream. In production, you will instantiate your template with
`ConcretePacketStream` as the type argument. In tests, you will instantiate the
same template with `MockPacketStream`. For example, you may write:
```cpp
template <class PacketStream>
void CreateConnection(PacketStream* stream) { ... }
template <class PacketStream>
class PacketReader {
public:
void ReadPackets(PacketStream* stream, size_t packet_num);
};
```
Then you can use `CreateConnection<ConcretePacketStream>()` and
`PacketReader<ConcretePacketStream>` in production code, and use
`CreateConnection<MockPacketStream>()` and `PacketReader<MockPacketStream>` in
tests.
```cpp
MockPacketStream mock_stream;
EXPECT_CALL(mock_stream, ...)...;
.. set more expectations on mock_stream ...
PacketReader<MockPacketStream> reader(&mock_stream);
... exercise reader ...
```
### Mocking Free Functions
It's possible to use gMock to mock a free function (i.e. a C-style function or a
static method). You just need to rewrite your code to use an interface (abstract
class).
Instead of calling a free function (say, `OpenFile`) directly, introduce an
interface for it and have a concrete subclass that calls the free function:
```cpp
class FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) = 0;
};
class File : public FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) {
return OpenFile(path, mode);
}
};
```
Your code should talk to `FileInterface` to open a file. Now it's easy to mock
out the function.
This may seem like a lot of hassle, but in practice you often have multiple
related functions that you can put in the same interface, so the per-function
syntactic overhead will be much lower.
If you are concerned about the performance overhead incurred by virtual
functions, and profiling confirms your concern, you can combine this with the
recipe for [mocking non-virtual methods](#MockingNonVirtualMethods).
### Old-Style `MOCK_METHODn` Macros
Before the generic `MOCK_METHOD` macro was introduced, mocks where created using
a family of macros collectively called `MOCK_METHODn`. These macros are still
supported, though migration to the new `MOCK_METHOD` is recommended.
The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`:
* The general structure is `MOCK_METHODn(MethodName, ReturnType(Args))`,
instead of `MOCK_METHOD(ReturnType, MethodName, (Args))`.
* The number `n` must equal the number of arguments.
* When mocking a const method, one must use `MOCK_CONST_METHODn`.
* When mocking a class template, the macro name must be suffixed with `_T`.
* In order to specify the call type, the macro name must be suffixed with
`_WITH_CALLTYPE`, and the call type is the first macro argument.
Old macros and their new equivalents:
<a name="table99"></a>
<table border="1" cellspacing="0" cellpadding="1">
<tr> <th colspan=2> Simple </th></tr>
<tr> <td> Old </td> <td> `MOCK_METHOD1(Foo, bool(int))` </td> </tr>
<tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int))` </td> </tr>
<tr> <th colspan=2> Const Method </th></tr> <tr> <td> Old </td> <td>
`MOCK_CONST_METHOD1(Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td>
`MOCK_METHOD(bool, Foo, (int), (const))` </td> </tr>
<tr> <th colspan=2> Method in a Class Template </th></tr> <tr> <td> Old </td>
<td> `MOCK_METHOD1_T(Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td>
`MOCK_METHOD(bool, Foo, (int))` </td> </tr>
<tr> <th colspan=2> Const Method in a Class Template </th></tr> <tr> <td> Old
</td> <td> `MOCK_CONST_METHOD1_T(Foo, bool(int))` </td> </tr> <tr> <td> New
</td> <td> `MOCK_METHOD(bool, Foo, (int), (const))` </td> </tr>
<tr> <th colspan=2> Method with Call Type </th></tr> <tr> <td> Old </td> <td>
`MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))` </td> </tr> <tr>
<td> New </td> <td> `MOCK_METHOD(bool, Foo, (int),
(Calltype(STDMETHODCALLTYPE)))` </td> </tr>
<tr> <th colspan=2> Const Method with Call Type </th></tr> <tr> <td> Old</td>
<td> `MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))` </td>
</tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int), (const,
Calltype(STDMETHODCALLTYPE)))` </td> </tr>
<tr> <th colspan=2> Method with Call Type in a Class Template </th></tr> <tr>
<td> Old </td> <td> `MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo,
bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int),
(Calltype(STDMETHODCALLTYPE)))` </td> </tr>
<tr> <th colspan=2> Const Method with Call Type in a Class Template </th></tr>
<tr> <td> Old </td> <td> `MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE,
Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo,
(int), (const, Calltype(STDMETHODCALLTYPE)))` </td> </tr>
</table>
### The Nice, the Strict, and the Naggy {#NiceStrictNaggy}
If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an
"uninteresting call", and the default action (which can be specified using
`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will
also by default cause gMock to print a warning. (In the future, we might remove
this warning by default.)
However, sometimes you may want to ignore these uninteresting calls, and
sometimes you may want to treat them as errors. gMock lets you make the decision
on a per-mock-object basis.
Suppose your test uses a mock class `MockFoo`:
```cpp
TEST(...) {
MockFoo mock_foo;
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
}
```
If a method of `mock_foo` other than `DoThis()` is called, you will get a
warning. However, if you rewrite your test to use `NiceMock<MockFoo>` instead,
you can suppress the warning:
```cpp
using ::testing::NiceMock;
TEST(...) {
NiceMock<MockFoo> mock_foo;
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
}
```
`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used wherever
`MockFoo` is accepted.
It also works if `MockFoo`'s constructor takes some arguments, as
`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:
```cpp
using ::testing::NiceMock;
TEST(...) {
NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi").
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
}
```
The usage of `StrictMock` is similar, except that it makes all uninteresting
calls failures:
```cpp
using ::testing::StrictMock;
TEST(...) {
StrictMock<MockFoo> mock_foo;
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
// The test will fail if a method of mock_foo other than DoThis()
// is called.
}
```
NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of
*methods* with no expectations); they do not affect *unexpected* calls (calls of
methods with expectations, but they don't match). See
[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected).
There are some caveats though (I dislike them just as much as the next guy, but
sadly they are side effects of C++'s limitations):
1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods
defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class.
If a mock method is defined in a **base class** of `MockFoo`, the "nice" or
"strict" modifier may not affect it, depending on the compiler. In
particular, nesting `NiceMock` and `StrictMock` (e.g.
`NiceMock<StrictMock<MockFoo> >`) is **not** supported.
2. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` may not work correctly if the
destructor of `MockFoo` is not virtual. We would like to fix this, but it
requires cleaning up existing tests. http://b/28934720 tracks the issue.
3. During the constructor or destructor of `MockFoo`, the mock object is *not*
nice or strict. This may cause surprises if the constructor or destructor
calls a mock method on `this` object. (This behavior, however, is consistent
with C++'s general rule: if a constructor or destructor calls a virtual
method of `this` object, that method is treated as non-virtual. In other
words, to the base class's constructor or destructor, `this` object behaves
like an instance of the base class, not the derived class. This rule is
required for safety. Otherwise a base constructor may use members of a
derived class before they are initialized, or a base destructor may use
members of a derived class after they have been destroyed.)
Finally, you should be **very cautious** about when to use naggy or strict
mocks, as they tend to make tests more brittle and harder to maintain. When you
refactor your code without changing its externally visible behavior, ideally you
shouldn't need to update any tests. If your code interacts with a naggy mock,
however, you may start to get spammed with warnings as the result of your
change. Worse, if your code interacts with a strict mock, your tests may start
to fail and you'll be forced to fix them. Our general recommendation is to use
nice mocks (not yet the default) most of the time, use naggy mocks (the current
default) when developing or debugging tests, and use strict mocks only as the
last resort.
### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces}
Sometimes a method has a long list of arguments that is mostly uninteresting.
For example:
```cpp
class LogSink {
public:
...
virtual void send(LogSeverity severity, const char* full_filename,
const char* base_filename, int line,
const struct tm* tm_time,
const char* message, size_t message_len) = 0;
};
```
This method's argument list is lengthy and hard to work with (the `message`
argument is not even 0-terminated). If we mock it as is, using the mock will be
awkward. If, however, we try to simplify this interface, we'll need to fix all
clients depending on it, which is often infeasible.
The trick is to redispatch the method in the mock class:
```cpp
class ScopedMockLog : public LogSink {
public:
...
virtual void send(LogSeverity severity, const char* full_filename,
const char* base_filename, int line, const tm* tm_time,
const char* message, size_t message_len) {
// We are only interested in the log severity, full file name, and
// log message.
Log(severity, full_filename, std::string(message, message_len));
}
// Implements the mock method:
//
// void Log(LogSeverity severity,
// const string& file_path,
// const string& message);
MOCK_METHOD(void, Log,
(LogSeverity severity, const string& file_path,
const string& message));
};
```
By defining a new mock method with a trimmed argument list, we make the mock
class more user-friendly.
This technique may also be applied to make overloaded methods more amenable to
mocking. For example, when overloads have been used to implement default
arguments:
```cpp
class MockTurtleFactory : public TurtleFactory {
public:
Turtle* MakeTurtle(int length, int weight) override { ... }
Turtle* MakeTurtle(int length, int weight, int speed) override { ... }
// the above methods delegate to this one:
MOCK_METHOD(Turtle*, DoMakeTurtle, ());
};
```
This allows tests that don't care which overload was invoked to avoid specifying
argument matchers:
```cpp
ON_CALL(factory, DoMakeTurtle)
.WillByDefault(MakeMockTurtle());
```
### Alternative to Mocking Concrete Classes
Often you may find yourself using classes that don't implement interfaces. In
order to test your code that uses such a class (let's call it `Concrete`), you
may be tempted to make the methods of `Concrete` virtual and then mock it.
Try not to do that.
Making a non-virtual function virtual is a big decision. It creates an extension
point where subclasses can tweak your class' behavior. This weakens your control
on the class because now it's harder to maintain the class invariants. You
should make a function virtual only when there is a valid reason for a subclass
to override it.
Mocking concrete classes directly is problematic as it creates a tight coupling
between the class and the tests - any small change in the class may invalidate
your tests and make test maintenance a pain.
To avoid such problems, many programmers have been practicing "coding to
interfaces": instead of talking to the `Concrete` class, your code would define
an interface and talk to it. Then you implement that interface as an adaptor on
top of `Concrete`. In tests, you can easily mock that interface to observe how
your code is doing.
This technique incurs some overhead:
* You pay the cost of virtual function calls (usually not a problem).
* There is more abstraction for the programmers to learn.
However, it can also bring significant benefits in addition to better
testability:
* `Concrete`'s API may not fit your problem domain very well, as you may not
be the only client it tries to serve. By designing your own interface, you
have a chance to tailor it to your need - you may add higher-level
functionalities, rename stuff, etc instead of just trimming the class. This
allows you to write your code (user of the interface) in a more natural way,
which means it will be more readable, more maintainable, and you'll be more
productive.
* If `Concrete`'s implementation ever has to change, you don't have to rewrite
everywhere it is used. Instead, you can absorb the change in your
implementation of the interface, and your other code and tests will be
insulated from this change.
Some people worry that if everyone is practicing this technique, they will end
up writing lots of redundant code. This concern is totally understandable.
However, there are two reasons why it may not be the case:
* Different projects may need to use `Concrete` in different ways, so the best
interfaces for them will be different. Therefore, each of them will have its
own domain-specific interface on top of `Concrete`, and they will not be the
same code.
* If enough projects want to use the same interface, they can always share it,
just like they have been sharing `Concrete`. You can check in the interface
and the adaptor somewhere near `Concrete` (perhaps in a `contrib`
sub-directory) and let many projects use it.
You need to weigh the pros and cons carefully for your particular problem, but
I'd like to assure you that the Java community has been practicing this for a
long time and it's a proven effective technique applicable in a wide variety of
situations. :-)
### Delegating Calls to a Fake {#DelegatingToFake}
Some times you have a non-trivial fake implementation of an interface. For
example:
```cpp
class Foo {
public:
virtual ~Foo() {}
virtual char DoThis(int n) = 0;
virtual void DoThat(const char* s, int* p) = 0;
};
class FakeFoo : public Foo {
public:
char DoThis(int n) override {
return (n > 0) ? '+' :
(n < 0) ? '-' : '0';
}
void DoThat(const char* s, int* p) override {
*p = strlen(s);
}
};
```
Now you want to mock this interface such that you can set expectations on it.
However, you also want to use `FakeFoo` for the default behavior, as duplicating
it in the mock object is, well, a lot of work.
When you define the mock class using gMock, you can have it delegate its default
action to a fake class you already have, using this pattern:
```cpp
class MockFoo : public Foo {
public:
// Normal mock method definitions using gMock.
MOCK_METHOD(char, DoThis, (int n), (override));
MOCK_METHOD(void, DoThat, (const char* s, int* p), (override));
// Delegates the default actions of the methods to a FakeFoo object.
// This must be called *before* the custom ON_CALL() statements.
void DelegateToFake() {
ON_CALL(*this, DoThis).WillByDefault([this](int n) {
return fake_.DoThis(n);
});
ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) {
fake_.DoThat(s, p);
});
}
private:
FakeFoo fake_; // Keeps an instance of the fake in the mock.
};
```
With that, you can use `MockFoo` in your tests as usual. Just remember that if
you don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the
fake will be called upon to do it.:
```cpp
using ::testing::_;
TEST(AbcTest, Xyz) {
MockFoo foo;
foo.DelegateToFake(); // Enables the fake for delegation.
// Put your ON_CALL(foo, ...)s here, if any.
// No action specified, meaning to use the default action.
EXPECT_CALL(foo, DoThis(5));
EXPECT_CALL(foo, DoThat(_, _));
int n = 0;
EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked.
foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked.
EXPECT_EQ(2, n);
}
```
**Some tips:**
* If you want, you can still override the default action by providing your own
`ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
* In `DelegateToFake()`, you only need to delegate the methods whose fake
implementation you intend to use.
* The general technique discussed here works for overloaded methods, but
you'll need to tell the compiler which version you mean. To disambiguate a
mock function (the one you specify inside the parentheses of `ON_CALL()`),
use [this technique](#SelectOverload); to disambiguate a fake function (the
one you place inside `Invoke()`), use a `static_cast` to specify the
function's type. For instance, if class `Foo` has methods `char DoThis(int
n)` and `bool DoThis(double x) const`, and you want to invoke the latter,
you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double)
const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)`
(The strange-looking thing inside the angled brackets of `static_cast` is
the type of a function pointer to the second `DoThis()` method.).
* Having to mix a mock and a fake is often a sign of something gone wrong.
Perhaps you haven't got used to the interaction-based way of testing yet. Or
perhaps your interface is taking on too many roles and should be split up.
Therefore, **don't abuse this**. We would only recommend to do it as an
intermediate step when you are refactoring your code.
Regarding the tip on mixing a mock and a fake, here's an example on why it may
be a bad sign: Suppose you have a class `System` for low-level system
operations. In particular, it does file and I/O operations. And suppose you want
to test how your code uses `System` to do I/O, and you just want the file
operations to work normally. If you mock out the entire `System` class, you'll
have to provide a fake implementation for the file operation part, which
suggests that `System` is taking on too many roles.
Instead, you can define a `FileOps` interface and an `IOOps` interface and split
`System`'s functionalities into the two. Then you can mock `IOOps` without
mocking `FileOps`.
### Delegating Calls to a Real Object
When using testing doubles (mocks, fakes, stubs, and etc), sometimes their
behaviors will differ from those of the real objects. This difference could be
either intentional (as in simulating an error such that you can test the error
handling code) or unintentional. If your mocks have different behaviors than the
real objects by mistake, you could end up with code that passes the tests but
fails in production.
You can use the *delegating-to-real* technique to ensure that your mock has the
same behavior as the real object while retaining the ability to validate calls.
This technique is very similar to the [delegating-to-fake](#DelegatingToFake)
technique, the difference being that we use a real object instead of a fake.
Here's an example:
```cpp
using ::testing::AtLeast;
class MockFoo : public Foo {
public:
MockFoo() {
// By default, all calls are delegated to the real object.
ON_CALL(*this, DoThis).WillByDefault([this](int n) {
return real_.DoThis(n);
});
ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) {
real_.DoThat(s, p);
});
...
}
MOCK_METHOD(char, DoThis, ...);
MOCK_METHOD(void, DoThat, ...);
...
private:
Foo real_;
};
...
MockFoo mock;
EXPECT_CALL(mock, DoThis())