Blame googlemock/docs/v1_7/CookBook.md

Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
You can find recipes for using Google Mock here. If you haven't yet,
Packit bd1cd8
please read the [ForDummies](V1_7_ForDummies.md) document first to make sure you understand
Packit bd1cd8
the basics.
Packit bd1cd8
Packit bd1cd8
**Note:** Google Mock lives in the `testing` name space. For
Packit bd1cd8
readability, it is recommended to write `using ::testing::Foo;` once in
Packit bd1cd8
your file before using the name `Foo` defined by Google Mock. We omit
Packit bd1cd8
such `using` statements in this page for brevity, but you should do it
Packit bd1cd8
in your own code.
Packit bd1cd8
Packit bd1cd8
# Creating Mock Classes #
Packit bd1cd8
Packit bd1cd8
## Mocking Private or Protected Methods ##
Packit bd1cd8
Packit bd1cd8
You must always put a mock method definition (`MOCK_METHOD*`) in a
Packit bd1cd8
`public:` section of the mock class, regardless of the method being
Packit bd1cd8
mocked being `public`, `protected`, or `private` in the base class.
Packit bd1cd8
This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function
Packit bd1cd8
from outside of the mock class.  (Yes, C++ allows a subclass to change
Packit bd1cd8
the access level of a virtual function in the base class.)  Example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  virtual bool Transform(Gadget* g) = 0;
Packit bd1cd8
Packit bd1cd8
 protected:
Packit bd1cd8
  virtual void Resume();
Packit bd1cd8
Packit bd1cd8
 private:
Packit bd1cd8
  virtual int GetTimeOut();
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  MOCK_METHOD1(Transform, bool(Gadget* g));
Packit bd1cd8
Packit bd1cd8
  // The following must be in the public section, even though the
Packit bd1cd8
  // methods are protected or private in the base class.
Packit bd1cd8
  MOCK_METHOD0(Resume, void());
Packit bd1cd8
  MOCK_METHOD0(GetTimeOut, int());
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Mocking Overloaded Methods ##
Packit bd1cd8
Packit bd1cd8
You can mock overloaded functions as usual. No special attention is required:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class Foo {
Packit bd1cd8
  ...
Packit bd1cd8
Packit bd1cd8
  // Must be virtual as we'll inherit from Foo.
Packit bd1cd8
  virtual ~Foo();
Packit bd1cd8
Packit bd1cd8
  // Overloaded on the types and/or numbers of arguments.
Packit bd1cd8
  virtual int Add(Element x);
Packit bd1cd8
  virtual int Add(int times, Element x);
Packit bd1cd8
Packit bd1cd8
  // Overloaded on the const-ness of this object.
Packit bd1cd8
  virtual Bar& GetBar();
Packit bd1cd8
  virtual const Bar& GetBar() const;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
  ...
Packit bd1cd8
  MOCK_METHOD1(Add, int(Element x));
Packit bd1cd8
  MOCK_METHOD2(Add, int(int times, Element x);
Packit bd1cd8
Packit bd1cd8
  MOCK_METHOD0(GetBar, Bar&());
Packit bd1cd8
  MOCK_CONST_METHOD0(GetBar, const Bar&());
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
**Note:** if you don't mock all versions of the overloaded method, the
Packit bd1cd8
compiler will give you a warning about some methods in the base class
Packit bd1cd8
being hidden. To fix that, use `using` to bring them in scope:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
  ...
Packit bd1cd8
  using Foo::Add;
Packit bd1cd8
  MOCK_METHOD1(Add, int(Element x));
Packit bd1cd8
  // We don't want to mock int Add(int times, Element x);
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Mocking Class Templates ##
Packit bd1cd8
Packit bd1cd8
To mock a class template, append `_T` to the `MOCK_*` macros:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
template <typename Elem>
Packit bd1cd8
class StackInterface {
Packit bd1cd8
  ...
Packit bd1cd8
  // Must be virtual as we'll inherit from StackInterface.
Packit bd1cd8
  virtual ~StackInterface();
Packit bd1cd8
Packit bd1cd8
  virtual int GetSize() const = 0;
Packit bd1cd8
  virtual void Push(const Elem& x) = 0;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
template <typename Elem>
Packit bd1cd8
class MockStack : public StackInterface<Elem> {
Packit bd1cd8
  ...
Packit bd1cd8
  MOCK_CONST_METHOD0_T(GetSize, int());
Packit bd1cd8
  MOCK_METHOD1_T(Push, void(const Elem& x));
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Mocking Nonvirtual Methods ##
Packit bd1cd8
Packit bd1cd8
Google Mock can mock non-virtual functions to be used in what we call _hi-perf
Packit bd1cd8
dependency injection_.
Packit bd1cd8
Packit bd1cd8
In this case, instead of sharing a common base class with the real
Packit bd1cd8
class, your mock class will be _unrelated_ to the real class, but
Packit bd1cd8
contain methods with the same signatures.  The syntax for mocking
Packit bd1cd8
non-virtual methods is the _same_ as mocking virtual methods:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
// A simple packet stream class.  None of its members is virtual.
Packit bd1cd8
class ConcretePacketStream {
Packit bd1cd8
 public:
Packit bd1cd8
  void AppendPacket(Packet* new_packet);
Packit bd1cd8
  const Packet* GetPacket(size_t packet_number) const;
Packit bd1cd8
  size_t NumberOfPackets() const;
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
// A mock packet stream class.  It inherits from no other, but defines
Packit bd1cd8
// GetPacket() and NumberOfPackets().
Packit bd1cd8
class MockPacketStream {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
Packit bd1cd8
  MOCK_CONST_METHOD0(NumberOfPackets, size_t());
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Note that the mock class doesn't define `AppendPacket()`, unlike the
Packit bd1cd8
real class. That's fine as long as the test doesn't need to call it.
Packit bd1cd8
Packit bd1cd8
Next, you need a way to say that you want to use
Packit bd1cd8
`ConcretePacketStream` in production code, and use `MockPacketStream`
Packit bd1cd8
in tests.  Since the functions are not virtual and the two classes are
Packit bd1cd8
unrelated, you must specify your choice at _compile time_ (as opposed
Packit bd1cd8
to run time).
Packit bd1cd8
Packit bd1cd8
One way to do it is to templatize your code that needs to use a packet
Packit bd1cd8
stream.  More specifically, you will give your code a template type
Packit bd1cd8
argument for the type of the packet stream.  In production, you will
Packit bd1cd8
instantiate your template with `ConcretePacketStream` as the type
Packit bd1cd8
argument.  In tests, you will instantiate the same template with
Packit bd1cd8
`MockPacketStream`.  For example, you may write:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
template <class PacketStream>
Packit bd1cd8
void CreateConnection(PacketStream* stream) { ... }
Packit bd1cd8
Packit bd1cd8
template <class PacketStream>
Packit bd1cd8
class PacketReader {
Packit bd1cd8
 public:
Packit bd1cd8
  void ReadPackets(PacketStream* stream, size_t packet_num);
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Then you can use `CreateConnection<ConcretePacketStream>()` and
Packit bd1cd8
`PacketReader<ConcretePacketStream>` in production code, and use
Packit bd1cd8
`CreateConnection<MockPacketStream>()` and
Packit bd1cd8
`PacketReader<MockPacketStream>` in tests.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  MockPacketStream mock_stream;
Packit bd1cd8
  EXPECT_CALL(mock_stream, ...)...;
Packit bd1cd8
  .. set more expectations on mock_stream ...
Packit bd1cd8
  PacketReader<MockPacketStream> reader(&mock_stream);
Packit bd1cd8
  ... exercise reader ...
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Mocking Free Functions ##
Packit bd1cd8
Packit bd1cd8
It's possible to use Google Mock to mock a free function (i.e. a
Packit bd1cd8
C-style function or a static method).  You just need to rewrite your
Packit bd1cd8
code to use an interface (abstract class).
Packit bd1cd8
Packit bd1cd8
Instead of calling a free function (say, `OpenFile`) directly,
Packit bd1cd8
introduce an interface for it and have a concrete subclass that calls
Packit bd1cd8
the free function:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class FileInterface {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  virtual bool Open(const char* path, const char* mode) = 0;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
class File : public FileInterface {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  virtual bool Open(const char* path, const char* mode) {
Packit bd1cd8
    return OpenFile(path, mode);
Packit bd1cd8
  }
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Your code should talk to `FileInterface` to open a file.  Now it's
Packit bd1cd8
easy to mock out the function.
Packit bd1cd8
Packit bd1cd8
This may seem much hassle, but in practice you often have multiple
Packit bd1cd8
related functions that you can put in the same interface, so the
Packit bd1cd8
per-function syntactic overhead will be much lower.
Packit bd1cd8
Packit bd1cd8
If you are concerned about the performance overhead incurred by
Packit bd1cd8
virtual functions, and profiling confirms your concern, you can
Packit bd1cd8
combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md).
Packit bd1cd8
Packit bd1cd8
## The Nice, the Strict, and the Naggy ##
Packit bd1cd8
Packit bd1cd8
If a mock method has no `EXPECT_CALL` spec but is called, Google Mock
Packit bd1cd8
will print a warning about the "uninteresting call". The rationale is:
Packit bd1cd8
Packit bd1cd8
  * New methods may be added to an interface after a test is written. We shouldn't fail a test just because a method it doesn't know about is called.
Packit bd1cd8
  * However, this may also mean there's a bug in the test, so Google Mock shouldn't be silent either. If the user believes these calls are harmless, he can add an `EXPECT_CALL()` to suppress the warning.
Packit bd1cd8
Packit bd1cd8
However, sometimes you may want to suppress all "uninteresting call"
Packit bd1cd8
warnings, while sometimes you may want the opposite, i.e. to treat all
Packit bd1cd8
of them as errors. Google Mock lets you make the decision on a
Packit bd1cd8
per-mock-object basis.
Packit bd1cd8
Packit bd1cd8
Suppose your test uses a mock class `MockFoo`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST(...) {
Packit bd1cd8
  MockFoo mock_foo;
Packit bd1cd8
  EXPECT_CALL(mock_foo, DoThis());
Packit bd1cd8
  ... code that uses mock_foo ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If a method of `mock_foo` other than `DoThis()` is called, it will be
Packit bd1cd8
reported by Google Mock as a warning. However, if you rewrite your
Packit bd1cd8
test to use `NiceMock<MockFoo>` instead, the warning will be gone,
Packit bd1cd8
resulting in a cleaner test output:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::NiceMock;
Packit bd1cd8
Packit bd1cd8
TEST(...) {
Packit bd1cd8
  NiceMock<MockFoo> mock_foo;
Packit bd1cd8
  EXPECT_CALL(mock_foo, DoThis());
Packit bd1cd8
  ... code that uses mock_foo ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used
Packit bd1cd8
wherever `MockFoo` is accepted.
Packit bd1cd8
Packit bd1cd8
It also works if `MockFoo`'s constructor takes some arguments, as
Packit bd1cd8
`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::NiceMock;
Packit bd1cd8
Packit bd1cd8
TEST(...) {
Packit bd1cd8
  NiceMock<MockFoo> mock_foo(5, "hi");  // Calls MockFoo(5, "hi").
Packit bd1cd8
  EXPECT_CALL(mock_foo, DoThis());
Packit bd1cd8
  ... code that uses mock_foo ...
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The usage of `StrictMock` is similar, except that it makes all
Packit bd1cd8
uninteresting calls failures:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::StrictMock;
Packit bd1cd8
Packit bd1cd8
TEST(...) {
Packit bd1cd8
  StrictMock<MockFoo> mock_foo;
Packit bd1cd8
  EXPECT_CALL(mock_foo, DoThis());
Packit bd1cd8
  ... code that uses mock_foo ...
Packit bd1cd8
Packit bd1cd8
  // The test will fail if a method of mock_foo other than DoThis()
Packit bd1cd8
  // is called.
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
There are some caveats though (I don't like them just as much as the
Packit bd1cd8
next guy, but sadly they are side effects of C++'s limitations):
Packit bd1cd8
Packit bd1cd8
  1. `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods defined using the `MOCK_METHOD*` family of macros **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.
Packit bd1cd8
  1. The constructors of the base mock (`MockFoo`) cannot have arguments passed by non-const reference, which happens to be banned by the [Google C++ style guide](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml).
Packit bd1cd8
  1. 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.)
Packit bd1cd8
Packit bd1cd8
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 should'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.
Packit bd1cd8
Packit bd1cd8
## Simplifying the Interface without Breaking Existing Code ##
Packit bd1cd8
Packit bd1cd8
Sometimes a method has a long list of arguments that is mostly
Packit bd1cd8
uninteresting. For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class LogSink {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  virtual void send(LogSeverity severity, const char* full_filename,
Packit bd1cd8
                    const char* base_filename, int line,
Packit bd1cd8
                    const struct tm* tm_time,
Packit bd1cd8
                    const char* message, size_t message_len) = 0;
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
This method's argument list is lengthy and hard to work with (let's
Packit bd1cd8
say that the `message` argument is not even 0-terminated). If we mock
Packit bd1cd8
it as is, using the mock will be awkward. If, however, we try to
Packit bd1cd8
simplify this interface, we'll need to fix all clients depending on
Packit bd1cd8
it, which is often infeasible.
Packit bd1cd8
Packit bd1cd8
The trick is to re-dispatch the method in the mock class:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class ScopedMockLog : public LogSink {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  virtual void send(LogSeverity severity, const char* full_filename,
Packit bd1cd8
                    const char* base_filename, int line, const tm* tm_time,
Packit bd1cd8
                    const char* message, size_t message_len) {
Packit bd1cd8
    // We are only interested in the log severity, full file name, and
Packit bd1cd8
    // log message.
Packit bd1cd8
    Log(severity, full_filename, std::string(message, message_len));
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Implements the mock method:
Packit bd1cd8
  //
Packit bd1cd8
  //   void Log(LogSeverity severity,
Packit bd1cd8
  //            const string& file_path,
Packit bd1cd8
  //            const string& message);
Packit bd1cd8
  MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path,
Packit bd1cd8
                         const string& message));
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
By defining a new mock method with a trimmed argument list, we make
Packit bd1cd8
the mock class much more user-friendly.
Packit bd1cd8
Packit bd1cd8
## Alternative to Mocking Concrete Classes ##
Packit bd1cd8
Packit bd1cd8
Often you may find yourself using classes that don't implement
Packit bd1cd8
interfaces. In order to test your code that uses such a class (let's
Packit bd1cd8
call it `Concrete`), you may be tempted to make the methods of
Packit bd1cd8
`Concrete` virtual and then mock it.
Packit bd1cd8
Packit bd1cd8
Try not to do that.
Packit bd1cd8
Packit bd1cd8
Making a non-virtual function virtual is a big decision. It creates an
Packit bd1cd8
extension point where subclasses can tweak your class' behavior. This
Packit bd1cd8
weakens your control on the class because now it's harder to maintain
Packit bd1cd8
the class' invariants. You should make a function virtual only when
Packit bd1cd8
there is a valid reason for a subclass to override it.
Packit bd1cd8
Packit bd1cd8
Mocking concrete classes directly is problematic as it creates a tight
Packit bd1cd8
coupling between the class and the tests - any small change in the
Packit bd1cd8
class may invalidate your tests and make test maintenance a pain.
Packit bd1cd8
Packit bd1cd8
To avoid such problems, many programmers have been practicing "coding
Packit bd1cd8
to interfaces": instead of talking to the `Concrete` class, your code
Packit bd1cd8
would define an interface and talk to it. Then you implement that
Packit bd1cd8
interface as an adaptor on top of `Concrete`. In tests, you can easily
Packit bd1cd8
mock that interface to observe how your code is doing.
Packit bd1cd8
Packit bd1cd8
This technique incurs some overhead:
Packit bd1cd8
Packit bd1cd8
  * You pay the cost of virtual function calls (usually not a problem).
Packit bd1cd8
  * There is more abstraction for the programmers to learn.
Packit bd1cd8
Packit bd1cd8
However, it can also bring significant benefits in addition to better
Packit bd1cd8
testability:
Packit bd1cd8
Packit bd1cd8
  * `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.
Packit bd1cd8
  * 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.
Packit bd1cd8
Packit bd1cd8
Some people worry that if everyone is practicing this technique, they
Packit bd1cd8
will end up writing lots of redundant code. This concern is totally
Packit bd1cd8
understandable. However, there are two reasons why it may not be the
Packit bd1cd8
case:
Packit bd1cd8
Packit bd1cd8
  * 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.
Packit bd1cd8
  * 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.
Packit bd1cd8
Packit bd1cd8
You need to weigh the pros and cons carefully for your particular
Packit bd1cd8
problem, but I'd like to assure you that the Java community has been
Packit bd1cd8
practicing this for a long time and it's a proven effective technique
Packit bd1cd8
applicable in a wide variety of situations. :-)
Packit bd1cd8
Packit bd1cd8
## Delegating Calls to a Fake ##
Packit bd1cd8
Packit bd1cd8
Some times you have a non-trivial fake implementation of an
Packit bd1cd8
interface. For example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual ~Foo() {}
Packit bd1cd8
  virtual char DoThis(int n) = 0;
Packit bd1cd8
  virtual void DoThat(const char* s, int* p) = 0;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
class FakeFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual char DoThis(int n) {
Packit bd1cd8
    return (n > 0) ? '+' :
Packit bd1cd8
        (n < 0) ? '-' : '0';
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual void DoThat(const char* s, int* p) {
Packit bd1cd8
    *p = strlen(s);
Packit bd1cd8
  }
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Now you want to mock this interface such that you can set expectations
Packit bd1cd8
on it. However, you also want to use `FakeFoo` for the default
Packit bd1cd8
behavior, as duplicating it in the mock object is, well, a lot of
Packit bd1cd8
work.
Packit bd1cd8
Packit bd1cd8
When you define the mock class using Google Mock, you can have it
Packit bd1cd8
delegate its default action to a fake class you already have, using
Packit bd1cd8
this pattern:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  // Normal mock method definitions using Google Mock.
Packit bd1cd8
  MOCK_METHOD1(DoThis, char(int n));
Packit bd1cd8
  MOCK_METHOD2(DoThat, void(const char* s, int* p));
Packit bd1cd8
Packit bd1cd8
  // Delegates the default actions of the methods to a FakeFoo object.
Packit bd1cd8
  // This must be called *before* the custom ON_CALL() statements.
Packit bd1cd8
  void DelegateToFake() {
Packit bd1cd8
    ON_CALL(*this, DoThis(_))
Packit bd1cd8
        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis));
Packit bd1cd8
    ON_CALL(*this, DoThat(_, _))
Packit bd1cd8
        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat));
Packit bd1cd8
  }
Packit bd1cd8
 private:
Packit bd1cd8
  FakeFoo fake_;  // Keeps an instance of the fake in the mock.
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
With that, you can use `MockFoo` in your tests as usual. Just remember
Packit bd1cd8
that if you don't explicitly set an action in an `ON_CALL()` or
Packit bd1cd8
`EXPECT_CALL()`, the fake will be called upon to do it:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
Packit bd1cd8
TEST(AbcTest, Xyz) {
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  foo.DelegateToFake(); // Enables the fake for delegation.
Packit bd1cd8
Packit bd1cd8
  // Put your ON_CALL(foo, ...)s here, if any.
Packit bd1cd8
Packit bd1cd8
  // No action specified, meaning to use the default action.
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(5));
Packit bd1cd8
  EXPECT_CALL(foo, DoThat(_, _));
Packit bd1cd8
Packit bd1cd8
  int n = 0;
Packit bd1cd8
  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.
Packit bd1cd8
  foo.DoThat("Hi", &n);           // FakeFoo::DoThat() is invoked.
Packit bd1cd8
  EXPECT_EQ(2, n);
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
**Some tips:**
Packit bd1cd8
Packit bd1cd8
  * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
Packit bd1cd8
  * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use.
Packit bd1cd8
  * 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()`), see the "Selecting Between Overloaded Functions" section on this page; 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.).
Packit bd1cd8
  * 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.
Packit bd1cd8
Packit bd1cd8
Regarding the tip on mixing a mock and a fake, here's an example on
Packit bd1cd8
why it may be a bad sign: Suppose you have a class `System` for
Packit bd1cd8
low-level system operations. In particular, it does file and I/O
Packit bd1cd8
operations. And suppose you want to test how your code uses `System`
Packit bd1cd8
to do I/O, and you just want the file operations to work normally. If
Packit bd1cd8
you mock out the entire `System` class, you'll have to provide a fake
Packit bd1cd8
implementation for the file operation part, which suggests that
Packit bd1cd8
`System` is taking on too many roles.
Packit bd1cd8
Packit bd1cd8
Instead, you can define a `FileOps` interface and an `IOOps` interface
Packit bd1cd8
and split `System`'s functionalities into the two. Then you can mock
Packit bd1cd8
`IOOps` without mocking `FileOps`.
Packit bd1cd8
Packit bd1cd8
## Delegating Calls to a Real Object ##
Packit bd1cd8
Packit bd1cd8
When using testing doubles (mocks, fakes, stubs, and etc), sometimes
Packit bd1cd8
their behaviors will differ from those of the real objects. This
Packit bd1cd8
difference could be either intentional (as in simulating an error such
Packit bd1cd8
that you can test the error handling code) or unintentional. If your
Packit bd1cd8
mocks have different behaviors than the real objects by mistake, you
Packit bd1cd8
could end up with code that passes the tests but fails in production.
Packit bd1cd8
Packit bd1cd8
You can use the _delegating-to-real_ technique to ensure that your
Packit bd1cd8
mock has the same behavior as the real object while retaining the
Packit bd1cd8
ability to validate calls. This technique is very similar to the
Packit bd1cd8
delegating-to-fake technique, the difference being that we use a real
Packit bd1cd8
object instead of a fake. Here's an example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::AtLeast;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MockFoo() {
Packit bd1cd8
    // By default, all calls are delegated to the real object.
Packit bd1cd8
    ON_CALL(*this, DoThis())
Packit bd1cd8
        .WillByDefault(Invoke(&real_, &Foo::DoThis));
Packit bd1cd8
    ON_CALL(*this, DoThat(_))
Packit bd1cd8
        .WillByDefault(Invoke(&real_, &Foo::DoThat));
Packit bd1cd8
    ...
Packit bd1cd8
  }
Packit bd1cd8
  MOCK_METHOD0(DoThis, ...);
Packit bd1cd8
  MOCK_METHOD1(DoThat, ...);
Packit bd1cd8
  ...
Packit bd1cd8
 private:
Packit bd1cd8
  Foo real_;
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo mock;
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(mock, DoThis())
Packit bd1cd8
      .Times(3);
Packit bd1cd8
  EXPECT_CALL(mock, DoThat("Hi"))
Packit bd1cd8
      .Times(AtLeast(1));
Packit bd1cd8
  ... use mock in test ...
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
With this, Google Mock will verify that your code made the right calls
Packit bd1cd8
(with the right arguments, in the right order, called the right number
Packit bd1cd8
of times, etc), and a real object will answer the calls (so the
Packit bd1cd8
behavior will be the same as in production). This gives you the best
Packit bd1cd8
of both worlds.
Packit bd1cd8
Packit bd1cd8
## Delegating Calls to a Parent Class ##
Packit bd1cd8
Packit bd1cd8
Ideally, you should code to interfaces, whose methods are all pure
Packit bd1cd8
virtual. In reality, sometimes you do need to mock a virtual method
Packit bd1cd8
that is not pure (i.e, it already has an implementation). For example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual ~Foo();
Packit bd1cd8
Packit bd1cd8
  virtual void Pure(int n) = 0;
Packit bd1cd8
  virtual int Concrete(const char* str) { ... }
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  // Mocking a pure method.
Packit bd1cd8
  MOCK_METHOD1(Pure, void(int n));
Packit bd1cd8
  // Mocking a concrete method.  Foo::Concrete() is shadowed.
Packit bd1cd8
  MOCK_METHOD1(Concrete, int(const char* str));
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Sometimes you may want to call `Foo::Concrete()` instead of
Packit bd1cd8
`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub
Packit bd1cd8
action, or perhaps your test doesn't need to mock `Concrete()` at all
Packit bd1cd8
(but it would be oh-so painful to have to define a new mock class
Packit bd1cd8
whenever you don't need to mock one of its methods).
Packit bd1cd8
Packit bd1cd8
The trick is to leave a back door in your mock class for accessing the
Packit bd1cd8
real methods in the base class:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  // Mocking a pure method.
Packit bd1cd8
  MOCK_METHOD1(Pure, void(int n));
Packit bd1cd8
  // Mocking a concrete method.  Foo::Concrete() is shadowed.
Packit bd1cd8
  MOCK_METHOD1(Concrete, int(const char* str));
Packit bd1cd8
Packit bd1cd8
  // Use this to call Concrete() defined in Foo.
Packit bd1cd8
  int FooConcrete(const char* str) { return Foo::Concrete(str); }
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Now, you can call `Foo::Concrete()` inside an action by:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, Concrete(_))
Packit bd1cd8
      .WillOnce(Invoke(&foo, &MockFoo::FooConcrete));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
or tell the mock object that you don't want to mock `Concrete()`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
...
Packit bd1cd8
  ON_CALL(foo, Concrete(_))
Packit bd1cd8
      .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do
Packit bd1cd8
that, `MockFoo::Concrete()` will be called (and cause an infinite
Packit bd1cd8
recursion) since `Foo::Concrete()` is virtual. That's just how C++
Packit bd1cd8
works.)
Packit bd1cd8
Packit bd1cd8
# Using Matchers #
Packit bd1cd8
Packit bd1cd8
## Matching Argument Values Exactly ##
Packit bd1cd8
Packit bd1cd8
You can specify exactly which arguments a mock method is expecting:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::Return;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(5))
Packit bd1cd8
      .WillOnce(Return('a'));
Packit bd1cd8
  EXPECT_CALL(foo, DoThat("Hello", bar));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Using Simple Matchers ##
Packit bd1cd8
Packit bd1cd8
You can use matchers to match arguments that have a certain property:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::Ge;
Packit bd1cd8
using ::testing::NotNull;
Packit bd1cd8
using ::testing::Return;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.
Packit bd1cd8
      .WillOnce(Return('a'));
Packit bd1cd8
  EXPECT_CALL(foo, DoThat("Hello", NotNull()));
Packit bd1cd8
  // The second argument must not be NULL.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
A frequently used matcher is `_`, which matches anything:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::NotNull;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, DoThat(_, NotNull()));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Combining Matchers ##
Packit bd1cd8
Packit bd1cd8
You can build complex matchers from existing ones using `AllOf()`,
Packit bd1cd8
`AnyOf()`, and `Not()`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::AllOf;
Packit bd1cd8
using ::testing::Gt;
Packit bd1cd8
using ::testing::HasSubstr;
Packit bd1cd8
using ::testing::Ne;
Packit bd1cd8
using ::testing::Not;
Packit bd1cd8
...
Packit bd1cd8
  // The argument must be > 5 and != 10.
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
Packit bd1cd8
                                Ne(10))));
Packit bd1cd8
Packit bd1cd8
  // The first argument must not contain sub-string "blah".
Packit bd1cd8
  EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
Packit bd1cd8
                          NULL));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Casting Matchers ##
Packit bd1cd8
Packit bd1cd8
Google Mock matchers are statically typed, meaning that the compiler
Packit bd1cd8
can catch your mistake if you use a matcher of the wrong type (for
Packit bd1cd8
example, if you use `Eq(5)` to match a `string` argument). Good for
Packit bd1cd8
you!
Packit bd1cd8
Packit bd1cd8
Sometimes, however, you know what you're doing and want the compiler
Packit bd1cd8
to give you some slack. One example is that you have a matcher for
Packit bd1cd8
`long` and the argument you want to match is `int`. While the two
Packit bd1cd8
types aren't exactly the same, there is nothing really wrong with
Packit bd1cd8
using a `Matcher<long>` to match an `int` - after all, we can first
Packit bd1cd8
convert the `int` argument to a `long` before giving it to the
Packit bd1cd8
matcher.
Packit bd1cd8
Packit bd1cd8
To support this need, Google Mock gives you the
Packit bd1cd8
`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type
Packit bd1cd8
`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the
Packit bd1cd8
type `m` accepts):
Packit bd1cd8
Packit bd1cd8
  1. Type `T` can be implicitly cast to type `U`;
Packit bd1cd8
  1. When both `T` and `U` are built-in arithmetic types (`bool`, integers, and floating-point numbers), the conversion from `T` to `U` is not lossy (in other words, any value representable by `T` can also be represented by `U`); and
Packit bd1cd8
  1. When `U` is a reference, `T` must also be a reference (as the underlying matcher may be interested in the address of the `U` value).
Packit bd1cd8
Packit bd1cd8
The code won't compile if any of these conditions isn't met.
Packit bd1cd8
Packit bd1cd8
Here's one example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::SafeMatcherCast;
Packit bd1cd8
Packit bd1cd8
// A base class and a child class.
Packit bd1cd8
class Base { ... };
Packit bd1cd8
class Derived : public Base { ... };
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD1(DoThis, void(Derived* derived));
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  // m is a Matcher<Base*> we got from somewhere.
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar
Packit bd1cd8
function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works
Packit bd1cd8
as long as you can `static_cast` type `T` to type `U`.
Packit bd1cd8
Packit bd1cd8
`MatcherCast` essentially lets you bypass C++'s type system
Packit bd1cd8
(`static_cast` isn't always safe as it could throw away information,
Packit bd1cd8
for example), so be careful not to misuse/abuse it.
Packit bd1cd8
Packit bd1cd8
## Selecting Between Overloaded Functions ##
Packit bd1cd8
Packit bd1cd8
If you expect an overloaded function to be called, the compiler may
Packit bd1cd8
need some help on which overloaded version it is.
Packit bd1cd8
Packit bd1cd8
To disambiguate functions overloaded on the const-ness of this object,
Packit bd1cd8
use the `Const()` argument wrapper.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::ReturnRef;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
  ...
Packit bd1cd8
  MOCK_METHOD0(GetBar, Bar&());
Packit bd1cd8
  MOCK_CONST_METHOD0(GetBar, const Bar&());
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  Bar bar1, bar2;
Packit bd1cd8
  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().
Packit bd1cd8
      .WillOnce(ReturnRef(bar1));
Packit bd1cd8
  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().
Packit bd1cd8
      .WillOnce(ReturnRef(bar2));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
(`Const()` is defined by Google Mock and returns a `const` reference
Packit bd1cd8
to its argument.)
Packit bd1cd8
Packit bd1cd8
To disambiguate overloaded functions with the same number of arguments
Packit bd1cd8
but different argument types, you may need to specify the exact type
Packit bd1cd8
of a matcher, either by wrapping your matcher in `Matcher<type>()`, or
Packit bd1cd8
using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`,
Packit bd1cd8
etc):
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::An;
Packit bd1cd8
using ::testing::Lt;
Packit bd1cd8
using ::testing::Matcher;
Packit bd1cd8
using ::testing::TypedEq;
Packit bd1cd8
Packit bd1cd8
class MockPrinter : public Printer {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD1(Print, void(int n));
Packit bd1cd8
  MOCK_METHOD1(Print, void(char c));
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
TEST(PrinterTest, Print) {
Packit bd1cd8
  MockPrinter printer;
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);
Packit bd1cd8
  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);
Packit bd1cd8
  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);
Packit bd1cd8
Packit bd1cd8
  printer.Print(3);
Packit bd1cd8
  printer.Print(6);
Packit bd1cd8
  printer.Print('a');
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Performing Different Actions Based on the Arguments ##
Packit bd1cd8
Packit bd1cd8
When a mock method is called, the _last_ matching expectation that's
Packit bd1cd8
still active will be selected (think "newer overrides older"). So, you
Packit bd1cd8
can make a method do different things depending on its argument values
Packit bd1cd8
like this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Lt;
Packit bd1cd8
using ::testing::Return;
Packit bd1cd8
...
Packit bd1cd8
  // The default case.
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(_))
Packit bd1cd8
      .WillRepeatedly(Return('b'));
Packit bd1cd8
Packit bd1cd8
  // The more specific case.
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(Lt(5)))
Packit bd1cd8
      .WillRepeatedly(Return('a'));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will
Packit bd1cd8
be returned; otherwise `'b'` will be returned.
Packit bd1cd8
Packit bd1cd8
## Matching Multiple Arguments as a Whole ##
Packit bd1cd8
Packit bd1cd8
Sometimes it's not enough to match the arguments individually. For
Packit bd1cd8
example, we may want to say that the first argument must be less than
Packit bd1cd8
the second argument. The `With()` clause allows us to match
Packit bd1cd8
all arguments of a mock function as a whole. For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Lt;
Packit bd1cd8
using ::testing::Ne;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, InRange(Ne(0), _))
Packit bd1cd8
      .With(Lt());
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
says that the first argument of `InRange()` must not be 0, and must be
Packit bd1cd8
less than the second argument.
Packit bd1cd8
Packit bd1cd8
The expression inside `With()` must be a matcher of type
Packit bd1cd8
`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the
Packit bd1cd8
types of the function arguments.
Packit bd1cd8
Packit bd1cd8
You can also write `AllArgs(m)` instead of `m` inside `.With()`. The
Packit bd1cd8
two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable
Packit bd1cd8
than `.With(Lt())`.
Packit bd1cd8
Packit bd1cd8
You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments
Packit bd1cd8
(as a tuple) against `m`. For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::AllOf;
Packit bd1cd8
using ::testing::Args;
Packit bd1cd8
using ::testing::Lt;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, Blah(_, _, _))
Packit bd1cd8
      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
says that `Blah()` will be called with arguments `x`, `y`, and `z` where
Packit bd1cd8
`x < y < z`.
Packit bd1cd8
Packit bd1cd8
As a convenience and example, Google Mock provides some matchers for
Packit bd1cd8
2-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_7_CheatSheet.md) for
Packit bd1cd8
the complete list.
Packit bd1cd8
Packit bd1cd8
Note that if you want to pass the arguments to a predicate of your own
Packit bd1cd8
(e.g. `.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be
Packit bd1cd8
written to take a `tr1::tuple` as its argument; Google Mock will pass the `n`
Packit bd1cd8
selected arguments as _one_ single tuple to the predicate.
Packit bd1cd8
Packit bd1cd8
## Using Matchers as Predicates ##
Packit bd1cd8
Packit bd1cd8
Have you noticed that a matcher is just a fancy predicate that also
Packit bd1cd8
knows how to describe itself? Many existing algorithms take predicates
Packit bd1cd8
as arguments (e.g. those defined in STL's `<algorithm>` header), and
Packit bd1cd8
it would be a shame if Google Mock matchers are not allowed to
Packit bd1cd8
participate.
Packit bd1cd8
Packit bd1cd8
Luckily, you can use a matcher where a unary predicate functor is
Packit bd1cd8
expected by wrapping it inside the `Matches()` function. For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
#include <algorithm>
Packit bd1cd8
#include <vector>
Packit bd1cd8
Packit bd1cd8
std::vector<int> v;
Packit bd1cd8
...
Packit bd1cd8
// How many elements in v are >= 10?
Packit bd1cd8
const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Since you can build complex matchers from simpler ones easily using
Packit bd1cd8
Google Mock, this gives you a way to conveniently construct composite
Packit bd1cd8
predicates (doing the same using STL's `<functional>` header is just
Packit bd1cd8
painful). For example, here's a predicate that's satisfied by any
Packit bd1cd8
number that is >= 0, <= 100, and != 50:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Matches(AllOf(Ge(0), Le(100), Ne(50)))
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Using Matchers in Google Test Assertions ##
Packit bd1cd8
Packit bd1cd8
Since matchers are basically predicates that also know how to describe
Packit bd1cd8
themselves, there is a way to take advantage of them in
Packit bd1cd8
[Google Test](http://code.google.com/p/googletest/) assertions. It's
Packit bd1cd8
called `ASSERT_THAT` and `EXPECT_THAT`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  ASSERT_THAT(value, matcher);  // Asserts that value matches matcher.
Packit bd1cd8
  EXPECT_THAT(value, matcher);  // The non-fatal version.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
For example, in a Google Test test you can write:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
#include "gmock/gmock.h"
Packit bd1cd8
Packit bd1cd8
using ::testing::AllOf;
Packit bd1cd8
using ::testing::Ge;
Packit bd1cd8
using ::testing::Le;
Packit bd1cd8
using ::testing::MatchesRegex;
Packit bd1cd8
using ::testing::StartsWith;
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_THAT(Foo(), StartsWith("Hello"));
Packit bd1cd8
  EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
Packit bd1cd8
  ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
which (as you can probably guess) executes `Foo()`, `Bar()`, and
Packit bd1cd8
`Baz()`, and verifies that:
Packit bd1cd8
Packit bd1cd8
  * `Foo()` returns a string that starts with `"Hello"`.
Packit bd1cd8
  * `Bar()` returns a string that matches regular expression `"Line \\d+"`.
Packit bd1cd8
  * `Baz()` returns a number in the range [5, 10].
Packit bd1cd8
Packit bd1cd8
The nice thing about these macros is that _they read like
Packit bd1cd8
English_. They generate informative messages too. For example, if the
Packit bd1cd8
first `EXPECT_THAT()` above fails, the message will be something like:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Value of: Foo()
Packit bd1cd8
  Actual: "Hi, world!"
Packit bd1cd8
Expected: starts with "Hello"
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the
Packit bd1cd8
[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds
Packit bd1cd8
`assertThat()` to JUnit.
Packit bd1cd8
Packit bd1cd8
## Using Predicates as Matchers ##
Packit bd1cd8
Packit bd1cd8
Google Mock provides a built-in set of matchers. In case you find them
Packit bd1cd8
lacking, you can use an arbitray unary predicate function or functor
Packit bd1cd8
as a matcher - as long as the predicate accepts a value of the type
Packit bd1cd8
you want. You do this by wrapping the predicate inside the `Truly()`
Packit bd1cd8
function, for example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::Truly;
Packit bd1cd8
Packit bd1cd8
int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  // Bar() must be called with an even number.
Packit bd1cd8
  EXPECT_CALL(foo, Bar(Truly(IsEven)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Note that the predicate function / functor doesn't have to return
Packit bd1cd8
`bool`. It works as long as the return value can be used as the
Packit bd1cd8
condition in statement `if (condition) ...`.
Packit bd1cd8
Packit bd1cd8
## Matching Arguments that Are Not Copyable ##
Packit bd1cd8
Packit bd1cd8
When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves
Packit bd1cd8
away a copy of `bar`. When `Foo()` is called later, Google Mock
Packit bd1cd8
compares the argument to `Foo()` with the saved copy of `bar`. This
Packit bd1cd8
way, you don't need to worry about `bar` being modified or destroyed
Packit bd1cd8
after the `EXPECT_CALL()` is executed. The same is true when you use
Packit bd1cd8
matchers like `Eq(bar)`, `Le(bar)`, and so on.
Packit bd1cd8
Packit bd1cd8
But what if `bar` cannot be copied (i.e. has no copy constructor)? You
Packit bd1cd8
could define your own matcher function and use it with `Truly()`, as
Packit bd1cd8
the previous couple of recipes have shown. Or, you may be able to get
Packit bd1cd8
away from it if you can guarantee that `bar` won't be changed after
Packit bd1cd8
the `EXPECT_CALL()` is executed. Just tell Google Mock that it should
Packit bd1cd8
save a reference to `bar`, instead of a copy of it. Here's how:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::Eq;
Packit bd1cd8
using ::testing::ByRef;
Packit bd1cd8
using ::testing::Lt;
Packit bd1cd8
...
Packit bd1cd8
  // Expects that Foo()'s argument == bar.
Packit bd1cd8
  EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
Packit bd1cd8
Packit bd1cd8
  // Expects that Foo()'s argument < bar.
Packit bd1cd8
  EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Remember: if you do this, don't change `bar` after the
Packit bd1cd8
`EXPECT_CALL()`, or the result is undefined.
Packit bd1cd8
Packit bd1cd8
## Validating a Member of an Object ##
Packit bd1cd8
Packit bd1cd8
Often a mock function takes a reference to object as an argument. When
Packit bd1cd8
matching the argument, you may not want to compare the entire object
Packit bd1cd8
against a fixed object, as that may be over-specification. Instead,
Packit bd1cd8
you may need to validate a certain member variable or the result of a
Packit bd1cd8
certain getter method of the object. You can do this with `Field()`
Packit bd1cd8
and `Property()`. More specifically,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Field(&Foo::bar, m)
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
is a matcher that matches a `Foo` object whose `bar` member variable
Packit bd1cd8
satisfies matcher `m`.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Property(&Foo::baz, m)
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
is a matcher that matches a `Foo` object whose `baz()` method returns
Packit bd1cd8
a value that satisfies matcher `m`.
Packit bd1cd8
Packit bd1cd8
For example:
Packit bd1cd8
Packit bd1cd8
> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
Packit bd1cd8
|:-----------------------------|:-----------------------------------|
Packit bd1cd8
> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |
Packit bd1cd8
Packit bd1cd8
Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no
Packit bd1cd8
argument and be declared as `const`.
Packit bd1cd8
Packit bd1cd8
BTW, `Field()` and `Property()` can also match plain pointers to
Packit bd1cd8
objects. For instance,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Field(&Foo::number, Ge(3))
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`,
Packit bd1cd8
the match will always fail regardless of the inner matcher.
Packit bd1cd8
Packit bd1cd8
What if you want to validate more than one members at the same time?
Packit bd1cd8
Remember that there is `AllOf()`.
Packit bd1cd8
Packit bd1cd8
## Validating the Value Pointed to by a Pointer Argument ##
Packit bd1cd8
Packit bd1cd8
C++ functions often take pointers as arguments. You can use matchers
Packit bd1cd8
like `IsNull()`, `NotNull()`, and other comparison matchers to match a
Packit bd1cd8
pointer, but what if you want to make sure the value _pointed to_ by
Packit bd1cd8
the pointer, instead of the pointer itself, has a certain property?
Packit bd1cd8
Well, you can use the `Pointee(m)` matcher.
Packit bd1cd8
Packit bd1cd8
`Pointee(m)` matches a pointer iff `m` matches the value the pointer
Packit bd1cd8
points to. For example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::Ge;
Packit bd1cd8
using ::testing::Pointee;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
expects `foo.Bar()` to be called with a pointer that points to a value
Packit bd1cd8
greater than or equal to 3.
Packit bd1cd8
Packit bd1cd8
One nice thing about `Pointee()` is that it treats a `NULL` pointer as
Packit bd1cd8
a match failure, so you can write `Pointee(m)` instead of
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  AllOf(NotNull(), Pointee(m))
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
without worrying that a `NULL` pointer will crash your test.
Packit bd1cd8
Packit bd1cd8
Also, did we tell you that `Pointee()` works with both raw pointers
Packit bd1cd8
**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and
Packit bd1cd8
etc)?
Packit bd1cd8
Packit bd1cd8
What if you have a pointer to pointer? You guessed it - you can use
Packit bd1cd8
nested `Pointee()` to probe deeper inside the value. For example,
Packit bd1cd8
`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer
Packit bd1cd8
that points to a number less than 3 (what a mouthful...).
Packit bd1cd8
Packit bd1cd8
## Testing a Certain Property of an Object ##
Packit bd1cd8
Packit bd1cd8
Sometimes you want to specify that an object argument has a certain
Packit bd1cd8
property, but there is no existing matcher that does this. If you want
Packit bd1cd8
good error messages, you should define a matcher. If you want to do it
Packit bd1cd8
quick and dirty, you could get away with writing an ordinary function.
Packit bd1cd8
Packit bd1cd8
Let's say you have a mock function that takes an object of type `Foo`,
Packit bd1cd8
which has an `int bar()` method and an `int baz()` method, and you
Packit bd1cd8
want to constrain that the argument's `bar()` value plus its `baz()`
Packit bd1cd8
value is a given number. Here's how you can define a matcher to do it:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::MatcherInterface;
Packit bd1cd8
using ::testing::MatchResultListener;
Packit bd1cd8
Packit bd1cd8
class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
Packit bd1cd8
 public:
Packit bd1cd8
  explicit BarPlusBazEqMatcher(int expected_sum)
Packit bd1cd8
      : expected_sum_(expected_sum) {}
Packit bd1cd8
Packit bd1cd8
  virtual bool MatchAndExplain(const Foo& foo,
Packit bd1cd8
                               MatchResultListener* listener) const {
Packit bd1cd8
    return (foo.bar() + foo.baz()) == expected_sum_;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual void DescribeTo(::std::ostream* os) const {
Packit bd1cd8
    *os << "bar() + baz() equals " << expected_sum_;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual void DescribeNegationTo(::std::ostream* os) const {
Packit bd1cd8
    *os << "bar() + baz() does not equal " << expected_sum_;
Packit bd1cd8
  }
Packit bd1cd8
 private:
Packit bd1cd8
  const int expected_sum_;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
Packit bd1cd8
  return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Matching Containers ##
Packit bd1cd8
Packit bd1cd8
Sometimes an STL container (e.g. list, vector, map, ...) is passed to
Packit bd1cd8
a mock function and you may want to validate it. Since most STL
Packit bd1cd8
containers support the `==` operator, you can write
Packit bd1cd8
`Eq(expected_container)` or simply `expected_container` to match a
Packit bd1cd8
container exactly.
Packit bd1cd8
Packit bd1cd8
Sometimes, though, you may want to be more flexible (for example, the
Packit bd1cd8
first element must be an exact match, but the second element can be
Packit bd1cd8
any positive number, and so on). Also, containers used in tests often
Packit bd1cd8
have a small number of elements, and having to define the expected
Packit bd1cd8
container out-of-line is a bit of a hassle.
Packit bd1cd8
Packit bd1cd8
You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in
Packit bd1cd8
such cases:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::ElementsAre;
Packit bd1cd8
using ::testing::Gt;
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The above matcher says that the container must have 4 elements, which
Packit bd1cd8
must be 1, greater than 0, anything, and 5 respectively.
Packit bd1cd8
Packit bd1cd8
If you instead write:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Gt;
Packit bd1cd8
using ::testing::UnorderedElementsAre;
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
It means that the container must have 4 elements, which under some
Packit bd1cd8
permutation must be 1, greater than 0, anything, and 5 respectively.
Packit bd1cd8
Packit bd1cd8
`ElementsAre()` and `UnorderedElementsAre()` are overloaded to take 0
Packit bd1cd8
to 10 arguments. If more are needed, you can place them in a C-style
Packit bd1cd8
array and use `ElementsAreArray()` or `UnorderedElementsAreArray()`
Packit bd1cd8
instead:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::ElementsAreArray;
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  // ElementsAreArray accepts an array of element values.
Packit bd1cd8
  const int expected_vector1[] = { 1, 5, 2, 4, ... };
Packit bd1cd8
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));
Packit bd1cd8
Packit bd1cd8
  // Or, an array of element matchers.
Packit bd1cd8
  Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... };
Packit bd1cd8
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
In case the array needs to be dynamically created (and therefore the
Packit bd1cd8
array size cannot be inferred by the compiler), you can give
Packit bd1cd8
`ElementsAreArray()` an additional argument to specify the array size:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::ElementsAreArray;
Packit bd1cd8
...
Packit bd1cd8
  int* const expected_vector3 = new int[count];
Packit bd1cd8
  ... fill expected_vector3 with values ...
Packit bd1cd8
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
**Tips:**
Packit bd1cd8
Packit bd1cd8
  * `ElementsAre*()` can be used to match _any_ container that implements the STL iterator pattern (i.e. it has a `const_iterator` type and supports `begin()/end()`), not just the ones defined in STL. It will even work with container types yet to be written - as long as they follows the above pattern.
Packit bd1cd8
  * You can use nested `ElementsAre*()` to match nested (multi-dimensional) containers.
Packit bd1cd8
  * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`.
Packit bd1cd8
  * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`).
Packit bd1cd8
Packit bd1cd8
## Sharing Matchers ##
Packit bd1cd8
Packit bd1cd8
Under the hood, a Google Mock matcher object consists of a pointer to
Packit bd1cd8
a ref-counted implementation object. Copying matchers is allowed and
Packit bd1cd8
very efficient, as only the pointer is copied. When the last matcher
Packit bd1cd8
that references the implementation object dies, the implementation
Packit bd1cd8
object will be deleted.
Packit bd1cd8
Packit bd1cd8
Therefore, if you have some complex matcher that you want to use again
Packit bd1cd8
and again, there is no need to build it everytime. Just assign it to a
Packit bd1cd8
matcher variable and use that variable repeatedly! For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  Matcher<int> in_range = AllOf(Gt(5), Le(10));
Packit bd1cd8
  ... use in_range as a matcher in multiple EXPECT_CALLs ...
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
# Setting Expectations #
Packit bd1cd8
Packit bd1cd8
## Knowing When to Expect ##
Packit bd1cd8
Packit bd1cd8
`ON_CALL` is likely the single most under-utilized construct in Google Mock.
Packit bd1cd8
Packit bd1cd8
There are basically two constructs for defining the behavior of a mock object: `ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when a mock method is called, but _doesn't imply any expectation on the method being called._ `EXPECT_CALL` not only defines the behavior, but also sets an expectation that _the method will be called with the given arguments, for the given number of times_ (and _in the given order_ when you specify the order too).
Packit bd1cd8
Packit bd1cd8
Since `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every `EXPECT_CALL` adds a constraint on the behavior of the code under test. Having more constraints than necessary is _baaad_ - even worse than not having enough constraints.
Packit bd1cd8
Packit bd1cd8
This may be counter-intuitive. How could tests that verify more be worse than tests that verify less? Isn't verification the whole point of tests?
Packit bd1cd8
Packit bd1cd8
The answer, lies in _what_ a test should verify. **A good test verifies the contract of the code.** If a test over-specifies, it doesn't leave enough freedom to the implementation. As a result, changing the implementation without breaking the contract (e.g. refactoring and optimization), which should be perfectly fine to do, can break such tests. Then you have to spend time fixing them, only to see them broken again the next time the implementation is changed.
Packit bd1cd8
Packit bd1cd8
Keep in mind that one doesn't have to verify more than one property in one test. In fact, **it's a good style to verify only one thing in one test.** If you do that, a bug will likely break only one or two tests instead of dozens (which case would you rather debug?). If you are also in the habit of giving tests descriptive names that tell what they verify, you can often easily guess what's wrong just from the test log itself.
Packit bd1cd8
Packit bd1cd8
So use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend to verify that the call is made. For example, you may have a bunch of `ON_CALL`s in your test fixture to set the common mock behavior shared by all tests in the same group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s to verify different aspects of the code's behavior. Compared with the style where each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more resilient to implementational changes (and thus less likely to require maintenance) and makes the intent of the tests more obvious (so they are easier to maintain when you do need to maintain them).
Packit bd1cd8
Packit bd1cd8
## Ignoring Uninteresting Calls ##
Packit bd1cd8
Packit bd1cd8
If you are not interested in how a mock method is called, just don't
Packit bd1cd8
say anything about it. In this case, if the method is ever called,
Packit bd1cd8
Google Mock will perform its default action to allow the test program
Packit bd1cd8
to continue. If you are not happy with the default action taken by
Packit bd1cd8
Google Mock, you can override it using `DefaultValue<T>::Set()`
Packit bd1cd8
(described later in this document) or `ON_CALL()`.
Packit bd1cd8
Packit bd1cd8
Please note that once you expressed interest in a particular mock
Packit bd1cd8
method (via `EXPECT_CALL()`), all invocations to it must match some
Packit bd1cd8
expectation. If this function is called but the arguments don't match
Packit bd1cd8
any `EXPECT_CALL()` statement, it will be an error.
Packit bd1cd8
Packit bd1cd8
## Disallowing Unexpected Calls ##
Packit bd1cd8
Packit bd1cd8
If a mock method shouldn't be called at all, explicitly say so:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, Bar(_))
Packit bd1cd8
      .Times(0);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If some calls to the method are allowed, but the rest are not, just
Packit bd1cd8
list all the expected calls:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::AnyNumber;
Packit bd1cd8
using ::testing::Gt;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, Bar(5));
Packit bd1cd8
  EXPECT_CALL(foo, Bar(Gt(10)))
Packit bd1cd8
      .Times(AnyNumber());
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()`
Packit bd1cd8
statements will be an error.
Packit bd1cd8
Packit bd1cd8
## Expecting Ordered Calls ##
Packit bd1cd8
Packit bd1cd8
Although an `EXPECT_CALL()` statement defined earlier takes precedence
Packit bd1cd8
when Google Mock tries to match a function call with an expectation,
Packit bd1cd8
by default calls don't have to happen in the order `EXPECT_CALL()`
Packit bd1cd8
statements are written. For example, if the arguments match the
Packit bd1cd8
matchers in the third `EXPECT_CALL()`, but not those in the first two,
Packit bd1cd8
then the third expectation will be used.
Packit bd1cd8
Packit bd1cd8
If you would rather have all calls occur in the order of the
Packit bd1cd8
expectations, put the `EXPECT_CALL()` statements in a block where you
Packit bd1cd8
define a variable of type `InSequence`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  using ::testing::_;
Packit bd1cd8
  using ::testing::InSequence;
Packit bd1cd8
Packit bd1cd8
  {
Packit bd1cd8
    InSequence s;
Packit bd1cd8
Packit bd1cd8
    EXPECT_CALL(foo, DoThis(5));
Packit bd1cd8
    EXPECT_CALL(bar, DoThat(_))
Packit bd1cd8
        .Times(2);
Packit bd1cd8
    EXPECT_CALL(foo, DoThis(6));
Packit bd1cd8
  }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
In this example, we expect a call to `foo.DoThis(5)`, followed by two
Packit bd1cd8
calls to `bar.DoThat()` where the argument can be anything, which are
Packit bd1cd8
in turn followed by a call to `foo.DoThis(6)`. If a call occurred
Packit bd1cd8
out-of-order, Google Mock will report an error.
Packit bd1cd8
Packit bd1cd8
## Expecting Partially Ordered Calls ##
Packit bd1cd8
Packit bd1cd8
Sometimes requiring everything to occur in a predetermined order can
Packit bd1cd8
lead to brittle tests. For example, we may care about `A` occurring
Packit bd1cd8
before both `B` and `C`, but aren't interested in the relative order
Packit bd1cd8
of `B` and `C`. In this case, the test should reflect our real intent,
Packit bd1cd8
instead of being overly constraining.
Packit bd1cd8
Packit bd1cd8
Google Mock allows you to impose an arbitrary DAG (directed acyclic
Packit bd1cd8
graph) on the calls. One way to express the DAG is to use the
Packit bd1cd8
[After](http://code.google.com/p/googlemock/wiki/V1_7_CheatSheet#The_After_Clause) clause of `EXPECT_CALL`.
Packit bd1cd8
Packit bd1cd8
Another way is via the `InSequence()` clause (not the same as the
Packit bd1cd8
`InSequence` class), which we borrowed from jMock 2. It's less
Packit bd1cd8
flexible than `After()`, but more convenient when you have long chains
Packit bd1cd8
of sequential calls, as it doesn't require you to come up with
Packit bd1cd8
different names for the expectations in the chains.  Here's how it
Packit bd1cd8
works:
Packit bd1cd8
Packit bd1cd8
If we view `EXPECT_CALL()` statements as nodes in a graph, and add an
Packit bd1cd8
edge from node A to node B wherever A must occur before B, we can get
Packit bd1cd8
a DAG. We use the term "sequence" to mean a directed path in this
Packit bd1cd8
DAG. Now, if we decompose the DAG into sequences, we just need to know
Packit bd1cd8
which sequences each `EXPECT_CALL()` belongs to in order to be able to
Packit bd1cd8
reconstruct the orginal DAG.
Packit bd1cd8
Packit bd1cd8
So, to specify the partial order on the expectations we need to do two
Packit bd1cd8
things: first to define some `Sequence` objects, and then for each
Packit bd1cd8
`EXPECT_CALL()` say which `Sequence` objects it is part
Packit bd1cd8
of. Expectations in the same sequence must occur in the order they are
Packit bd1cd8
written. For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  using ::testing::Sequence;
Packit bd1cd8
Packit bd1cd8
  Sequence s1, s2;
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, A())
Packit bd1cd8
      .InSequence(s1, s2);
Packit bd1cd8
  EXPECT_CALL(bar, B())
Packit bd1cd8
      .InSequence(s1);
Packit bd1cd8
  EXPECT_CALL(bar, C())
Packit bd1cd8
      .InSequence(s2);
Packit bd1cd8
  EXPECT_CALL(foo, D())
Packit bd1cd8
      .InSequence(s2);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A ->
Packit bd1cd8
C -> D`):
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
       +---> B
Packit bd1cd8
       |
Packit bd1cd8
  A ---|
Packit bd1cd8
       |
Packit bd1cd8
       +---> C ---> D
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
This means that A must occur before B and C, and C must occur before
Packit bd1cd8
D. There's no restriction about the order other than these.
Packit bd1cd8
Packit bd1cd8
## Controlling When an Expectation Retires ##
Packit bd1cd8
Packit bd1cd8
When a mock method is called, Google Mock only consider expectations
Packit bd1cd8
that are still active. An expectation is active when created, and
Packit bd1cd8
becomes inactive (aka _retires_) when a call that has to occur later
Packit bd1cd8
has occurred. For example, in
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  using ::testing::_;
Packit bd1cd8
  using ::testing::Sequence;
Packit bd1cd8
Packit bd1cd8
  Sequence s1, s2;
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(log, Log(WARNING, _, "File too large."))     // #1
Packit bd1cd8
      .Times(AnyNumber())
Packit bd1cd8
      .InSequence(s1, s2);
Packit bd1cd8
  EXPECT_CALL(log, Log(WARNING, _, "Data set is empty."))  // #2
Packit bd1cd8
      .InSequence(s1);
Packit bd1cd8
  EXPECT_CALL(log, Log(WARNING, _, "User not found."))     // #3
Packit bd1cd8
      .InSequence(s2);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
as soon as either #2 or #3 is matched, #1 will retire. If a warning
Packit bd1cd8
`"File too large."` is logged after this, it will be an error.
Packit bd1cd8
Packit bd1cd8
Note that an expectation doesn't retire automatically when it's
Packit bd1cd8
saturated. For example,
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(log, Log(WARNING, _, _));                  // #1
Packit bd1cd8
  EXPECT_CALL(log, Log(WARNING, _, "File too large."));  // #2
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
says that there will be exactly one warning with the message `"File
Packit bd1cd8
too large."`. If the second warning contains this message too, #2 will
Packit bd1cd8
match again and result in an upper-bound-violated error.
Packit bd1cd8
Packit bd1cd8
If this is not what you want, you can ask an expectation to retire as
Packit bd1cd8
soon as it becomes saturated:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(log, Log(WARNING, _, _));                 // #1
Packit bd1cd8
  EXPECT_CALL(log, Log(WARNING, _, "File too large."))  // #2
Packit bd1cd8
      .RetiresOnSaturation();
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Here #2 can be used only once, so if you have two warnings with the
Packit bd1cd8
message `"File too large."`, the first will match #2 and the second
Packit bd1cd8
will match #1 - there will be no error.
Packit bd1cd8
Packit bd1cd8
# Using Actions #
Packit bd1cd8
Packit bd1cd8
## Returning References from Mock Methods ##
Packit bd1cd8
Packit bd1cd8
If a mock function's return type is a reference, you need to use
Packit bd1cd8
`ReturnRef()` instead of `Return()` to return a result:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::ReturnRef;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD0(GetBar, Bar&());
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  Bar bar;
Packit bd1cd8
  EXPECT_CALL(foo, GetBar())
Packit bd1cd8
      .WillOnce(ReturnRef(bar));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Returning Live Values from Mock Methods ##
Packit bd1cd8
Packit bd1cd8
The `Return(x)` action saves a copy of `x` when the action is
Packit bd1cd8
_created_, and always returns the same value whenever it's
Packit bd1cd8
executed. Sometimes you may want to instead return the _live_ value of
Packit bd1cd8
`x` (i.e. its value at the time when the action is _executed_.).
Packit bd1cd8
Packit bd1cd8
If the mock function's return type is a reference, you can do it using
Packit bd1cd8
`ReturnRef(x)`, as shown in the previous recipe ("Returning References
Packit bd1cd8
from Mock Methods"). However, Google Mock doesn't let you use
Packit bd1cd8
`ReturnRef()` in a mock function whose return type is not a reference,
Packit bd1cd8
as doing that usually indicates a user error. So, what shall you do?
Packit bd1cd8
Packit bd1cd8
You may be tempted to try `ByRef()`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using testing::ByRef;
Packit bd1cd8
using testing::Return;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD0(GetValue, int());
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
  int x = 0;
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  EXPECT_CALL(foo, GetValue())
Packit bd1cd8
      .WillRepeatedly(Return(ByRef(x)));
Packit bd1cd8
  x = 42;
Packit bd1cd8
  EXPECT_EQ(42, foo.GetValue());
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Unfortunately, it doesn't work here. The above code will fail with error:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Value of: foo.GetValue()
Packit bd1cd8
  Actual: 0
Packit bd1cd8
Expected: 42
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The reason is that `Return(value)` converts `value` to the actual
Packit bd1cd8
return type of the mock function at the time when the action is
Packit bd1cd8
_created_, not when it is _executed_. (This behavior was chosen for
Packit bd1cd8
the action to be safe when `value` is a proxy object that references
Packit bd1cd8
some temporary objects.) As a result, `ByRef(x)` is converted to an
Packit bd1cd8
`int` value (instead of a `const int&`) when the expectation is set,
Packit bd1cd8
and `Return(ByRef(x))` will always return 0.
Packit bd1cd8
Packit bd1cd8
`ReturnPointee(pointer)` was provided to solve this problem
Packit bd1cd8
specifically. It returns the value pointed to by `pointer` at the time
Packit bd1cd8
the action is _executed_:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using testing::ReturnPointee;
Packit bd1cd8
...
Packit bd1cd8
  int x = 0;
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  EXPECT_CALL(foo, GetValue())
Packit bd1cd8
      .WillRepeatedly(ReturnPointee(&x);;  // Note the & here.
Packit bd1cd8
  x = 42;
Packit bd1cd8
  EXPECT_EQ(42, foo.GetValue());  // This will succeed now.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Combining Actions ##
Packit bd1cd8
Packit bd1cd8
Want to do more than one thing when a function is called? That's
Packit bd1cd8
fine. `DoAll()` allow you to do sequence of actions every time. Only
Packit bd1cd8
the return value of the last action in the sequence will be used.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::DoAll;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD1(Bar, bool(int n));
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, Bar(_))
Packit bd1cd8
      .WillOnce(DoAll(action_1,
Packit bd1cd8
                      action_2,
Packit bd1cd8
                      ...
Packit bd1cd8
                      action_n));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Mocking Side Effects ##
Packit bd1cd8
Packit bd1cd8
Sometimes a method exhibits its effect not via returning a value but
Packit bd1cd8
via side effects. For example, it may change some global state or
Packit bd1cd8
modify an output argument. To mock side effects, in general you can
Packit bd1cd8
define your own action by implementing `::testing::ActionInterface`.
Packit bd1cd8
Packit bd1cd8
If all you need to do is to change an output argument, the built-in
Packit bd1cd8
`SetArgPointee()` action is convenient:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::SetArgPointee;
Packit bd1cd8
Packit bd1cd8
class MockMutator : public Mutator {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD2(Mutate, void(bool mutate, int* value));
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockMutator mutator;
Packit bd1cd8
  EXPECT_CALL(mutator, Mutate(true, _))
Packit bd1cd8
      .WillOnce(SetArgPointee<1>(5));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
In this example, when `mutator.Mutate()` is called, we will assign 5
Packit bd1cd8
to the `int` variable pointed to by argument #1
Packit bd1cd8
(0-based).
Packit bd1cd8
Packit bd1cd8
`SetArgPointee()` conveniently makes an internal copy of the
Packit bd1cd8
value you pass to it, removing the need to keep the value in scope and
Packit bd1cd8
alive. The implication however is that the value must have a copy
Packit bd1cd8
constructor and assignment operator.
Packit bd1cd8
Packit bd1cd8
If the mock method also needs to return a value as well, you can chain
Packit bd1cd8
`SetArgPointee()` with `Return()` using `DoAll()`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Return;
Packit bd1cd8
using ::testing::SetArgPointee;
Packit bd1cd8
Packit bd1cd8
class MockMutator : public Mutator {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  MOCK_METHOD1(MutateInt, bool(int* value));
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockMutator mutator;
Packit bd1cd8
  EXPECT_CALL(mutator, MutateInt(_))
Packit bd1cd8
      .WillOnce(DoAll(SetArgPointee<0>(5),
Packit bd1cd8
                      Return(true)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If the output argument is an array, use the
Packit bd1cd8
`SetArrayArgument<N>(first, last)` action instead. It copies the
Packit bd1cd8
elements in source range `[first, last)` to the array pointed to by
Packit bd1cd8
the `N`-th (0-based) argument:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::NotNull;
Packit bd1cd8
using ::testing::SetArrayArgument;
Packit bd1cd8
Packit bd1cd8
class MockArrayMutator : public ArrayMutator {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD2(Mutate, void(int* values, int num_values));
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockArrayMutator mutator;
Packit bd1cd8
  int values[5] = { 1, 2, 3, 4, 5 };
Packit bd1cd8
  EXPECT_CALL(mutator, Mutate(NotNull(), 5))
Packit bd1cd8
      .WillOnce(SetArrayArgument<0>(values, values + 5));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
This also works when the argument is an output iterator:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::SeArrayArgument;
Packit bd1cd8
Packit bd1cd8
class MockRolodex : public Rolodex {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >));
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockRolodex rolodex;
Packit bd1cd8
  vector<string> names;
Packit bd1cd8
  names.push_back("George");
Packit bd1cd8
  names.push_back("John");
Packit bd1cd8
  names.push_back("Thomas");
Packit bd1cd8
  EXPECT_CALL(rolodex, GetNames(_))
Packit bd1cd8
      .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Changing a Mock Object's Behavior Based on the State ##
Packit bd1cd8
Packit bd1cd8
If you expect a call to change the behavior of a mock object, you can use `::testing::InSequence` to specify different behaviors before and after the call:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::InSequence;
Packit bd1cd8
using ::testing::Return;
Packit bd1cd8
Packit bd1cd8
...
Packit bd1cd8
  {
Packit bd1cd8
    InSequence seq;
Packit bd1cd8
    EXPECT_CALL(my_mock, IsDirty())
Packit bd1cd8
        .WillRepeatedly(Return(true));
Packit bd1cd8
    EXPECT_CALL(my_mock, Flush());
Packit bd1cd8
    EXPECT_CALL(my_mock, IsDirty())
Packit bd1cd8
        .WillRepeatedly(Return(false));
Packit bd1cd8
  }
Packit bd1cd8
  my_mock.FlushIfDirty();
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards.
Packit bd1cd8
Packit bd1cd8
If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::SaveArg;
Packit bd1cd8
using ::testing::Return;
Packit bd1cd8
Packit bd1cd8
ACTION_P(ReturnPointee, p) { return *p; }
Packit bd1cd8
...
Packit bd1cd8
  int previous_value = 0;
Packit bd1cd8
  EXPECT_CALL(my_mock, GetPrevValue())
Packit bd1cd8
      .WillRepeatedly(ReturnPointee(&previous_value));
Packit bd1cd8
  EXPECT_CALL(my_mock, UpdateValue(_))
Packit bd1cd8
      .WillRepeatedly(SaveArg<0>(&previous_value));
Packit bd1cd8
  my_mock.DoSomethingToUpdateValue();
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call.
Packit bd1cd8
Packit bd1cd8
## Setting the Default Value for a Return Type ##
Packit bd1cd8
Packit bd1cd8
If a mock method's return type is a built-in C++ type or pointer, by
Packit bd1cd8
default it will return 0 when invoked. You only need to specify an
Packit bd1cd8
action if this default value doesn't work for you.
Packit bd1cd8
Packit bd1cd8
Sometimes, you may want to change this default value, or you may want
Packit bd1cd8
to specify a default value for types Google Mock doesn't know
Packit bd1cd8
about. You can do this using the `::testing::DefaultValue` class
Packit bd1cd8
template:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD0(CalculateBar, Bar());
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  Bar default_bar;
Packit bd1cd8
  // Sets the default return value for type Bar.
Packit bd1cd8
  DefaultValue<Bar>::Set(default_bar);
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
Packit bd1cd8
  // We don't need to specify an action here, as the default
Packit bd1cd8
  // return value works for us.
Packit bd1cd8
  EXPECT_CALL(foo, CalculateBar());
Packit bd1cd8
Packit bd1cd8
  foo.CalculateBar();  // This should return default_bar.
Packit bd1cd8
Packit bd1cd8
  // Unsets the default return value.
Packit bd1cd8
  DefaultValue<Bar>::Clear();
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Please note that changing the default value for a type can make you
Packit bd1cd8
tests hard to understand. We recommend you to use this feature
Packit bd1cd8
judiciously. For example, you may want to make sure the `Set()` and
Packit bd1cd8
`Clear()` calls are right next to the code that uses your mock.
Packit bd1cd8
Packit bd1cd8
## Setting the Default Actions for a Mock Method ##
Packit bd1cd8
Packit bd1cd8
You've learned how to change the default value of a given
Packit bd1cd8
type. However, this may be too coarse for your purpose: perhaps you
Packit bd1cd8
have two mock methods with the same return type and you want them to
Packit bd1cd8
have different behaviors. The `ON_CALL()` macro allows you to
Packit bd1cd8
customize your mock's behavior at the method level:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::AnyNumber;
Packit bd1cd8
using ::testing::Gt;
Packit bd1cd8
using ::testing::Return;
Packit bd1cd8
...
Packit bd1cd8
  ON_CALL(foo, Sign(_))
Packit bd1cd8
      .WillByDefault(Return(-1));
Packit bd1cd8
  ON_CALL(foo, Sign(0))
Packit bd1cd8
      .WillByDefault(Return(0));
Packit bd1cd8
  ON_CALL(foo, Sign(Gt(0)))
Packit bd1cd8
      .WillByDefault(Return(1));
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, Sign(_))
Packit bd1cd8
      .Times(AnyNumber());
Packit bd1cd8
Packit bd1cd8
  foo.Sign(5);   // This should return 1.
Packit bd1cd8
  foo.Sign(-9);  // This should return -1.
Packit bd1cd8
  foo.Sign(0);   // This should return 0.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
As you may have guessed, when there are more than one `ON_CALL()`
Packit bd1cd8
statements, the news order take precedence over the older ones. In
Packit bd1cd8
other words, the **last** one that matches the function arguments will
Packit bd1cd8
be used. This matching order allows you to set up the common behavior
Packit bd1cd8
in a mock object's constructor or the test fixture's set-up phase and
Packit bd1cd8
specialize the mock's behavior later.
Packit bd1cd8
Packit bd1cd8
## Using Functions/Methods/Functors as Actions ##
Packit bd1cd8
Packit bd1cd8
If the built-in actions don't suit you, you can easily use an existing
Packit bd1cd8
function, method, or functor as an action:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD2(Sum, int(int x, int y));
Packit bd1cd8
  MOCK_METHOD1(ComplexJob, bool(int x));
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
int CalculateSum(int x, int y) { return x + y; }
Packit bd1cd8
Packit bd1cd8
class Helper {
Packit bd1cd8
 public:
Packit bd1cd8
  bool ComplexJob(int x);
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  Helper helper;
Packit bd1cd8
  EXPECT_CALL(foo, Sum(_, _))
Packit bd1cd8
      .WillOnce(Invoke(CalculateSum));
Packit bd1cd8
  EXPECT_CALL(foo, ComplexJob(_))
Packit bd1cd8
      .WillOnce(Invoke(&helper, &Helper::ComplexJob));
Packit bd1cd8
Packit bd1cd8
  foo.Sum(5, 6);       // Invokes CalculateSum(5, 6).
Packit bd1cd8
  foo.ComplexJob(10);  // Invokes helper.ComplexJob(10);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The only requirement is that the type of the function, etc must be
Packit bd1cd8
_compatible_ with the signature of the mock function, meaning that the
Packit bd1cd8
latter's arguments can be implicitly converted to the corresponding
Packit bd1cd8
arguments of the former, and the former's return type can be
Packit bd1cd8
implicitly converted to that of the latter. So, you can invoke
Packit bd1cd8
something whose type is _not_ exactly the same as the mock function,
Packit bd1cd8
as long as it's safe to do so - nice, huh?
Packit bd1cd8
Packit bd1cd8
## Invoking a Function/Method/Functor Without Arguments ##
Packit bd1cd8
Packit bd1cd8
`Invoke()` is very useful for doing actions that are more complex. It
Packit bd1cd8
passes the mock function's arguments to the function or functor being
Packit bd1cd8
invoked such that the callee has the full context of the call to work
Packit bd1cd8
with. If the invoked function is not interested in some or all of the
Packit bd1cd8
arguments, it can simply ignore them.
Packit bd1cd8
Packit bd1cd8
Yet, a common pattern is that a test author wants to invoke a function
Packit bd1cd8
without the arguments of the mock function. `Invoke()` allows her to
Packit bd1cd8
do that using a wrapper function that throws away the arguments before
Packit bd1cd8
invoking an underlining nullary function. Needless to say, this can be
Packit bd1cd8
tedious and obscures the intent of the test.
Packit bd1cd8
Packit bd1cd8
`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except
Packit bd1cd8
that it doesn't pass the mock function's arguments to the
Packit bd1cd8
callee. Here's an example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::InvokeWithoutArgs;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD1(ComplexJob, bool(int n));
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
bool Job1() { ... }
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  EXPECT_CALL(foo, ComplexJob(_))
Packit bd1cd8
      .WillOnce(InvokeWithoutArgs(Job1));
Packit bd1cd8
Packit bd1cd8
  foo.ComplexJob(10);  // Invokes Job1().
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Invoking an Argument of the Mock Function ##
Packit bd1cd8
Packit bd1cd8
Sometimes a mock function will receive a function pointer or a functor
Packit bd1cd8
(in other words, a "callable") as an argument, e.g.
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int)));
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
and you may want to invoke this callable argument:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
...
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(_, _))
Packit bd1cd8
      .WillOnce(...);
Packit bd1cd8
  // Will execute (*fp)(5), where fp is the
Packit bd1cd8
  // second argument DoThis() receives.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Arghh, you need to refer to a mock function argument but C++ has no
Packit bd1cd8
lambda (yet), so you have to define your own action. :-( Or do you
Packit bd1cd8
really?
Packit bd1cd8
Packit bd1cd8
Well, Google Mock has an action to solve _exactly_ this problem:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  InvokeArgument<N>(arg_1, arg_2, ..., arg_m)
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
will invoke the `N`-th (0-based) argument the mock function receives,
Packit bd1cd8
with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is
Packit bd1cd8
a function pointer or a functor, Google Mock handles them both.
Packit bd1cd8
Packit bd1cd8
With that, you could write:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::InvokeArgument;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(_, _))
Packit bd1cd8
      .WillOnce(InvokeArgument<1>(5));
Packit bd1cd8
  // Will execute (*fp)(5), where fp is the
Packit bd1cd8
  // second argument DoThis() receives.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
What if the callable takes an argument by reference? No problem - just
Packit bd1cd8
wrap it inside `ByRef()`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
...
Packit bd1cd8
  MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&)));
Packit bd1cd8
...
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::ByRef;
Packit bd1cd8
using ::testing::InvokeArgument;
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  Helper helper;
Packit bd1cd8
  ...
Packit bd1cd8
  EXPECT_CALL(foo, Bar(_))
Packit bd1cd8
      .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
Packit bd1cd8
  // ByRef(helper) guarantees that a reference to helper, not a copy of it,
Packit bd1cd8
  // will be passed to the callable.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
What if the callable takes an argument by reference and we do **not**
Packit bd1cd8
wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a
Packit bd1cd8
copy_ of the argument, and pass a _reference to the copy_, instead of
Packit bd1cd8
a reference to the original value, to the callable. This is especially
Packit bd1cd8
handy when the argument is a temporary value:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
...
Packit bd1cd8
  MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s)));
Packit bd1cd8
...
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::InvokeArgument;
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  ...
Packit bd1cd8
  EXPECT_CALL(foo, DoThat(_))
Packit bd1cd8
      .WillOnce(InvokeArgument<0>(5.0, string("Hi")));
Packit bd1cd8
  // Will execute (*f)(5.0, string("Hi")), where f is the function pointer
Packit bd1cd8
  // DoThat() receives.  Note that the values 5.0 and string("Hi") are
Packit bd1cd8
  // temporary and dead once the EXPECT_CALL() statement finishes.  Yet
Packit bd1cd8
  // it's fine to perform this action later, since a copy of the values
Packit bd1cd8
  // are kept inside the InvokeArgument action.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Ignoring an Action's Result ##
Packit bd1cd8
Packit bd1cd8
Sometimes you have an action that returns _something_, but you need an
Packit bd1cd8
action that returns `void` (perhaps you want to use it in a mock
Packit bd1cd8
function that returns `void`, or perhaps it needs to be used in
Packit bd1cd8
`DoAll()` and it's not the last in the list). `IgnoreResult()` lets
Packit bd1cd8
you do that. For example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
using ::testing::Return;
Packit bd1cd8
Packit bd1cd8
int Process(const MyData& data);
Packit bd1cd8
string DoSomething();
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD1(Abc, void(const MyData& data));
Packit bd1cd8
  MOCK_METHOD0(Xyz, bool());
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  EXPECT_CALL(foo, Abc(_))
Packit bd1cd8
  // .WillOnce(Invoke(Process));
Packit bd1cd8
  // The above line won't compile as Process() returns int but Abc() needs
Packit bd1cd8
  // to return void.
Packit bd1cd8
      .WillOnce(IgnoreResult(Invoke(Process)));
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, Xyz())
Packit bd1cd8
      .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)),
Packit bd1cd8
      // Ignores the string DoSomething() returns.
Packit bd1cd8
                      Return(true)));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Note that you **cannot** use `IgnoreResult()` on an action that already
Packit bd1cd8
returns `void`. Doing so will lead to ugly compiler errors.
Packit bd1cd8
Packit bd1cd8
## Selecting an Action's Arguments ##
Packit bd1cd8
Packit bd1cd8
Say you have a mock function `Foo()` that takes seven arguments, and
Packit bd1cd8
you have a custom action that you want to invoke when `Foo()` is
Packit bd1cd8
called. Trouble is, the custom action only wants three arguments:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
...
Packit bd1cd8
  MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y,
Packit bd1cd8
                         const map<pair<int, int>, double>& weight,
Packit bd1cd8
                         double min_weight, double max_wight));
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
bool IsVisibleInQuadrant1(bool visible, int x, int y) {
Packit bd1cd8
  return visible && x >= 0 && y >= 0;
Packit bd1cd8
}
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
Packit bd1cd8
      .WillOnce(Invoke(IsVisibleInQuadrant1));  // Uh, won't compile. :-(
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
To please the compiler God, you can to define an "adaptor" that has
Packit bd1cd8
the same signature as `Foo()` and calls the custom action with the
Packit bd1cd8
right arguments:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
Packit bd1cd8
bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,
Packit bd1cd8
                            const map<pair<int, int>, double>& weight,
Packit bd1cd8
                            double min_weight, double max_wight) {
Packit bd1cd8
  return IsVisibleInQuadrant1(visible, x, y);
Packit bd1cd8
}
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
Packit bd1cd8
      .WillOnce(Invoke(MyIsVisibleInQuadrant1));  // Now it works.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
But isn't this awkward?
Packit bd1cd8
Packit bd1cd8
Google Mock provides a generic _action adaptor_, so you can spend your
Packit bd1cd8
time minding more important business than writing your own
Packit bd1cd8
adaptors. Here's the syntax:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  WithArgs<N1, N2, ..., Nk>(action)
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
creates an action that passes the arguments of the mock function at
Packit bd1cd8
the given indices (0-based) to the inner `action` and performs
Packit bd1cd8
it. Using `WithArgs`, our original example can be written as:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
using ::testing::WithArgs;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
Packit bd1cd8
      .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));
Packit bd1cd8
      // No need to define your own adaptor.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
For better readability, Google Mock also gives you:
Packit bd1cd8
Packit bd1cd8
  * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and
Packit bd1cd8
  * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument.
Packit bd1cd8
Packit bd1cd8
As you may have realized, `InvokeWithoutArgs(...)` is just syntactic
Packit bd1cd8
sugar for `WithoutArgs(Inovke(...))`.
Packit bd1cd8
Packit bd1cd8
Here are more tips:
Packit bd1cd8
Packit bd1cd8
  * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything.
Packit bd1cd8
  * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`.
Packit bd1cd8
  * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`.
Packit bd1cd8
  * The types of the selected arguments do _not_ have to match the signature of the inner action exactly. It works as long as they can be implicitly converted to the corresponding arguments of the inner action. For example, if the 4-th argument of the mock function is an `int` and `my_action` takes a `double`, `WithArg<4>(my_action)` will work.
Packit bd1cd8
Packit bd1cd8
## Ignoring Arguments in Action Functions ##
Packit bd1cd8
Packit bd1cd8
The selecting-an-action's-arguments recipe showed us one way to make a
Packit bd1cd8
mock function and an action with incompatible argument lists fit
Packit bd1cd8
together. The downside is that wrapping the action in
Packit bd1cd8
`WithArgs<...>()` can get tedious for people writing the tests.
Packit bd1cd8
Packit bd1cd8
If you are defining a function, method, or functor to be used with
Packit bd1cd8
`Invoke*()`, and you are not interested in some of its arguments, an
Packit bd1cd8
alternative to `WithArgs` is to declare the uninteresting arguments as
Packit bd1cd8
`Unused`. This makes the definition less cluttered and less fragile in
Packit bd1cd8
case the types of the uninteresting arguments change. It could also
Packit bd1cd8
increase the chance the action function can be reused. For example,
Packit bd1cd8
given
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  MOCK_METHOD3(Foo, double(const string& label, double x, double y));
Packit bd1cd8
  MOCK_METHOD3(Bar, double(int index, double x, double y));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
instead of
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
Packit bd1cd8
double DistanceToOriginWithLabel(const string& label, double x, double y) {
Packit bd1cd8
  return sqrt(x*x + y*y);
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
double DistanceToOriginWithIndex(int index, double x, double y) {
Packit bd1cd8
  return sqrt(x*x + y*y);
Packit bd1cd8
}
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXEPCT_CALL(mock, Foo("abc", _, _))
Packit bd1cd8
      .WillOnce(Invoke(DistanceToOriginWithLabel));
Packit bd1cd8
  EXEPCT_CALL(mock, Bar(5, _, _))
Packit bd1cd8
      .WillOnce(Invoke(DistanceToOriginWithIndex));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
you could write
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Invoke;
Packit bd1cd8
using ::testing::Unused;
Packit bd1cd8
Packit bd1cd8
double DistanceToOrigin(Unused, double x, double y) {
Packit bd1cd8
  return sqrt(x*x + y*y);
Packit bd1cd8
}
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXEPCT_CALL(mock, Foo("abc", _, _))
Packit bd1cd8
      .WillOnce(Invoke(DistanceToOrigin));
Packit bd1cd8
  EXEPCT_CALL(mock, Bar(5, _, _))
Packit bd1cd8
      .WillOnce(Invoke(DistanceToOrigin));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Sharing Actions ##
Packit bd1cd8
Packit bd1cd8
Just like matchers, a Google Mock action object consists of a pointer
Packit bd1cd8
to a ref-counted implementation object. Therefore copying actions is
Packit bd1cd8
also allowed and very efficient. When the last action that references
Packit bd1cd8
the implementation object dies, the implementation object will be
Packit bd1cd8
deleted.
Packit bd1cd8
Packit bd1cd8
If you have some complex action that you want to use again and again,
Packit bd1cd8
you may not have to build it from scratch everytime. If the action
Packit bd1cd8
doesn't have an internal state (i.e. if it always does the same thing
Packit bd1cd8
no matter how many times it has been called), you can assign it to an
Packit bd1cd8
action variable and use that variable repeatedly. For example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5),
Packit bd1cd8
                                      Return(true));
Packit bd1cd8
  ... use set_flag in .WillOnce() and .WillRepeatedly() ...
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
However, if the action has its own state, you may be surprised if you
Packit bd1cd8
share the action object. Suppose you have an action factory
Packit bd1cd8
`IncrementCounter(init)` which creates an action that increments and
Packit bd1cd8
returns a counter whose initial value is `init`, using two actions
Packit bd1cd8
created from the same expression and using a shared action will
Packit bd1cd8
exihibit different behaviors. Example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  EXPECT_CALL(foo, DoThis())
Packit bd1cd8
      .WillRepeatedly(IncrementCounter(0));
Packit bd1cd8
  EXPECT_CALL(foo, DoThat())
Packit bd1cd8
      .WillRepeatedly(IncrementCounter(0));
Packit bd1cd8
  foo.DoThis();  // Returns 1.
Packit bd1cd8
  foo.DoThis();  // Returns 2.
Packit bd1cd8
  foo.DoThat();  // Returns 1 - Blah() uses a different
Packit bd1cd8
                 // counter than Bar()'s.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
versus
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  Action<int()> increment = IncrementCounter(0);
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, DoThis())
Packit bd1cd8
      .WillRepeatedly(increment);
Packit bd1cd8
  EXPECT_CALL(foo, DoThat())
Packit bd1cd8
      .WillRepeatedly(increment);
Packit bd1cd8
  foo.DoThis();  // Returns 1.
Packit bd1cd8
  foo.DoThis();  // Returns 2.
Packit bd1cd8
  foo.DoThat();  // Returns 3 - the counter is shared.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
# Misc Recipes on Using Google Mock #
Packit bd1cd8
Packit bd1cd8
## Making the Compilation Faster ##
Packit bd1cd8
Packit bd1cd8
Believe it or not, the _vast majority_ of the time spent on compiling
Packit bd1cd8
a mock class is in generating its constructor and destructor, as they
Packit bd1cd8
perform non-trivial tasks (e.g. verification of the
Packit bd1cd8
expectations). What's more, mock methods with different signatures
Packit bd1cd8
have different types and thus their constructors/destructors need to
Packit bd1cd8
be generated by the compiler separately. As a result, if you mock many
Packit bd1cd8
different types of methods, compiling your mock class can get really
Packit bd1cd8
slow.
Packit bd1cd8
Packit bd1cd8
If you are experiencing slow compilation, you can move the definition
Packit bd1cd8
of your mock class' constructor and destructor out of the class body
Packit bd1cd8
and into a `.cpp` file. This way, even if you `#include` your mock
Packit bd1cd8
class in N files, the compiler only needs to generate its constructor
Packit bd1cd8
and destructor once, resulting in a much faster compilation.
Packit bd1cd8
Packit bd1cd8
Let's illustrate the idea using an example. Here's the definition of a
Packit bd1cd8
mock class before applying this recipe:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
// File mock_foo.h.
Packit bd1cd8
...
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  // Since we don't declare the constructor or the destructor,
Packit bd1cd8
  // the compiler will generate them in every translation unit
Packit bd1cd8
  // where this mock class is used.
Packit bd1cd8
Packit bd1cd8
  MOCK_METHOD0(DoThis, int());
Packit bd1cd8
  MOCK_METHOD1(DoThat, bool(const char* str));
Packit bd1cd8
  ... more mock methods ...
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
After the change, it would look like:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
// File mock_foo.h.
Packit bd1cd8
...
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  // The constructor and destructor are declared, but not defined, here.
Packit bd1cd8
  MockFoo();
Packit bd1cd8
  virtual ~MockFoo();
Packit bd1cd8
Packit bd1cd8
  MOCK_METHOD0(DoThis, int());
Packit bd1cd8
  MOCK_METHOD1(DoThat, bool(const char* str));
Packit bd1cd8
  ... more mock methods ...
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
and
Packit bd1cd8
```
Packit bd1cd8
// File mock_foo.cpp.
Packit bd1cd8
#include "path/to/mock_foo.h"
Packit bd1cd8
Packit bd1cd8
// The definitions may appear trivial, but the functions actually do a
Packit bd1cd8
// lot of things through the constructors/destructors of the member
Packit bd1cd8
// variables used to implement the mock methods.
Packit bd1cd8
MockFoo::MockFoo() {}
Packit bd1cd8
MockFoo::~MockFoo() {}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Forcing a Verification ##
Packit bd1cd8
Packit bd1cd8
When it's being destoyed, your friendly mock object will automatically
Packit bd1cd8
verify that all expectations on it have been satisfied, and will
Packit bd1cd8
generate [Google Test](http://code.google.com/p/googletest/) failures
Packit bd1cd8
if not. This is convenient as it leaves you with one less thing to
Packit bd1cd8
worry about. That is, unless you are not sure if your mock object will
Packit bd1cd8
be destoyed.
Packit bd1cd8
Packit bd1cd8
How could it be that your mock object won't eventually be destroyed?
Packit bd1cd8
Well, it might be created on the heap and owned by the code you are
Packit bd1cd8
testing. Suppose there's a bug in that code and it doesn't delete the
Packit bd1cd8
mock object properly - you could end up with a passing test when
Packit bd1cd8
there's actually a bug.
Packit bd1cd8
Packit bd1cd8
Using a heap checker is a good idea and can alleviate the concern, but
Packit bd1cd8
its implementation may not be 100% reliable. So, sometimes you do want
Packit bd1cd8
to _force_ Google Mock to verify a mock object before it is
Packit bd1cd8
(hopefully) destructed. You can do this with
Packit bd1cd8
`Mock::VerifyAndClearExpectations(&mock_object)`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
TEST(MyServerTest, ProcessesRequest) {
Packit bd1cd8
  using ::testing::Mock;
Packit bd1cd8
Packit bd1cd8
  MockFoo* const foo = new MockFoo;
Packit bd1cd8
  EXPECT_CALL(*foo, ...)...;
Packit bd1cd8
  // ... other expectations ...
Packit bd1cd8
Packit bd1cd8
  // server now owns foo.
Packit bd1cd8
  MyServer server(foo);
Packit bd1cd8
  server.ProcessRequest(...);
Packit bd1cd8
Packit bd1cd8
  // In case that server's destructor will forget to delete foo,
Packit bd1cd8
  // this will verify the expectations anyway.
Packit bd1cd8
  Mock::VerifyAndClearExpectations(foo);
Packit bd1cd8
}  // server is destroyed when it goes out of scope here.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a
Packit bd1cd8
`bool` to indicate whether the verification was successful (`true` for
Packit bd1cd8
yes), so you can wrap that function call inside a `ASSERT_TRUE()` if
Packit bd1cd8
there is no point going further when the verification has failed.
Packit bd1cd8
Packit bd1cd8
## Using Check Points ##
Packit bd1cd8
Packit bd1cd8
Sometimes you may want to "reset" a mock object at various check
Packit bd1cd8
points in your test: at each check point, you verify that all existing
Packit bd1cd8
expectations on the mock object have been satisfied, and then you set
Packit bd1cd8
some new expectations on it as if it's newly created. This allows you
Packit bd1cd8
to work with a mock object in "phases" whose sizes are each
Packit bd1cd8
manageable.
Packit bd1cd8
Packit bd1cd8
One such scenario is that in your test's `SetUp()` function, you may
Packit bd1cd8
want to put the object you are testing into a certain state, with the
Packit bd1cd8
help from a mock object. Once in the desired state, you want to clear
Packit bd1cd8
all expectations on the mock, such that in the `TEST_F` body you can
Packit bd1cd8
set fresh expectations on it.
Packit bd1cd8
Packit bd1cd8
As you may have figured out, the `Mock::VerifyAndClearExpectations()`
Packit bd1cd8
function we saw in the previous recipe can help you here. Or, if you
Packit bd1cd8
are using `ON_CALL()` to set default actions on the mock object and
Packit bd1cd8
want to clear the default actions as well, use
Packit bd1cd8
`Mock::VerifyAndClear(&mock_object)` instead. This function does what
Packit bd1cd8
`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the
Packit bd1cd8
same `bool`, **plus** it clears the `ON_CALL()` statements on
Packit bd1cd8
`mock_object` too.
Packit bd1cd8
Packit bd1cd8
Another trick you can use to achieve the same effect is to put the
Packit bd1cd8
expectations in sequences and insert calls to a dummy "check-point"
Packit bd1cd8
function at specific places. Then you can verify that the mock
Packit bd1cd8
function calls do happen at the right time. For example, if you are
Packit bd1cd8
exercising code:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
Foo(1);
Packit bd1cd8
Foo(2);
Packit bd1cd8
Foo(3);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
and want to verify that `Foo(1)` and `Foo(3)` both invoke
Packit bd1cd8
`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::MockFunction;
Packit bd1cd8
Packit bd1cd8
TEST(FooTest, InvokesBarCorrectly) {
Packit bd1cd8
  MyMock mock;
Packit bd1cd8
  // Class MockFunction<F> has exactly one mock method.  It is named
Packit bd1cd8
  // Call() and has type F.
Packit bd1cd8
  MockFunction<void(string check_point_name)> check;
Packit bd1cd8
  {
Packit bd1cd8
    InSequence s;
Packit bd1cd8
Packit bd1cd8
    EXPECT_CALL(mock, Bar("a"));
Packit bd1cd8
    EXPECT_CALL(check, Call("1"));
Packit bd1cd8
    EXPECT_CALL(check, Call("2"));
Packit bd1cd8
    EXPECT_CALL(mock, Bar("a"));
Packit bd1cd8
  }
Packit bd1cd8
  Foo(1);
Packit bd1cd8
  check.Call("1");
Packit bd1cd8
  Foo(2);
Packit bd1cd8
  check.Call("2");
Packit bd1cd8
  Foo(3);
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The expectation spec says that the first `Bar("a")` must happen before
Packit bd1cd8
check point "1", the second `Bar("a")` must happen after check point "2",
Packit bd1cd8
and nothing should happen between the two check points. The explicit
Packit bd1cd8
check points make it easy to tell which `Bar("a")` is called by which
Packit bd1cd8
call to `Foo()`.
Packit bd1cd8
Packit bd1cd8
## Mocking Destructors ##
Packit bd1cd8
Packit bd1cd8
Sometimes you want to make sure a mock object is destructed at the
Packit bd1cd8
right time, e.g. after `bar->A()` is called but before `bar->B()` is
Packit bd1cd8
called. We already know that you can specify constraints on the order
Packit bd1cd8
of mock function calls, so all we need to do is to mock the destructor
Packit bd1cd8
of the mock function.
Packit bd1cd8
Packit bd1cd8
This sounds simple, except for one problem: a destructor is a special
Packit bd1cd8
function with special syntax and special semantics, and the
Packit bd1cd8
`MOCK_METHOD0` macro doesn't work for it:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  MOCK_METHOD0(~MockFoo, void());  // Won't compile!
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
The good news is that you can use a simple pattern to achieve the same
Packit bd1cd8
effect. First, add a mock function `Die()` to your mock class and call
Packit bd1cd8
it in the destructor, like this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
  ...
Packit bd1cd8
  // Add the following two lines to the mock class.
Packit bd1cd8
  MOCK_METHOD0(Die, void());
Packit bd1cd8
  virtual ~MockFoo() { Die(); }
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
(If the name `Die()` clashes with an existing symbol, choose another
Packit bd1cd8
name.) Now, we have translated the problem of testing when a `MockFoo`
Packit bd1cd8
object dies to testing when its `Die()` method is called:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  MockFoo* foo = new MockFoo;
Packit bd1cd8
  MockBar* bar = new MockBar;
Packit bd1cd8
  ...
Packit bd1cd8
  {
Packit bd1cd8
    InSequence s;
Packit bd1cd8
Packit bd1cd8
    // Expects *foo to die after bar->A() and before bar->B().
Packit bd1cd8
    EXPECT_CALL(*bar, A());
Packit bd1cd8
    EXPECT_CALL(*foo, Die());
Packit bd1cd8
    EXPECT_CALL(*bar, B());
Packit bd1cd8
  }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
And that's that.
Packit bd1cd8
Packit bd1cd8
## Using Google Mock and Threads ##
Packit bd1cd8
Packit bd1cd8
**IMPORTANT NOTE:** What we describe in this recipe is **ONLY** true on
Packit bd1cd8
platforms where Google Mock is thread-safe. Currently these are only
Packit bd1cd8
platforms that support the pthreads library (this includes Linux and Mac).
Packit bd1cd8
To make it thread-safe on other platforms we only need to implement
Packit bd1cd8
some synchronization operations in `"gtest/internal/gtest-port.h"`.
Packit bd1cd8
Packit bd1cd8
In a **unit** test, it's best if you could isolate and test a piece of
Packit bd1cd8
code in a single-threaded context. That avoids race conditions and
Packit bd1cd8
dead locks, and makes debugging your test much easier.
Packit bd1cd8
Packit bd1cd8
Yet many programs are multi-threaded, and sometimes to test something
Packit bd1cd8
we need to pound on it from more than one thread. Google Mock works
Packit bd1cd8
for this purpose too.
Packit bd1cd8
Packit bd1cd8
Remember the steps for using a mock:
Packit bd1cd8
Packit bd1cd8
  1. Create a mock object `foo`.
Packit bd1cd8
  1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`.
Packit bd1cd8
  1. The code under test calls methods of `foo`.
Packit bd1cd8
  1. Optionally, verify and reset the mock.
Packit bd1cd8
  1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it.
Packit bd1cd8
Packit bd1cd8
If you follow the following simple rules, your mocks and threads can
Packit bd1cd8
live happily togeter:
Packit bd1cd8
Packit bd1cd8
  * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow.
Packit bd1cd8
  * Obviously, you can do step #1 without locking.
Packit bd1cd8
  * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh?
Packit bd1cd8
  * #3 and #4 can be done either in one thread or in multiple threads - anyway you want. Google Mock takes care of the locking, so you don't have to do any - unless required by your test logic.
Packit bd1cd8
Packit bd1cd8
If you violate the rules (for example, if you set expectations on a
Packit bd1cd8
mock while another thread is calling its methods), you get undefined
Packit bd1cd8
behavior. That's not fun, so don't do it.
Packit bd1cd8
Packit bd1cd8
Google Mock guarantees that the action for a mock function is done in
Packit bd1cd8
the same thread that called the mock function. For example, in
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  EXPECT_CALL(mock, Foo(1))
Packit bd1cd8
      .WillOnce(action1);
Packit bd1cd8
  EXPECT_CALL(mock, Foo(2))
Packit bd1cd8
      .WillOnce(action2);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2,
Packit bd1cd8
Google Mock will execute `action1` in thread 1 and `action2` in thread
Packit bd1cd8
2.
Packit bd1cd8
Packit bd1cd8
Google Mock does _not_ impose a sequence on actions performed in
Packit bd1cd8
different threads (doing so may create deadlocks as the actions may
Packit bd1cd8
need to cooperate). This means that the execution of `action1` and
Packit bd1cd8
`action2` in the above example _may_ interleave. If this is a problem,
Packit bd1cd8
you should add proper synchronization logic to `action1` and `action2`
Packit bd1cd8
to make the test thread-safe.
Packit bd1cd8
Packit bd1cd8
Packit bd1cd8
Also, remember that `DefaultValue<T>` is a global resource that
Packit bd1cd8
potentially affects _all_ living mock objects in your
Packit bd1cd8
program. Naturally, you won't want to mess with it from multiple
Packit bd1cd8
threads or when there still are mocks in action.
Packit bd1cd8
Packit bd1cd8
## Controlling How Much Information Google Mock Prints ##
Packit bd1cd8
Packit bd1cd8
When Google Mock sees something that has the potential of being an
Packit bd1cd8
error (e.g. a mock function with no expectation is called, a.k.a. an
Packit bd1cd8
uninteresting call, which is allowed but perhaps you forgot to
Packit bd1cd8
explicitly ban the call), it prints some warning messages, including
Packit bd1cd8
the arguments of the function and the return value. Hopefully this
Packit bd1cd8
will remind you to take a look and see if there is indeed a problem.
Packit bd1cd8
Packit bd1cd8
Sometimes you are confident that your tests are correct and may not
Packit bd1cd8
appreciate such friendly messages. Some other times, you are debugging
Packit bd1cd8
your tests or learning about the behavior of the code you are testing,
Packit bd1cd8
and wish you could observe every mock call that happens (including
Packit bd1cd8
argument values and the return value). Clearly, one size doesn't fit
Packit bd1cd8
all.
Packit bd1cd8
Packit bd1cd8
You can control how much Google Mock tells you using the
Packit bd1cd8
`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string
Packit bd1cd8
with three possible values:
Packit bd1cd8
Packit bd1cd8
  * `info`: Google Mock will print all informational messages, warnings, and errors (most verbose). At this setting, Google Mock will also log any calls to the `ON_CALL/EXPECT_CALL` macros.
Packit bd1cd8
  * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default.
Packit bd1cd8
  * `error`: Google Mock will print errors only (least verbose).
Packit bd1cd8
Packit bd1cd8
Alternatively, you can adjust the value of that flag from within your
Packit bd1cd8
tests like so:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  ::testing::FLAGS_gmock_verbose = "error";
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Now, judiciously use the right flag to enable Google Mock serve you better!
Packit bd1cd8
Packit bd1cd8
## Gaining Super Vision into Mock Calls ##
Packit bd1cd8
Packit bd1cd8
You have a test using Google Mock. It fails: Google Mock tells you
Packit bd1cd8
that some expectations aren't satisfied. However, you aren't sure why:
Packit bd1cd8
Is there a typo somewhere in the matchers? Did you mess up the order
Packit bd1cd8
of the `EXPECT_CALL`s? Or is the code under test doing something
Packit bd1cd8
wrong?  How can you find out the cause?
Packit bd1cd8
Packit bd1cd8
Won't it be nice if you have X-ray vision and can actually see the
Packit bd1cd8
trace of all `EXPECT_CALL`s and mock method calls as they are made?
Packit bd1cd8
For each call, would you like to see its actual argument values and
Packit bd1cd8
which `EXPECT_CALL` Google Mock thinks it matches?
Packit bd1cd8
Packit bd1cd8
You can unlock this power by running your test with the
Packit bd1cd8
`--gmock_verbose=info` flag. For example, given the test program:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using testing::_;
Packit bd1cd8
using testing::HasSubstr;
Packit bd1cd8
using testing::Return;
Packit bd1cd8
Packit bd1cd8
class MockFoo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD2(F, void(const string& x, const string& y));
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
TEST(Foo, Bar) {
Packit bd1cd8
  MockFoo mock;
Packit bd1cd8
  EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return());
Packit bd1cd8
  EXPECT_CALL(mock, F("a", "b"));
Packit bd1cd8
  EXPECT_CALL(mock, F("c", HasSubstr("d")));
Packit bd1cd8
Packit bd1cd8
  mock.F("a", "good");
Packit bd1cd8
  mock.F("a", "b");
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
if you run it with `--gmock_verbose=info`, you will see this output:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
[ RUN      ] Foo.Bar
Packit bd1cd8
Packit bd1cd8
foo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked
Packit bd1cd8
foo_test.cc:15: EXPECT_CALL(mock, F("a", "b")) invoked
Packit bd1cd8
foo_test.cc:16: EXPECT_CALL(mock, F("c", HasSubstr("d"))) invoked
Packit bd1cd8
foo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))...
Packit bd1cd8
    Function call: F(@0x7fff7c8dad40"a", @0x7fff7c8dad10"good")
Packit bd1cd8
foo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F("a", "b"))...
Packit bd1cd8
    Function call: F(@0x7fff7c8dada0"a", @0x7fff7c8dad70"b")
Packit bd1cd8
foo_test.cc:16: Failure
Packit bd1cd8
Actual function call count doesn't match EXPECT_CALL(mock, F("c", HasSubstr("d")))...
Packit bd1cd8
         Expected: to be called once
Packit bd1cd8
           Actual: never called - unsatisfied and active
Packit bd1cd8
[  FAILED  ] Foo.Bar
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Suppose the bug is that the `"c"` in the third `EXPECT_CALL` is a typo
Packit bd1cd8
and should actually be `"a"`. With the above message, you should see
Packit bd1cd8
that the actual `F("a", "good")` call is matched by the first
Packit bd1cd8
`EXPECT_CALL`, not the third as you thought. From that it should be
Packit bd1cd8
obvious that the third `EXPECT_CALL` is written wrong. Case solved.
Packit bd1cd8
Packit bd1cd8
## Running Tests in Emacs ##
Packit bd1cd8
Packit bd1cd8
If you build and run your tests in Emacs, the source file locations of
Packit bd1cd8
Google Mock and [Google Test](http://code.google.com/p/googletest/)
Packit bd1cd8
errors will be highlighted. Just press `<Enter>` on one of them and
Packit bd1cd8
you'll be taken to the offending line. Or, you can just type `C-x ``
Packit bd1cd8
to jump to the next error.
Packit bd1cd8
Packit bd1cd8
To make it even easier, you can add the following lines to your
Packit bd1cd8
`~/.emacs` file:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
(global-set-key "\M-m"   'compile)  ; m is for make
Packit bd1cd8
(global-set-key [M-down] 'next-error)
Packit bd1cd8
(global-set-key [M-up]   '(lambda () (interactive) (next-error -1)))
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Then you can type `M-m` to start a build, or `M-up`/`M-down` to move
Packit bd1cd8
back and forth between errors.
Packit bd1cd8
Packit bd1cd8
## Fusing Google Mock Source Files ##
Packit bd1cd8
Packit bd1cd8
Google Mock's implementation consists of dozens of files (excluding
Packit bd1cd8
its own tests).  Sometimes you may want them to be packaged up in
Packit bd1cd8
fewer files instead, such that you can easily copy them to a new
Packit bd1cd8
machine and start hacking there.  For this we provide an experimental
Packit bd1cd8
Python script `fuse_gmock_files.py` in the `scripts/` directory
Packit bd1cd8
(starting with release 1.2.0).  Assuming you have Python 2.4 or above
Packit bd1cd8
installed on your machine, just go to that directory and run
Packit bd1cd8
```
Packit bd1cd8
python fuse_gmock_files.py OUTPUT_DIR
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
and you should see an `OUTPUT_DIR` directory being created with files
Packit bd1cd8
`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it.
Packit bd1cd8
These three files contain everything you need to use Google Mock (and
Packit bd1cd8
Google Test).  Just copy them to anywhere you want and you are ready
Packit bd1cd8
to write tests and use mocks.  You can use the
Packit bd1cd8
[scrpts/test/Makefile](http://code.google.com/p/googlemock/source/browse/trunk/scripts/test/Makefile) file as an example on how to compile your tests
Packit bd1cd8
against them.
Packit bd1cd8
Packit bd1cd8
# Extending Google Mock #
Packit bd1cd8
Packit bd1cd8
## Writing New Matchers Quickly ##
Packit bd1cd8
Packit bd1cd8
The `MATCHER*` family of macros can be used to define custom matchers
Packit bd1cd8
easily.  The syntax:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
MATCHER(name, description_string_expression) { statements; }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
will define a matcher with the given name that executes the
Packit bd1cd8
statements, which must return a `bool` to indicate if the match
Packit bd1cd8
succeeds.  Inside the statements, you can refer to the value being
Packit bd1cd8
matched by `arg`, and refer to its type by `arg_type`.
Packit bd1cd8
Packit bd1cd8
The description string is a `string`-typed expression that documents
Packit bd1cd8
what the matcher does, and is used to generate the failure message
Packit bd1cd8
when the match fails.  It can (and should) reference the special
Packit bd1cd8
`bool` variable `negation`, and should evaluate to the description of
Packit bd1cd8
the matcher when `negation` is `false`, or that of the matcher's
Packit bd1cd8
negation when `negation` is `true`.
Packit bd1cd8
Packit bd1cd8
For convenience, we allow the description string to be empty (`""`),
Packit bd1cd8
in which case Google Mock will use the sequence of words in the
Packit bd1cd8
matcher name as the description.
Packit bd1cd8
Packit bd1cd8
For example:
Packit bd1cd8
```
Packit bd1cd8
MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
Packit bd1cd8
```
Packit bd1cd8
allows you to write
Packit bd1cd8
```
Packit bd1cd8
  // Expects mock_foo.Bar(n) to be called where n is divisible by 7.
Packit bd1cd8
  EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));
Packit bd1cd8
```
Packit bd1cd8
or,
Packit bd1cd8
```
Packit bd1cd8
using ::testing::Not;
Packit bd1cd8
...
Packit bd1cd8
  EXPECT_THAT(some_expression, IsDivisibleBy7());
Packit bd1cd8
  EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7()));
Packit bd1cd8
```
Packit bd1cd8
If the above assertions fail, they will print something like:
Packit bd1cd8
```
Packit bd1cd8
  Value of: some_expression
Packit bd1cd8
  Expected: is divisible by 7
Packit bd1cd8
    Actual: 27
Packit bd1cd8
...
Packit bd1cd8
  Value of: some_other_expression
Packit bd1cd8
  Expected: not (is divisible by 7)
Packit bd1cd8
    Actual: 21
Packit bd1cd8
```
Packit bd1cd8
where the descriptions `"is divisible by 7"` and `"not (is divisible
Packit bd1cd8
by 7)"` are automatically calculated from the matcher name
Packit bd1cd8
`IsDivisibleBy7`.
Packit bd1cd8
Packit bd1cd8
As you may have noticed, the auto-generated descriptions (especially
Packit bd1cd8
those for the negation) may not be so great. You can always override
Packit bd1cd8
them with a string expression of your own:
Packit bd1cd8
```
Packit bd1cd8
MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") +
Packit bd1cd8
                        " divisible by 7") {
Packit bd1cd8
  return (arg % 7) == 0;
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Optionally, you can stream additional information to a hidden argument
Packit bd1cd8
named `result_listener` to explain the match result. For example, a
Packit bd1cd8
better definition of `IsDivisibleBy7` is:
Packit bd1cd8
```
Packit bd1cd8
MATCHER(IsDivisibleBy7, "") {
Packit bd1cd8
  if ((arg % 7) == 0)
Packit bd1cd8
    return true;
Packit bd1cd8
Packit bd1cd8
  *result_listener << "the remainder is " << (arg % 7);
Packit bd1cd8
  return false;
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
With this definition, the above assertion will give a better message:
Packit bd1cd8
```
Packit bd1cd8
  Value of: some_expression
Packit bd1cd8
  Expected: is divisible by 7
Packit bd1cd8
    Actual: 27 (the remainder is 6)
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
You should let `MatchAndExplain()` print _any additional information_
Packit bd1cd8
that can help a user understand the match result. Note that it should
Packit bd1cd8
explain why the match succeeds in case of a success (unless it's
Packit bd1cd8
obvious) - this is useful when the matcher is used inside
Packit bd1cd8
`Not()`. There is no need to print the argument value itself, as
Packit bd1cd8
Google Mock already prints it for you.
Packit bd1cd8
Packit bd1cd8
**Notes:**
Packit bd1cd8
Packit bd1cd8
  1. The type of the value being matched (`arg_type`) is determined by the context in which you use the matcher and is supplied to you by the compiler, so you don't need to worry about declaring it (nor can you).  This allows the matcher to be polymorphic.  For example, `IsDivisibleBy7()` can be used to match any type where the value of `(arg % 7) == 0` can be implicitly converted to a `bool`.  In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an `int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will be `unsigned long`; and so on.
Packit bd1cd8
  1. Google Mock doesn't guarantee when or how many times a matcher will be invoked. Therefore the matcher logic must be _purely functional_ (i.e. it cannot have any side effect, and the result must not depend on anything other than the value being matched and the matcher parameters). This requirement must be satisfied no matter how you define the matcher (e.g. using one of the methods described in the following recipes). In particular, a matcher can never call a mock function, as that will affect the state of the mock object and Google Mock.
Packit bd1cd8
Packit bd1cd8
## Writing New Parameterized Matchers Quickly ##
Packit bd1cd8
Packit bd1cd8
Sometimes you'll want to define a matcher that has parameters.  For that you
Packit bd1cd8
can use the macro:
Packit bd1cd8
```
Packit bd1cd8
MATCHER_P(name, param_name, description_string) { statements; }
Packit bd1cd8
```
Packit bd1cd8
where the description string can be either `""` or a string expression
Packit bd1cd8
that references `negation` and `param_name`.
Packit bd1cd8
Packit bd1cd8
For example:
Packit bd1cd8
```
Packit bd1cd8
MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
Packit bd1cd8
```
Packit bd1cd8
will allow you to write:
Packit bd1cd8
```
Packit bd1cd8
  EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
Packit bd1cd8
```
Packit bd1cd8
which may lead to this message (assuming `n` is 10):
Packit bd1cd8
```
Packit bd1cd8
  Value of: Blah("a")
Packit bd1cd8
  Expected: has absolute value 10
Packit bd1cd8
    Actual: -9
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Note that both the matcher description and its parameter are
Packit bd1cd8
printed, making the message human-friendly.
Packit bd1cd8
Packit bd1cd8
In the matcher definition body, you can write `foo_type` to
Packit bd1cd8
reference the type of a parameter named `foo`.  For example, in the
Packit bd1cd8
body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write
Packit bd1cd8
`value_type` to refer to the type of `value`.
Packit bd1cd8
Packit bd1cd8
Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to
Packit bd1cd8
`MATCHER_P10` to support multi-parameter matchers:
Packit bd1cd8
```
Packit bd1cd8
MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Please note that the custom description string is for a particular
Packit bd1cd8
**instance** of the matcher, where the parameters have been bound to
Packit bd1cd8
actual values.  Therefore usually you'll want the parameter values to
Packit bd1cd8
be part of the description.  Google Mock lets you do that by
Packit bd1cd8
referencing the matcher parameters in the description string
Packit bd1cd8
expression.
Packit bd1cd8
Packit bd1cd8
For example,
Packit bd1cd8
```
Packit bd1cd8
  using ::testing::PrintToString;
Packit bd1cd8
  MATCHER_P2(InClosedRange, low, hi,
Packit bd1cd8
             std::string(negation ? "isn't" : "is") + " in range [" +
Packit bd1cd8
             PrintToString(low) + ", " + PrintToString(hi) + "]") {
Packit bd1cd8
    return low <= arg && arg <= hi;
Packit bd1cd8
  }
Packit bd1cd8
  ...
Packit bd1cd8
  EXPECT_THAT(3, InClosedRange(4, 6));
Packit bd1cd8
```
Packit bd1cd8
would generate a failure that contains the message:
Packit bd1cd8
```
Packit bd1cd8
  Expected: is in range [4, 6]
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If you specify `""` as the description, the failure message will
Packit bd1cd8
contain the sequence of words in the matcher name followed by the
Packit bd1cd8
parameter values printed as a tuple.  For example,
Packit bd1cd8
```
Packit bd1cd8
  MATCHER_P2(InClosedRange, low, hi, "") { ... }
Packit bd1cd8
  ...
Packit bd1cd8
  EXPECT_THAT(3, InClosedRange(4, 6));
Packit bd1cd8
```
Packit bd1cd8
would generate a failure that contains the text:
Packit bd1cd8
```
Packit bd1cd8
  Expected: in closed range (4, 6)
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
For the purpose of typing, you can view
Packit bd1cd8
```
Packit bd1cd8
MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
Packit bd1cd8
```
Packit bd1cd8
as shorthand for
Packit bd1cd8
```
Packit bd1cd8
template <typename p1_type, ..., typename pk_type>
Packit bd1cd8
FooMatcherPk<p1_type, ..., pk_type>
Packit bd1cd8
Foo(p1_type p1, ..., pk_type pk) { ... }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
When you write `Foo(v1, ..., vk)`, the compiler infers the types of
Packit bd1cd8
the parameters `v1`, ..., and `vk` for you.  If you are not happy with
Packit bd1cd8
the result of the type inference, you can specify the types by
Packit bd1cd8
explicitly instantiating the template, as in `Foo<long, bool>(5, false)`.
Packit bd1cd8
As said earlier, you don't get to (or need to) specify
Packit bd1cd8
`arg_type` as that's determined by the context in which the matcher
Packit bd1cd8
is used.
Packit bd1cd8
Packit bd1cd8
You can assign the result of expression `Foo(p1, ..., pk)` to a
Packit bd1cd8
variable of type `FooMatcherPk<p1_type, ..., pk_type>`.  This can be
Packit bd1cd8
useful when composing matchers.  Matchers that don't have a parameter
Packit bd1cd8
or have only one parameter have special types: you can assign `Foo()`
Packit bd1cd8
to a `FooMatcher`-typed variable, and assign `Foo(p)` to a
Packit bd1cd8
`FooMatcherP<p_type>`-typed variable.
Packit bd1cd8
Packit bd1cd8
While you can instantiate a matcher template with reference types,
Packit bd1cd8
passing the parameters by pointer usually makes your code more
Packit bd1cd8
readable.  If, however, you still want to pass a parameter by
Packit bd1cd8
reference, be aware that in the failure message generated by the
Packit bd1cd8
matcher you will see the value of the referenced object but not its
Packit bd1cd8
address.
Packit bd1cd8
Packit bd1cd8
You can overload matchers with different numbers of parameters:
Packit bd1cd8
```
Packit bd1cd8
MATCHER_P(Blah, a, description_string_1) { ... }
Packit bd1cd8
MATCHER_P2(Blah, a, b, description_string_2) { ... }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
While it's tempting to always use the `MATCHER*` macros when defining
Packit bd1cd8
a new matcher, you should also consider implementing
Packit bd1cd8
`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see
Packit bd1cd8
the recipes that follow), especially if you need to use the matcher a
Packit bd1cd8
lot.  While these approaches require more work, they give you more
Packit bd1cd8
control on the types of the value being matched and the matcher
Packit bd1cd8
parameters, which in general leads to better compiler error messages
Packit bd1cd8
that pay off in the long run.  They also allow overloading matchers
Packit bd1cd8
based on parameter types (as opposed to just based on the number of
Packit bd1cd8
parameters).
Packit bd1cd8
Packit bd1cd8
## Writing New Monomorphic Matchers ##
Packit bd1cd8
Packit bd1cd8
A matcher of argument type `T` implements
Packit bd1cd8
`::testing::MatcherInterface<T>` and does two things: it tests whether a
Packit bd1cd8
value of type `T` matches the matcher, and can describe what kind of
Packit bd1cd8
values it matches. The latter ability is used for generating readable
Packit bd1cd8
error messages when expectations are violated.
Packit bd1cd8
Packit bd1cd8
The interface looks like this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class MatchResultListener {
Packit bd1cd8
 public:
Packit bd1cd8
  ...
Packit bd1cd8
  // Streams x to the underlying ostream; does nothing if the ostream
Packit bd1cd8
  // is NULL.
Packit bd1cd8
  template <typename T>
Packit bd1cd8
  MatchResultListener& operator<<(const T& x);
Packit bd1cd8
Packit bd1cd8
  // Returns the underlying ostream.
Packit bd1cd8
  ::std::ostream* stream();
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
template <typename T>
Packit bd1cd8
class MatcherInterface {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual ~MatcherInterface();
Packit bd1cd8
Packit bd1cd8
  // Returns true iff the matcher matches x; also explains the match
Packit bd1cd8
  // result to 'listener'.
Packit bd1cd8
  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
Packit bd1cd8
Packit bd1cd8
  // Describes this matcher to an ostream.
Packit bd1cd8
  virtual void DescribeTo(::std::ostream* os) const = 0;
Packit bd1cd8
Packit bd1cd8
  // Describes the negation of this matcher to an ostream.
Packit bd1cd8
  virtual void DescribeNegationTo(::std::ostream* os) const;
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If you need a custom matcher but `Truly()` is not a good option (for
Packit bd1cd8
example, you may not be happy with the way `Truly(predicate)`
Packit bd1cd8
describes itself, or you may want your matcher to be polymorphic as
Packit bd1cd8
`Eq(value)` is), you can define a matcher to do whatever you want in
Packit bd1cd8
two steps: first implement the matcher interface, and then define a
Packit bd1cd8
factory function to create a matcher instance. The second step is not
Packit bd1cd8
strictly needed but it makes the syntax of using the matcher nicer.
Packit bd1cd8
Packit bd1cd8
For example, you can define a matcher to test whether an `int` is
Packit bd1cd8
divisible by 7 and then use it like this:
Packit bd1cd8
```
Packit bd1cd8
using ::testing::MakeMatcher;
Packit bd1cd8
using ::testing::Matcher;
Packit bd1cd8
using ::testing::MatcherInterface;
Packit bd1cd8
using ::testing::MatchResultListener;
Packit bd1cd8
Packit bd1cd8
class DivisibleBy7Matcher : public MatcherInterface<int> {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual bool MatchAndExplain(int n, MatchResultListener* listener) const {
Packit bd1cd8
    return (n % 7) == 0;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual void DescribeTo(::std::ostream* os) const {
Packit bd1cd8
    *os << "is divisible by 7";
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual void DescribeNegationTo(::std::ostream* os) const {
Packit bd1cd8
    *os << "is not divisible by 7";
Packit bd1cd8
  }
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
inline Matcher<int> DivisibleBy7() {
Packit bd1cd8
  return MakeMatcher(new DivisibleBy7Matcher);
Packit bd1cd8
}
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, Bar(DivisibleBy7()));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
You may improve the matcher message by streaming additional
Packit bd1cd8
information to the `listener` argument in `MatchAndExplain()`:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class DivisibleBy7Matcher : public MatcherInterface<int> {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual bool MatchAndExplain(int n,
Packit bd1cd8
                               MatchResultListener* listener) const {
Packit bd1cd8
    const int remainder = n % 7;
Packit bd1cd8
    if (remainder != 0) {
Packit bd1cd8
      *listener << "the remainder is " << remainder;
Packit bd1cd8
    }
Packit bd1cd8
    return remainder == 0;
Packit bd1cd8
  }
Packit bd1cd8
  ...
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this:
Packit bd1cd8
```
Packit bd1cd8
Value of: x
Packit bd1cd8
Expected: is divisible by 7
Packit bd1cd8
  Actual: 23 (the remainder is 2)
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Writing New Polymorphic Matchers ##
Packit bd1cd8
Packit bd1cd8
You've learned how to write your own matchers in the previous
Packit bd1cd8
recipe. Just one problem: a matcher created using `MakeMatcher()` only
Packit bd1cd8
works for one particular type of arguments. If you want a
Packit bd1cd8
_polymorphic_ matcher that works with arguments of several types (for
Packit bd1cd8
instance, `Eq(x)` can be used to match a `value` as long as `value` ==
Packit bd1cd8
`x` compiles -- `value` and `x` don't have to share the same type),
Packit bd1cd8
you can learn the trick from `"gmock/gmock-matchers.h"` but it's a bit
Packit bd1cd8
involved.
Packit bd1cd8
Packit bd1cd8
Fortunately, most of the time you can define a polymorphic matcher
Packit bd1cd8
easily with the help of `MakePolymorphicMatcher()`. Here's how you can
Packit bd1cd8
define `NotNull()` as an example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::MakePolymorphicMatcher;
Packit bd1cd8
using ::testing::MatchResultListener;
Packit bd1cd8
using ::testing::NotNull;
Packit bd1cd8
using ::testing::PolymorphicMatcher;
Packit bd1cd8
Packit bd1cd8
class NotNullMatcher {
Packit bd1cd8
 public:
Packit bd1cd8
  // To implement a polymorphic matcher, first define a COPYABLE class
Packit bd1cd8
  // that has three members MatchAndExplain(), DescribeTo(), and
Packit bd1cd8
  // DescribeNegationTo(), like the following.
Packit bd1cd8
Packit bd1cd8
  // In this example, we want to use NotNull() with any pointer, so
Packit bd1cd8
  // MatchAndExplain() accepts a pointer of any type as its first argument.
Packit bd1cd8
  // In general, you can define MatchAndExplain() as an ordinary method or
Packit bd1cd8
  // a method template, or even overload it.
Packit bd1cd8
  template <typename T>
Packit bd1cd8
  bool MatchAndExplain(T* p,
Packit bd1cd8
                       MatchResultListener* /* listener */) const {
Packit bd1cd8
    return p != NULL;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  // Describes the property of a value matching this matcher.
Packit bd1cd8
  void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
Packit bd1cd8
Packit bd1cd8
  // Describes the property of a value NOT matching this matcher.
Packit bd1cd8
  void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
// To construct a polymorphic matcher, pass an instance of the class
Packit bd1cd8
// to MakePolymorphicMatcher().  Note the return type.
Packit bd1cd8
inline PolymorphicMatcher<NotNullMatcher> NotNull() {
Packit bd1cd8
  return MakePolymorphicMatcher(NotNullMatcher());
Packit bd1cd8
}
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
**Note:** Your polymorphic matcher class does **not** need to inherit from
Packit bd1cd8
`MatcherInterface` or any other class, and its methods do **not** need
Packit bd1cd8
to be virtual.
Packit bd1cd8
Packit bd1cd8
Like in a monomorphic matcher, you may explain the match result by
Packit bd1cd8
streaming additional information to the `listener` argument in
Packit bd1cd8
`MatchAndExplain()`.
Packit bd1cd8
Packit bd1cd8
## Writing New Cardinalities ##
Packit bd1cd8
Packit bd1cd8
A cardinality is used in `Times()` to tell Google Mock how many times
Packit bd1cd8
you expect a call to occur. It doesn't have to be exact. For example,
Packit bd1cd8
you can say `AtLeast(5)` or `Between(2, 4)`.
Packit bd1cd8
Packit bd1cd8
If the built-in set of cardinalities doesn't suit you, you are free to
Packit bd1cd8
define your own by implementing the following interface (in namespace
Packit bd1cd8
`testing`):
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class CardinalityInterface {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual ~CardinalityInterface();
Packit bd1cd8
Packit bd1cd8
  // Returns true iff call_count calls will satisfy this cardinality.
Packit bd1cd8
  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
Packit bd1cd8
Packit bd1cd8
  // Returns true iff call_count calls will saturate this cardinality.
Packit bd1cd8
  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
Packit bd1cd8
Packit bd1cd8
  // Describes self to an ostream.
Packit bd1cd8
  virtual void DescribeTo(::std::ostream* os) const = 0;
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
For example, to specify that a call must occur even number of times,
Packit bd1cd8
you can write
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::Cardinality;
Packit bd1cd8
using ::testing::CardinalityInterface;
Packit bd1cd8
using ::testing::MakeCardinality;
Packit bd1cd8
Packit bd1cd8
class EvenNumberCardinality : public CardinalityInterface {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual bool IsSatisfiedByCallCount(int call_count) const {
Packit bd1cd8
    return (call_count % 2) == 0;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual bool IsSaturatedByCallCount(int call_count) const {
Packit bd1cd8
    return false;
Packit bd1cd8
  }
Packit bd1cd8
Packit bd1cd8
  virtual void DescribeTo(::std::ostream* os) const {
Packit bd1cd8
    *os << "called even number of times";
Packit bd1cd8
  }
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
Cardinality EvenNumber() {
Packit bd1cd8
  return MakeCardinality(new EvenNumberCardinality);
Packit bd1cd8
}
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, Bar(3))
Packit bd1cd8
      .Times(EvenNumber());
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Writing New Actions Quickly ##
Packit bd1cd8
Packit bd1cd8
If the built-in actions don't work for you, and you find it
Packit bd1cd8
inconvenient to use `Invoke()`, you can use a macro from the `ACTION*`
Packit bd1cd8
family to quickly define a new action that can be used in your code as
Packit bd1cd8
if it's a built-in action.
Packit bd1cd8
Packit bd1cd8
By writing
Packit bd1cd8
```
Packit bd1cd8
ACTION(name) { statements; }
Packit bd1cd8
```
Packit bd1cd8
in a namespace scope (i.e. not inside a class or function), you will
Packit bd1cd8
define an action with the given name that executes the statements.
Packit bd1cd8
The value returned by `statements` will be used as the return value of
Packit bd1cd8
the action.  Inside the statements, you can refer to the K-th
Packit bd1cd8
(0-based) argument of the mock function as `argK`.  For example:
Packit bd1cd8
```
Packit bd1cd8
ACTION(IncrementArg1) { return ++(*arg1); }
Packit bd1cd8
```
Packit bd1cd8
allows you to write
Packit bd1cd8
```
Packit bd1cd8
... WillOnce(IncrementArg1());
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Note that you don't need to specify the types of the mock function
Packit bd1cd8
arguments.  Rest assured that your code is type-safe though:
Packit bd1cd8
you'll get a compiler error if `*arg1` doesn't support the `++`
Packit bd1cd8
operator, or if the type of `++(*arg1)` isn't compatible with the mock
Packit bd1cd8
function's return type.
Packit bd1cd8
Packit bd1cd8
Another example:
Packit bd1cd8
```
Packit bd1cd8
ACTION(Foo) {
Packit bd1cd8
  (*arg2)(5);
Packit bd1cd8
  Blah();
Packit bd1cd8
  *arg1 = 0;
Packit bd1cd8
  return arg0;
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
defines an action `Foo()` that invokes argument #2 (a function pointer)
Packit bd1cd8
with 5, calls function `Blah()`, sets the value pointed to by argument
Packit bd1cd8
#1 to 0, and returns argument #0.
Packit bd1cd8
Packit bd1cd8
For more convenience and flexibility, you can also use the following
Packit bd1cd8
pre-defined symbols in the body of `ACTION`:
Packit bd1cd8
Packit bd1cd8
| `argK_type` | The type of the K-th (0-based) argument of the mock function |
Packit bd1cd8
|:------------|:-------------------------------------------------------------|
Packit bd1cd8
| `args`      | All arguments of the mock function as a tuple                |
Packit bd1cd8
| `args_type` | The type of all arguments of the mock function as a tuple    |
Packit bd1cd8
| `return_type` | The return type of the mock function                         |
Packit bd1cd8
| `function_type` | The type of the mock function                                |
Packit bd1cd8
Packit bd1cd8
For example, when using an `ACTION` as a stub action for mock function:
Packit bd1cd8
```
Packit bd1cd8
int DoSomething(bool flag, int* ptr);
Packit bd1cd8
```
Packit bd1cd8
we have:
Packit bd1cd8
| **Pre-defined Symbol** | **Is Bound To** |
Packit bd1cd8
|:-----------------------|:----------------|
Packit bd1cd8
| `arg0`                 | the value of `flag` |
Packit bd1cd8
| `arg0_type`            | the type `bool` |
Packit bd1cd8
| `arg1`                 | the value of `ptr` |
Packit bd1cd8
| `arg1_type`            | the type `int*` |
Packit bd1cd8
| `args`                 | the tuple `(flag, ptr)` |
Packit bd1cd8
| `args_type`            | the type `std::tr1::tuple<bool, int*>` |
Packit bd1cd8
| `return_type`          | the type `int`  |
Packit bd1cd8
| `function_type`        | the type `int(bool, int*)` |
Packit bd1cd8
Packit bd1cd8
## Writing New Parameterized Actions Quickly ##
Packit bd1cd8
Packit bd1cd8
Sometimes you'll want to parameterize an action you define.  For that
Packit bd1cd8
we have another macro
Packit bd1cd8
```
Packit bd1cd8
ACTION_P(name, param) { statements; }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
For example,
Packit bd1cd8
```
Packit bd1cd8
ACTION_P(Add, n) { return arg0 + n; }
Packit bd1cd8
```
Packit bd1cd8
will allow you to write
Packit bd1cd8
```
Packit bd1cd8
// Returns argument #0 + 5.
Packit bd1cd8
... WillOnce(Add(5));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
For convenience, we use the term _arguments_ for the values used to
Packit bd1cd8
invoke the mock function, and the term _parameters_ for the values
Packit bd1cd8
used to instantiate an action.
Packit bd1cd8
Packit bd1cd8
Note that you don't need to provide the type of the parameter either.
Packit bd1cd8
Suppose the parameter is named `param`, you can also use the
Packit bd1cd8
Google-Mock-defined symbol `param_type` to refer to the type of the
Packit bd1cd8
parameter as inferred by the compiler.  For example, in the body of
Packit bd1cd8
`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`.
Packit bd1cd8
Packit bd1cd8
Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support
Packit bd1cd8
multi-parameter actions.  For example,
Packit bd1cd8
```
Packit bd1cd8
ACTION_P2(ReturnDistanceTo, x, y) {
Packit bd1cd8
  double dx = arg0 - x;
Packit bd1cd8
  double dy = arg1 - y;
Packit bd1cd8
  return sqrt(dx*dx + dy*dy);
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
lets you write
Packit bd1cd8
```
Packit bd1cd8
... WillOnce(ReturnDistanceTo(5.0, 26.5));
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
You can view `ACTION` as a degenerated parameterized action where the
Packit bd1cd8
number of parameters is 0.
Packit bd1cd8
Packit bd1cd8
You can also easily define actions overloaded on the number of parameters:
Packit bd1cd8
```
Packit bd1cd8
ACTION_P(Plus, a) { ... }
Packit bd1cd8
ACTION_P2(Plus, a, b) { ... }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Restricting the Type of an Argument or Parameter in an ACTION ##
Packit bd1cd8
Packit bd1cd8
For maximum brevity and reusability, the `ACTION*` macros don't ask
Packit bd1cd8
you to provide the types of the mock function arguments and the action
Packit bd1cd8
parameters.  Instead, we let the compiler infer the types for us.
Packit bd1cd8
Packit bd1cd8
Sometimes, however, we may want to be more explicit about the types.
Packit bd1cd8
There are several tricks to do that.  For example:
Packit bd1cd8
```
Packit bd1cd8
ACTION(Foo) {
Packit bd1cd8
  // Makes sure arg0 can be converted to int.
Packit bd1cd8
  int n = arg0;
Packit bd1cd8
  ... use n instead of arg0 here ...
Packit bd1cd8
}
Packit bd1cd8
Packit bd1cd8
ACTION_P(Bar, param) {
Packit bd1cd8
  // Makes sure the type of arg1 is const char*.
Packit bd1cd8
  ::testing::StaticAssertTypeEq<const char*, arg1_type>();
Packit bd1cd8
Packit bd1cd8
  // Makes sure param can be converted to bool.
Packit bd1cd8
  bool flag = param;
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
where `StaticAssertTypeEq` is a compile-time assertion in Google Test
Packit bd1cd8
that verifies two types are the same.
Packit bd1cd8
Packit bd1cd8
## Writing New Action Templates Quickly ##
Packit bd1cd8
Packit bd1cd8
Sometimes you want to give an action explicit template parameters that
Packit bd1cd8
cannot be inferred from its value parameters.  `ACTION_TEMPLATE()`
Packit bd1cd8
supports that and can be viewed as an extension to `ACTION()` and
Packit bd1cd8
`ACTION_P*()`.
Packit bd1cd8
Packit bd1cd8
The syntax:
Packit bd1cd8
```
Packit bd1cd8
ACTION_TEMPLATE(ActionName,
Packit bd1cd8
                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
Packit bd1cd8
                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
defines an action template that takes _m_ explicit template parameters
Packit bd1cd8
and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is
Packit bd1cd8
between 0 and 10.  `name_i` is the name of the i-th template
Packit bd1cd8
parameter, and `kind_i` specifies whether it's a `typename`, an
Packit bd1cd8
integral constant, or a template.  `p_i` is the name of the i-th value
Packit bd1cd8
parameter.
Packit bd1cd8
Packit bd1cd8
Example:
Packit bd1cd8
```
Packit bd1cd8
// DuplicateArg<k, T>(output) converts the k-th argument of the mock
Packit bd1cd8
// function to type T and copies it to *output.
Packit bd1cd8
ACTION_TEMPLATE(DuplicateArg,
Packit bd1cd8
                // Note the comma between int and k:
Packit bd1cd8
                HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
Packit bd1cd8
                AND_1_VALUE_PARAMS(output)) {
Packit bd1cd8
  *output = T(std::tr1::get<k>(args));
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
To create an instance of an action template, write:
Packit bd1cd8
```
Packit bd1cd8
  ActionName<t1, ..., t_m>(v1, ..., v_n)
Packit bd1cd8
```
Packit bd1cd8
where the `t`s are the template arguments and the
Packit bd1cd8
`v`s are the value arguments.  The value argument
Packit bd1cd8
types are inferred by the compiler.  For example:
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
...
Packit bd1cd8
  int n;
Packit bd1cd8
  EXPECT_CALL(mock, Foo(_, _))
Packit bd1cd8
      .WillOnce(DuplicateArg<1, unsigned char>(&n);;
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
If you want to explicitly specify the value argument types, you can
Packit bd1cd8
provide additional template arguments:
Packit bd1cd8
```
Packit bd1cd8
  ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
Packit bd1cd8
```
Packit bd1cd8
where `u_i` is the desired type of `v_i`.
Packit bd1cd8
Packit bd1cd8
`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the
Packit bd1cd8
number of value parameters, but not on the number of template
Packit bd1cd8
parameters.  Without the restriction, the meaning of the following is
Packit bd1cd8
unclear:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
  OverloadedAction<int, bool>(x);
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Are we using a single-template-parameter action where `bool` refers to
Packit bd1cd8
the type of `x`, or a two-template-parameter action where the compiler
Packit bd1cd8
is asked to infer the type of `x`?
Packit bd1cd8
Packit bd1cd8
## Using the ACTION Object's Type ##
Packit bd1cd8
Packit bd1cd8
If you are writing a function that returns an `ACTION` object, you'll
Packit bd1cd8
need to know its type.  The type depends on the macro used to define
Packit bd1cd8
the action and the parameter types.  The rule is relatively simple:
Packit bd1cd8
| **Given Definition** | **Expression** | **Has Type** |
Packit bd1cd8
|:---------------------|:---------------|:-------------|
Packit bd1cd8
| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
Packit bd1cd8
| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` |	`Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
Packit bd1cd8
| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
Packit bd1cd8
| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` |
Packit bd1cd8
| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
Packit bd1cd8
| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `FooActionP2<t1, ..., t_m, bool, int>` |
Packit bd1cd8
| ...                  | ...            | ...          |
Packit bd1cd8
Packit bd1cd8
Note that we have to pick different suffixes (`Action`, `ActionP`,
Packit bd1cd8
`ActionP2`, and etc) for actions with different numbers of value
Packit bd1cd8
parameters, or the action definitions cannot be overloaded on the
Packit bd1cd8
number of them.
Packit bd1cd8
Packit bd1cd8
## Writing New Monomorphic Actions ##
Packit bd1cd8
Packit bd1cd8
While the `ACTION*` macros are very convenient, sometimes they are
Packit bd1cd8
inappropriate.  For example, despite the tricks shown in the previous
Packit bd1cd8
recipes, they don't let you directly specify the types of the mock
Packit bd1cd8
function arguments and the action parameters, which in general leads
Packit bd1cd8
to unoptimized compiler error messages that can baffle unfamiliar
Packit bd1cd8
users.  They also don't allow overloading actions based on parameter
Packit bd1cd8
types without jumping through some hoops.
Packit bd1cd8
Packit bd1cd8
An alternative to the `ACTION*` macros is to implement
Packit bd1cd8
`::testing::ActionInterface<F>`, where `F` is the type of the mock
Packit bd1cd8
function in which the action will be used. For example:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
template <typename F>class ActionInterface {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual ~ActionInterface();
Packit bd1cd8
Packit bd1cd8
  // Performs the action.  Result is the return type of function type
Packit bd1cd8
  // F, and ArgumentTuple is the tuple of arguments of F.
Packit bd1cd8
  //
Packit bd1cd8
  // For example, if F is int(bool, const string&), then Result would
Packit bd1cd8
  // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>.
Packit bd1cd8
  virtual Result Perform(const ArgumentTuple& args) = 0;
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
using ::testing::Action;
Packit bd1cd8
using ::testing::ActionInterface;
Packit bd1cd8
using ::testing::MakeAction;
Packit bd1cd8
Packit bd1cd8
typedef int IncrementMethod(int*);
Packit bd1cd8
Packit bd1cd8
class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
Packit bd1cd8
 public:
Packit bd1cd8
  virtual int Perform(const tr1::tuple<int*>& args) {
Packit bd1cd8
    int* p = tr1::get<0>(args);  // Grabs the first argument.
Packit bd1cd8
    return *p++;
Packit bd1cd8
  }
Packit bd1cd8
};
Packit bd1cd8
Packit bd1cd8
Action<IncrementMethod> IncrementArgument() {
Packit bd1cd8
  return MakeAction(new IncrementArgumentAction);
Packit bd1cd8
}
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  EXPECT_CALL(foo, Baz(_))
Packit bd1cd8
      .WillOnce(IncrementArgument());
Packit bd1cd8
Packit bd1cd8
  int n = 5;
Packit bd1cd8
  foo.Baz(&n);  // Should return 5 and change n to 6.
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Writing New Polymorphic Actions ##
Packit bd1cd8
Packit bd1cd8
The previous recipe showed you how to define your own action. This is
Packit bd1cd8
all good, except that you need to know the type of the function in
Packit bd1cd8
which the action will be used. Sometimes that can be a problem. For
Packit bd1cd8
example, if you want to use the action in functions with _different_
Packit bd1cd8
types (e.g. like `Return()` and `SetArgPointee()`).
Packit bd1cd8
Packit bd1cd8
If an action can be used in several types of mock functions, we say
Packit bd1cd8
it's _polymorphic_. The `MakePolymorphicAction()` function template
Packit bd1cd8
makes it easy to define such an action:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
namespace testing {
Packit bd1cd8
Packit bd1cd8
template <typename Impl>
Packit bd1cd8
PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);
Packit bd1cd8
Packit bd1cd8
}  // namespace testing
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
As an example, let's define an action that returns the second argument
Packit bd1cd8
in the mock function's argument list. The first step is to define an
Packit bd1cd8
implementation class:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
class ReturnSecondArgumentAction {
Packit bd1cd8
 public:
Packit bd1cd8
  template <typename Result, typename ArgumentTuple>
Packit bd1cd8
  Result Perform(const ArgumentTuple& args) const {
Packit bd1cd8
    // To get the i-th (0-based) argument, use tr1::get(args).
Packit bd1cd8
    return tr1::get<1>(args);
Packit bd1cd8
  }
Packit bd1cd8
};
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
This implementation class does _not_ need to inherit from any
Packit bd1cd8
particular class. What matters is that it must have a `Perform()`
Packit bd1cd8
method template. This method template takes the mock function's
Packit bd1cd8
arguments as a tuple in a **single** argument, and returns the result of
Packit bd1cd8
the action. It can be either `const` or not, but must be invokable
Packit bd1cd8
with exactly one template argument, which is the result type. In other
Packit bd1cd8
words, you must be able to call `Perform<R>(args)` where `R` is the
Packit bd1cd8
mock function's return type and `args` is its arguments in a tuple.
Packit bd1cd8
Packit bd1cd8
Next, we use `MakePolymorphicAction()` to turn an instance of the
Packit bd1cd8
implementation class into the polymorphic action we need. It will be
Packit bd1cd8
convenient to have a wrapper for this:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::MakePolymorphicAction;
Packit bd1cd8
using ::testing::PolymorphicAction;
Packit bd1cd8
Packit bd1cd8
PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
Packit bd1cd8
  return MakePolymorphicAction(ReturnSecondArgumentAction());
Packit bd1cd8
}
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
Now, you can use this polymorphic action the same way you use the
Packit bd1cd8
built-in ones:
Packit bd1cd8
Packit bd1cd8
```
Packit bd1cd8
using ::testing::_;
Packit bd1cd8
Packit bd1cd8
class MockFoo : public Foo {
Packit bd1cd8
 public:
Packit bd1cd8
  MOCK_METHOD2(DoThis, int(bool flag, int n));
Packit bd1cd8
  MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2));
Packit bd1cd8
};
Packit bd1cd8
...
Packit bd1cd8
Packit bd1cd8
  MockFoo foo;
Packit bd1cd8
  EXPECT_CALL(foo, DoThis(_, _))
Packit bd1cd8
      .WillOnce(ReturnSecondArgument());
Packit bd1cd8
  EXPECT_CALL(foo, DoThat(_, _, _))
Packit bd1cd8
      .WillOnce(ReturnSecondArgument());
Packit bd1cd8
  ...
Packit bd1cd8
  foo.DoThis(true, 5);         // Will return 5.
Packit bd1cd8
  foo.DoThat(1, "Hi", "Bye");  // Will return "Hi".
Packit bd1cd8
```
Packit bd1cd8
Packit bd1cd8
## Teaching Google Mock How to Print Your Values ##
Packit bd1cd8
Packit bd1cd8
When an uninteresting or unexpected call occurs, Google Mock prints the
Packit bd1cd8
argument values and the stack trace to help you debug.  Assertion
Packit bd1cd8
macros like `EXPECT_THAT` and `EXPECT_EQ` also print the values in
Packit bd1cd8
question when the assertion fails.  Google Mock and Google Test do this using
Packit bd1cd8
Google Test's user-extensible value printer.
Packit bd1cd8
Packit bd1cd8
This printer knows how to print built-in C++ types, native arrays, STL
Packit bd1cd8
containers, and any type that supports the `<<` operator.  For other
Packit bd1cd8
types, it prints the raw bytes in the value and hopes that you the
Packit bd1cd8
user can figure it out.
Packit bd1cd8
[Google Test's advanced guide](http://code.google.com/p/googletest/wiki/AdvancedGuide#Teaching_Google_Test_How_to_Print_Your_Values)
Packit bd1cd8
explains how to extend the printer to do a better job at
Packit bd1cd8
printing your particular type than to dump the bytes.