# 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,