You can find recipes for using Google Mock here. If you haven't yet,
please read the [ForDummies](V1_5_ForDummies.md) document first to make sure you understand
the basics.
**Note:** Google Mock 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 Google Mock. We omit
such `using` statements in this page for brevity, but you should do it
in your own code.
# Creating Mock Classes #
## 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:
```
class Foo {
public:
...
virtual bool Transform(Gadget* g) = 0;
protected:
virtual void Resume();
private:
virtual int GetTimeOut();
};
class MockFoo : public Foo {
public:
...
MOCK_METHOD1(Transform, bool(Gadget* g));
// The following must be in the public section, even though the
// methods are protected or private in the base class.
MOCK_METHOD0(Resume, void());
MOCK_METHOD0(GetTimeOut, int());
};
```
## Mocking Overloaded Methods ##
You can mock overloaded functions as usual. No special attention is required:
```
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_METHOD1(Add, int(Element x));
MOCK_METHOD2(Add, int(int times, Element x);
MOCK_METHOD0(GetBar, Bar&());
MOCK_CONST_METHOD0(GetBar, const Bar&());
};
```
**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:
```
class MockFoo : public Foo {
...
using Foo::Add;
MOCK_METHOD1(Add, int(Element x));