1
2
3You can find recipes for using Google Mock here. If you haven't yet,
4please read the [ForDummies](V1_5_ForDummies.md) document first to make sure you understand
5the basics.
6
7**Note:** Google Mock lives in the `testing` name space. For
8readability, it is recommended to write `using ::testing::Foo;` once in
9your file before using the name `Foo` defined by Google Mock. We omit
10such `using` statements in this page for brevity, but you should do it
11in your own code.
12
13# Creating Mock Classes #
14
15## Mocking Private or Protected Methods ##
16
17You must always put a mock method definition (`MOCK_METHOD*`) in a
18`public:` section of the mock class, regardless of the method being
19mocked being `public`, `protected`, or `private` in the base class.
20This allows `ON_CALL` and `EXPECT_CALL` to reference the mock function
21from outside of the mock class.  (Yes, C++ allows a subclass to change
22the access level of a virtual function in the base class.)  Example:
23
24```
25class Foo {
26 public:
27  ...
28  virtual bool Transform(Gadget* g) = 0;
29
30 protected:
31  virtual void Resume();
32
33 private:
34  virtual int GetTimeOut();
35};
36
37class MockFoo : public Foo {
38 public:
39  ...
40  MOCK_METHOD1(Transform, bool(Gadget* g));
41
42  // The following must be in the public section, even though the
43  // methods are protected or private in the base class.
44  MOCK_METHOD0(Resume, void());
45  MOCK_METHOD0(GetTimeOut, int());
46};
47```
48
49## Mocking Overloaded Methods ##
50
51You can mock overloaded functions as usual. No special attention is required:
52
53```
54class Foo {
55  ...
56
57  // Must be virtual as we'll inherit from Foo.
58  virtual ~Foo();
59
60  // Overloaded on the types and/or numbers of arguments.
61  virtual int Add(Element x);
62  virtual int Add(int times, Element x);
63
64  // Overloaded on the const-ness of this object.
65  virtual Bar& GetBar();
66  virtual const Bar& GetBar() const;
67};
68
69class MockFoo : public Foo {
70  ...
71  MOCK_METHOD1(Add, int(Element x));
72  MOCK_METHOD2(Add, int(int times, Element x);
73
74  MOCK_METHOD0(GetBar, Bar&());
75  MOCK_CONST_METHOD0(GetBar, const Bar&());
76};
77```
78
79**Note:** if you don't mock all versions of the overloaded method, the
80compiler will give you a warning about some methods in the base class
81being hidden. To fix that, use `using` to bring them in scope:
82
83```
84class MockFoo : public Foo {
85  ...
86  using Foo::Add;
87  MOCK_METHOD1(Add, int(Element x));
88  // We don't want to mock int Add(int times, Element x);
89  ...
90};
91```
92
93## Mocking Class Templates ##
94
95To mock a class template, append `_T` to the `MOCK_*` macros:
96
97```
98template <typename Elem>
99class StackInterface {
100  ...
101  // Must be virtual as we'll inherit from StackInterface.
102  virtual ~StackInterface();
103
104  virtual int GetSize() const = 0;
105  virtual void Push(const Elem& x) = 0;
106};
107
108template <typename Elem>
109class MockStack : public StackInterface<Elem> {
110  ...
111  MOCK_CONST_METHOD0_T(GetSize, int());
112  MOCK_METHOD1_T(Push, void(const Elem& x));
113};
114```
115
116## Mocking Nonvirtual Methods ##
117
118Google Mock can mock non-virtual functions to be used in what we call _hi-perf
119dependency injection_.
120
121In this case, instead of sharing a common base class with the real
122class, your mock class will be _unrelated_ to the real class, but
123contain methods with the same signatures.  The syntax for mocking
124non-virtual methods is the _same_ as mocking virtual methods:
125
126```
127// A simple packet stream class.  None of its members is virtual.
128class ConcretePacketStream {
129 public:
130  void AppendPacket(Packet* new_packet);
131  const Packet* GetPacket(size_t packet_number) const;
132  size_t NumberOfPackets() const;
133  ...
134};
135
136// A mock packet stream class.  It inherits from no other, but defines
137// GetPacket() and NumberOfPackets().
138class MockPacketStream {
139 public:
140  MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
141  MOCK_CONST_METHOD0(NumberOfPackets, size_t());
142  ...
143};
144```
145
146Note that the mock class doesn't define `AppendPacket()`, unlike the
147real class. That's fine as long as the test doesn't need to call it.
148
149Next, you need a way to say that you want to use
150`ConcretePacketStream` in production code, and use `MockPacketStream`
151in tests.  Since the functions are not virtual and the two classes are
152unrelated, you must specify your choice at _compile time_ (as opposed
153to run time).
154
155One way to do it is to templatize your code that needs to use a packet
156stream.  More specifically, you will give your code a template type
157argument for the type of the packet stream.  In production, you will
158instantiate your template with `ConcretePacketStream` as the type
159argument.  In tests, you will instantiate the same template with
160`MockPacketStream`.  For example, you may write:
161
162```
163template <class PacketStream>
164void CreateConnection(PacketStream* stream) { ... }
165
166template <class PacketStream>
167class PacketReader {
168 public:
169  void ReadPackets(PacketStream* stream, size_t packet_num);
170};
171```
172
173Then you can use `CreateConnection<ConcretePacketStream>()` and
174`PacketReader<ConcretePacketStream>` in production code, and use
175`CreateConnection<MockPacketStream>()` and
176`PacketReader<MockPacketStream>` in tests.
177
178```
179  MockPacketStream mock_stream;
180  EXPECT_CALL(mock_stream, ...)...;
181  .. set more expectations on mock_stream ...
182  PacketReader<MockPacketStream> reader(&mock_stream);
183  ... exercise reader ...
184```
185
186## Mocking Free Functions ##
187
188It's possible to use Google Mock to mock a free function (i.e. a
189C-style function or a static method).  You just need to rewrite your
190code to use an interface (abstract class).
191
192Instead of calling a free function (say, `OpenFile`) directly,
193introduce an interface for it and have a concrete subclass that calls
194the free function:
195
196```
197class FileInterface {
198 public:
199  ...
200  virtual bool Open(const char* path, const char* mode) = 0;
201};
202
203class File : public FileInterface {
204 public:
205  ...
206  virtual bool Open(const char* path, const char* mode) {
207    return OpenFile(path, mode);
208  }
209};
210```
211
212Your code should talk to `FileInterface` to open a file.  Now it's
213easy to mock out the function.
214
215This may seem much hassle, but in practice you often have multiple
216related functions that you can put in the same interface, so the
217per-function syntactic overhead will be much lower.
218
219If you are concerned about the performance overhead incurred by
220virtual functions, and profiling confirms your concern, you can
221combine this with the recipe for [mocking non-virtual methods](#Mocking_Nonvirtual_Methods.md).
222
223## Nice Mocks and Strict Mocks ##
224
225If a mock method has no `EXPECT_CALL` spec but is called, Google Mock
226will print a warning about the "uninteresting call". The rationale is:
227
228  * 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.
229  * 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.
230
231However, sometimes you may want to suppress all "uninteresting call"
232warnings, while sometimes you may want the opposite, i.e. to treat all
233of them as errors. Google Mock lets you make the decision on a
234per-mock-object basis.
235
236Suppose your test uses a mock class `MockFoo`:
237
238```
239TEST(...) {
240  MockFoo mock_foo;
241  EXPECT_CALL(mock_foo, DoThis());
242  ... code that uses mock_foo ...
243}
244```
245
246If a method of `mock_foo` other than `DoThis()` is called, it will be
247reported by Google Mock as a warning. However, if you rewrite your
248test to use `NiceMock<MockFoo>` instead, the warning will be gone,
249resulting in a cleaner test output:
250
251```
252using ::testing::NiceMock;
253
254TEST(...) {
255  NiceMock<MockFoo> mock_foo;
256  EXPECT_CALL(mock_foo, DoThis());
257  ... code that uses mock_foo ...
258}
259```
260
261`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used
262wherever `MockFoo` is accepted.
263
264It also works if `MockFoo`'s constructor takes some arguments, as
265`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:
266
267```
268using ::testing::NiceMock;
269
270TEST(...) {
271  NiceMock<MockFoo> mock_foo(5, "hi");  // Calls MockFoo(5, "hi").
272  EXPECT_CALL(mock_foo, DoThis());
273  ... code that uses mock_foo ...
274}
275```
276
277The usage of `StrictMock` is similar, except that it makes all
278uninteresting calls failures:
279
280```
281using ::testing::StrictMock;
282
283TEST(...) {
284  StrictMock<MockFoo> mock_foo;
285  EXPECT_CALL(mock_foo, DoThis());
286  ... code that uses mock_foo ...
287
288  // The test will fail if a method of mock_foo other than DoThis()
289  // is called.
290}
291```
292
293There are some caveats though (I don't like them just as much as the
294next guy, but sadly they are side effects of C++'s limitations):
295
296  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.
297  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).
298  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.)
299
300Finally, you should be **very cautious** when using this feature, as the
301decision you make applies to **all** future changes to the mock
302class. If an important change is made in the interface you are mocking
303(and thus in the mock class), it could break your tests (if you use
304`StrictMock`) or let bugs pass through without a warning (if you use
305`NiceMock`). Therefore, try to specify the mock's behavior using
306explicit `EXPECT_CALL` first, and only turn to `NiceMock` or
307`StrictMock` as the last resort.
308
309## Simplifying the Interface without Breaking Existing Code ##
310
311Sometimes a method has a long list of arguments that is mostly
312uninteresting. For example,
313
314```
315class LogSink {
316 public:
317  ...
318  virtual void send(LogSeverity severity, const char* full_filename,
319                    const char* base_filename, int line,
320                    const struct tm* tm_time,
321                    const char* message, size_t message_len) = 0;
322};
323```
324
325This method's argument list is lengthy and hard to work with (let's
326say that the `message` argument is not even 0-terminated). If we mock
327it as is, using the mock will be awkward. If, however, we try to
328simplify this interface, we'll need to fix all clients depending on
329it, which is often infeasible.
330
331The trick is to re-dispatch the method in the mock class:
332
333```
334class ScopedMockLog : public LogSink {
335 public:
336  ...
337  virtual void send(LogSeverity severity, const char* full_filename,
338                    const char* base_filename, int line, const tm* tm_time,
339                    const char* message, size_t message_len) {
340    // We are only interested in the log severity, full file name, and
341    // log message.
342    Log(severity, full_filename, std::string(message, message_len));
343  }
344
345  // Implements the mock method:
346  //
347  //   void Log(LogSeverity severity,
348  //            const string& file_path,
349  //            const string& message);
350  MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path,
351                         const string& message));
352};
353```
354
355By defining a new mock method with a trimmed argument list, we make
356the mock class much more user-friendly.
357
358## Alternative to Mocking Concrete Classes ##
359
360Often you may find yourself using classes that don't implement
361interfaces. In order to test your code that uses such a class (let's
362call it `Concrete`), you may be tempted to make the methods of
363`Concrete` virtual and then mock it.
364
365Try not to do that.
366
367Making a non-virtual function virtual is a big decision. It creates an
368extension point where subclasses can tweak your class' behavior. This
369weakens your control on the class because now it's harder to maintain
370the class' invariants. You should make a function virtual only when
371there is a valid reason for a subclass to override it.
372
373Mocking concrete classes directly is problematic as it creates a tight
374coupling between the class and the tests - any small change in the
375class may invalidate your tests and make test maintenance a pain.
376
377To avoid such problems, many programmers have been practicing "coding
378to interfaces": instead of talking to the `Concrete` class, your code
379would define an interface and talk to it. Then you implement that
380interface as an adaptor on top of `Concrete`. In tests, you can easily
381mock that interface to observe how your code is doing.
382
383This technique incurs some overhead:
384
385  * You pay the cost of virtual function calls (usually not a problem).
386  * There is more abstraction for the programmers to learn.
387
388However, it can also bring significant benefits in addition to better
389testability:
390
391  * `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.
392  * 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.
393
394Some people worry that if everyone is practicing this technique, they
395will end up writing lots of redundant code. This concern is totally
396understandable. However, there are two reasons why it may not be the
397case:
398
399  * 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.
400  * 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.
401
402You need to weigh the pros and cons carefully for your particular
403problem, but I'd like to assure you that the Java community has been
404practicing this for a long time and it's a proven effective technique
405applicable in a wide variety of situations. :-)
406
407## Delegating Calls to a Fake ##
408
409Some times you have a non-trivial fake implementation of an
410interface. For example:
411
412```
413class Foo {
414 public:
415  virtual ~Foo() {}
416  virtual char DoThis(int n) = 0;
417  virtual void DoThat(const char* s, int* p) = 0;
418};
419
420class FakeFoo : public Foo {
421 public:
422  virtual char DoThis(int n) {
423    return (n > 0) ? '+' :
424        (n < 0) ? '-' : '0';
425  }
426
427  virtual void DoThat(const char* s, int* p) {
428    *p = strlen(s);
429  }
430};
431```
432
433Now you want to mock this interface such that you can set expectations
434on it. However, you also want to use `FakeFoo` for the default
435behavior, as duplicating it in the mock object is, well, a lot of
436work.
437
438When you define the mock class using Google Mock, you can have it
439delegate its default action to a fake class you already have, using
440this pattern:
441
442```
443using ::testing::_;
444using ::testing::Invoke;
445
446class MockFoo : public Foo {
447 public:
448  // Normal mock method definitions using Google Mock.
449  MOCK_METHOD1(DoThis, char(int n));
450  MOCK_METHOD2(DoThat, void(const char* s, int* p));
451
452  // Delegates the default actions of the methods to a FakeFoo object.
453  // This must be called *before* the custom ON_CALL() statements.
454  void DelegateToFake() {
455    ON_CALL(*this, DoThis(_))
456        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThis));
457    ON_CALL(*this, DoThat(_, _))
458        .WillByDefault(Invoke(&fake_, &FakeFoo::DoThat));
459  }
460 private:
461  FakeFoo fake_;  // Keeps an instance of the fake in the mock.
462};
463```
464
465With that, you can use `MockFoo` in your tests as usual. Just remember
466that if you don't explicitly set an action in an `ON_CALL()` or
467`EXPECT_CALL()`, the fake will be called upon to do it:
468
469```
470using ::testing::_;
471
472TEST(AbcTest, Xyz) {
473  MockFoo foo;
474  foo.DelegateToFake(); // Enables the fake for delegation.
475
476  // Put your ON_CALL(foo, ...)s here, if any.
477
478  // No action specified, meaning to use the default action.
479  EXPECT_CALL(foo, DoThis(5));
480  EXPECT_CALL(foo, DoThat(_, _));
481
482  int n = 0;
483  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.
484  foo.DoThat("Hi", &n);           // FakeFoo::DoThat() is invoked.
485  EXPECT_EQ(2, n);
486}
487```
488
489**Some tips:**
490
491  * If you want, you can still override the default action by providing your own `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
492  * In `DelegateToFake()`, you only need to delegate the methods whose fake implementation you intend to use.
493  * 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.
494  * 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.
495
496Regarding the tip on mixing a mock and a fake, here's an example on
497why it may be a bad sign: Suppose you have a class `System` for
498low-level system operations. In particular, it does file and I/O
499operations. And suppose you want to test how your code uses `System`
500to do I/O, and you just want the file operations to work normally. If
501you mock out the entire `System` class, you'll have to provide a fake
502implementation for the file operation part, which suggests that
503`System` is taking on too many roles.
504
505Instead, you can define a `FileOps` interface and an `IOOps` interface
506and split `System`'s functionalities into the two. Then you can mock
507`IOOps` without mocking `FileOps`.
508
509## Delegating Calls to a Real Object ##
510
511When using testing doubles (mocks, fakes, stubs, and etc), sometimes
512their behaviors will differ from those of the real objects. This
513difference could be either intentional (as in simulating an error such
514that you can test the error handling code) or unintentional. If your
515mocks have different behaviors than the real objects by mistake, you
516could end up with code that passes the tests but fails in production.
517
518You can use the _delegating-to-real_ technique to ensure that your
519mock has the same behavior as the real object while retaining the
520ability to validate calls. This technique is very similar to the
521delegating-to-fake technique, the difference being that we use a real
522object instead of a fake. Here's an example:
523
524```
525using ::testing::_;
526using ::testing::AtLeast;
527using ::testing::Invoke;
528
529class MockFoo : public Foo {
530 public:
531  MockFoo() {
532    // By default, all calls are delegated to the real object.
533    ON_CALL(*this, DoThis())
534        .WillByDefault(Invoke(&real_, &Foo::DoThis));
535    ON_CALL(*this, DoThat(_))
536        .WillByDefault(Invoke(&real_, &Foo::DoThat));
537    ...
538  }
539  MOCK_METHOD0(DoThis, ...);
540  MOCK_METHOD1(DoThat, ...);
541  ...
542 private:
543  Foo real_;
544};
545...
546
547  MockFoo mock;
548
549  EXPECT_CALL(mock, DoThis())
550      .Times(3);
551  EXPECT_CALL(mock, DoThat("Hi"))
552      .Times(AtLeast(1));
553  ... use mock in test ...
554```
555
556With this, Google Mock will verify that your code made the right calls
557(with the right arguments, in the right order, called the right number
558of times, etc), and a real object will answer the calls (so the
559behavior will be the same as in production). This gives you the best
560of both worlds.
561
562## Delegating Calls to a Parent Class ##
563
564Ideally, you should code to interfaces, whose methods are all pure
565virtual. In reality, sometimes you do need to mock a virtual method
566that is not pure (i.e, it already has an implementation). For example:
567
568```
569class Foo {
570 public:
571  virtual ~Foo();
572
573  virtual void Pure(int n) = 0;
574  virtual int Concrete(const char* str) { ... }
575};
576
577class MockFoo : public Foo {
578 public:
579  // Mocking a pure method.
580  MOCK_METHOD1(Pure, void(int n));
581  // Mocking a concrete method.  Foo::Concrete() is shadowed.
582  MOCK_METHOD1(Concrete, int(const char* str));
583};
584```
585
586Sometimes you may want to call `Foo::Concrete()` instead of
587`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub
588action, or perhaps your test doesn't need to mock `Concrete()` at all
589(but it would be oh-so painful to have to define a new mock class
590whenever you don't need to mock one of its methods).
591
592The trick is to leave a back door in your mock class for accessing the
593real methods in the base class:
594
595```
596class MockFoo : public Foo {
597 public:
598  // Mocking a pure method.
599  MOCK_METHOD1(Pure, void(int n));
600  // Mocking a concrete method.  Foo::Concrete() is shadowed.
601  MOCK_METHOD1(Concrete, int(const char* str));
602
603  // Use this to call Concrete() defined in Foo.
604  int FooConcrete(const char* str) { return Foo::Concrete(str); }
605};
606```
607
608Now, you can call `Foo::Concrete()` inside an action by:
609
610```
611using ::testing::_;
612using ::testing::Invoke;
613...
614  EXPECT_CALL(foo, Concrete(_))
615      .WillOnce(Invoke(&foo, &MockFoo::FooConcrete));
616```
617
618or tell the mock object that you don't want to mock `Concrete()`:
619
620```
621using ::testing::Invoke;
622...
623  ON_CALL(foo, Concrete(_))
624      .WillByDefault(Invoke(&foo, &MockFoo::FooConcrete));
625```
626
627(Why don't we just write `Invoke(&foo, &Foo::Concrete)`? If you do
628that, `MockFoo::Concrete()` will be called (and cause an infinite
629recursion) since `Foo::Concrete()` is virtual. That's just how C++
630works.)
631
632# Using Matchers #
633
634## Matching Argument Values Exactly ##
635
636You can specify exactly which arguments a mock method is expecting:
637
638```
639using ::testing::Return;
640...
641  EXPECT_CALL(foo, DoThis(5))
642      .WillOnce(Return('a'));
643  EXPECT_CALL(foo, DoThat("Hello", bar));
644```
645
646## Using Simple Matchers ##
647
648You can use matchers to match arguments that have a certain property:
649
650```
651using ::testing::Ge;
652using ::testing::NotNull;
653using ::testing::Return;
654...
655  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.
656      .WillOnce(Return('a'));
657  EXPECT_CALL(foo, DoThat("Hello", NotNull()));
658  // The second argument must not be NULL.
659```
660
661A frequently used matcher is `_`, which matches anything:
662
663```
664using ::testing::_;
665using ::testing::NotNull;
666...
667  EXPECT_CALL(foo, DoThat(_, NotNull()));
668```
669
670## Combining Matchers ##
671
672You can build complex matchers from existing ones using `AllOf()`,
673`AnyOf()`, and `Not()`:
674
675```
676using ::testing::AllOf;
677using ::testing::Gt;
678using ::testing::HasSubstr;
679using ::testing::Ne;
680using ::testing::Not;
681...
682  // The argument must be > 5 and != 10.
683  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
684                                Ne(10))));
685
686  // The first argument must not contain sub-string "blah".
687  EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
688                          NULL));
689```
690
691## Casting Matchers ##
692
693Google Mock matchers are statically typed, meaning that the compiler
694can catch your mistake if you use a matcher of the wrong type (for
695example, if you use `Eq(5)` to match a `string` argument). Good for
696you!
697
698Sometimes, however, you know what you're doing and want the compiler
699to give you some slack. One example is that you have a matcher for
700`long` and the argument you want to match is `int`. While the two
701types aren't exactly the same, there is nothing really wrong with
702using a `Matcher<long>` to match an `int` - after all, we can first
703convert the `int` argument to a `long` before giving it to the
704matcher.
705
706To support this need, Google Mock gives you the
707`SafeMatcherCast<T>(m)` function. It casts a matcher `m` to type
708`Matcher<T>`. To ensure safety, Google Mock checks that (let `U` be the
709type `m` accepts):
710
711  1. Type `T` can be implicitly cast to type `U`;
712  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
713  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).
714
715The code won't compile if any of these conditions isn't met.
716
717Here's one example:
718
719```
720using ::testing::SafeMatcherCast;
721
722// A base class and a child class.
723class Base { ... };
724class Derived : public Base { ... };
725
726class MockFoo : public Foo {
727 public:
728  MOCK_METHOD1(DoThis, void(Derived* derived));
729};
730...
731
732  MockFoo foo;
733  // m is a Matcher<Base*> we got from somewhere.
734  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
735```
736
737If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar
738function `MatcherCast<T>(m)`. The difference is that `MatcherCast` works
739as long as you can `static_cast` type `T` to type `U`.
740
741`MatcherCast` essentially lets you bypass C++'s type system
742(`static_cast` isn't always safe as it could throw away information,
743for example), so be careful not to misuse/abuse it.
744
745## Selecting Between Overloaded Functions ##
746
747If you expect an overloaded function to be called, the compiler may
748need some help on which overloaded version it is.
749
750To disambiguate functions overloaded on the const-ness of this object,
751use the `Const()` argument wrapper.
752
753```
754using ::testing::ReturnRef;
755
756class MockFoo : public Foo {
757  ...
758  MOCK_METHOD0(GetBar, Bar&());
759  MOCK_CONST_METHOD0(GetBar, const Bar&());
760};
761...
762
763  MockFoo foo;
764  Bar bar1, bar2;
765  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().
766      .WillOnce(ReturnRef(bar1));
767  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().
768      .WillOnce(ReturnRef(bar2));
769```
770
771(`Const()` is defined by Google Mock and returns a `const` reference
772to its argument.)
773
774To disambiguate overloaded functions with the same number of arguments
775but different argument types, you may need to specify the exact type
776of a matcher, either by wrapping your matcher in `Matcher<type>()`, or
777using a matcher whose type is fixed (`TypedEq<type>`, `An<type>()`,
778etc):
779
780```
781using ::testing::An;
782using ::testing::Lt;
783using ::testing::Matcher;
784using ::testing::TypedEq;
785
786class MockPrinter : public Printer {
787 public:
788  MOCK_METHOD1(Print, void(int n));
789  MOCK_METHOD1(Print, void(char c));
790};
791
792TEST(PrinterTest, Print) {
793  MockPrinter printer;
794
795  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);
796  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);
797  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);
798
799  printer.Print(3);
800  printer.Print(6);
801  printer.Print('a');
802}
803```
804
805## Performing Different Actions Based on the Arguments ##
806
807When a mock method is called, the _last_ matching expectation that's
808still active will be selected (think "newer overrides older"). So, you
809can make a method do different things depending on its argument values
810like this:
811
812```
813using ::testing::_;
814using ::testing::Lt;
815using ::testing::Return;
816...
817  // The default case.
818  EXPECT_CALL(foo, DoThis(_))
819      .WillRepeatedly(Return('b'));
820
821  // The more specific case.
822  EXPECT_CALL(foo, DoThis(Lt(5)))
823      .WillRepeatedly(Return('a'));
824```
825
826Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will
827be returned; otherwise `'b'` will be returned.
828
829## Matching Multiple Arguments as a Whole ##
830
831Sometimes it's not enough to match the arguments individually. For
832example, we may want to say that the first argument must be less than
833the second argument. The `With()` clause allows us to match
834all arguments of a mock function as a whole. For example,
835
836```
837using ::testing::_;
838using ::testing::Lt;
839using ::testing::Ne;
840...
841  EXPECT_CALL(foo, InRange(Ne(0), _))
842      .With(Lt());
843```
844
845says that the first argument of `InRange()` must not be 0, and must be
846less than the second argument.
847
848The expression inside `With()` must be a matcher of type
849`Matcher<tr1::tuple<A1, ..., An> >`, where `A1`, ..., `An` are the
850types of the function arguments.
851
852You can also write `AllArgs(m)` instead of `m` inside `.With()`. The
853two forms are equivalent, but `.With(AllArgs(Lt()))` is more readable
854than `.With(Lt())`.
855
856You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments
857against `m`. For example,
858
859```
860using ::testing::_;
861using ::testing::AllOf;
862using ::testing::Args;
863using ::testing::Lt;
864...
865  EXPECT_CALL(foo, Blah(_, _, _))
866      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
867```
868
869says that `Blah()` will be called with arguments `x`, `y`, and `z` where
870`x < y < z`.
871
872As a convenience and example, Google Mock provides some matchers for
8732-tuples, including the `Lt()` matcher above. See the [CheatSheet](V1_5_CheatSheet.md) for
874the complete list.
875
876## Using Matchers as Predicates ##
877
878Have you noticed that a matcher is just a fancy predicate that also
879knows how to describe itself? Many existing algorithms take predicates
880as arguments (e.g. those defined in STL's `<algorithm>` header), and
881it would be a shame if Google Mock matchers are not allowed to
882participate.
883
884Luckily, you can use a matcher where a unary predicate functor is
885expected by wrapping it inside the `Matches()` function. For example,
886
887```
888#include <algorithm>
889#include <vector>
890
891std::vector<int> v;
892...
893// How many elements in v are >= 10?
894const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
895```
896
897Since you can build complex matchers from simpler ones easily using
898Google Mock, this gives you a way to conveniently construct composite
899predicates (doing the same using STL's `<functional>` header is just
900painful). For example, here's a predicate that's satisfied by any
901number that is >= 0, <= 100, and != 50:
902
903```
904Matches(AllOf(Ge(0), Le(100), Ne(50)))
905```
906
907## Using Matchers in Google Test Assertions ##
908
909Since matchers are basically predicates that also know how to describe
910themselves, there is a way to take advantage of them in
911[Google Test](http://code.google.com/p/googletest/) assertions. It's
912called `ASSERT_THAT` and `EXPECT_THAT`:
913
914```
915  ASSERT_THAT(value, matcher);  // Asserts that value matches matcher.
916  EXPECT_THAT(value, matcher);  // The non-fatal version.
917```
918
919For example, in a Google Test test you can write:
920
921```
922#include <gmock/gmock.h>
923
924using ::testing::AllOf;
925using ::testing::Ge;
926using ::testing::Le;
927using ::testing::MatchesRegex;
928using ::testing::StartsWith;
929...
930
931  EXPECT_THAT(Foo(), StartsWith("Hello"));
932  EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
933  ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
934```
935
936which (as you can probably guess) executes `Foo()`, `Bar()`, and
937`Baz()`, and verifies that:
938
939  * `Foo()` returns a string that starts with `"Hello"`.
940  * `Bar()` returns a string that matches regular expression `"Line \\d+"`.
941  * `Baz()` returns a number in the range [5, 10].
942
943The nice thing about these macros is that _they read like
944English_. They generate informative messages too. For example, if the
945first `EXPECT_THAT()` above fails, the message will be something like:
946
947```
948Value of: Foo()
949  Actual: "Hi, world!"
950Expected: starts with "Hello"
951```
952
953**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was stolen from the
954[Hamcrest](http://code.google.com/p/hamcrest/) project, which adds
955`assertThat()` to JUnit.
956
957## Using Predicates as Matchers ##
958
959Google Mock provides a built-in set of matchers. In case you find them
960lacking, you can use an arbitray unary predicate function or functor
961as a matcher - as long as the predicate accepts a value of the type
962you want. You do this by wrapping the predicate inside the `Truly()`
963function, for example:
964
965```
966using ::testing::Truly;
967
968int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
969...
970
971  // Bar() must be called with an even number.
972  EXPECT_CALL(foo, Bar(Truly(IsEven)));
973```
974
975Note that the predicate function / functor doesn't have to return
976`bool`. It works as long as the return value can be used as the
977condition in statement `if (condition) ...`.
978
979## Matching Arguments that Are Not Copyable ##
980
981When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, Google Mock saves
982away a copy of `bar`. When `Foo()` is called later, Google Mock
983compares the argument to `Foo()` with the saved copy of `bar`. This
984way, you don't need to worry about `bar` being modified or destroyed
985after the `EXPECT_CALL()` is executed. The same is true when you use
986matchers like `Eq(bar)`, `Le(bar)`, and so on.
987
988But what if `bar` cannot be copied (i.e. has no copy constructor)? You
989could define your own matcher function and use it with `Truly()`, as
990the previous couple of recipes have shown. Or, you may be able to get
991away from it if you can guarantee that `bar` won't be changed after
992the `EXPECT_CALL()` is executed. Just tell Google Mock that it should
993save a reference to `bar`, instead of a copy of it. Here's how:
994
995```
996using ::testing::Eq;
997using ::testing::ByRef;
998using ::testing::Lt;
999...
1000  // Expects that Foo()'s argument == bar.
1001  EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
1002
1003  // Expects that Foo()'s argument < bar.
1004  EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
1005```
1006
1007Remember: if you do this, don't change `bar` after the
1008`EXPECT_CALL()`, or the result is undefined.
1009
1010## Validating a Member of an Object ##
1011
1012Often a mock function takes a reference to object as an argument. When
1013matching the argument, you may not want to compare the entire object
1014against a fixed object, as that may be over-specification. Instead,
1015you may need to validate a certain member variable or the result of a
1016certain getter method of the object. You can do this with `Field()`
1017and `Property()`. More specifically,
1018
1019```
1020Field(&Foo::bar, m)
1021```
1022
1023is a matcher that matches a `Foo` object whose `bar` member variable
1024satisfies matcher `m`.
1025
1026```
1027Property(&Foo::baz, m)
1028```
1029
1030is a matcher that matches a `Foo` object whose `baz()` method returns
1031a value that satisfies matcher `m`.
1032
1033For example:
1034
1035> | `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`. |
1036|:-----------------------------|:-----------------------------------|
1037> | `Property(&Foo::name, StartsWith("John "))` | Matches `x` where `x.name()` starts with `"John "`. |
1038
1039Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no
1040argument and be declared as `const`.
1041
1042BTW, `Field()` and `Property()` can also match plain pointers to
1043objects. For instance,
1044
1045```
1046Field(&Foo::number, Ge(3))
1047```
1048
1049matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`,
1050the match will always fail regardless of the inner matcher.
1051
1052What if you want to validate more than one members at the same time?
1053Remember that there is `AllOf()`.
1054
1055## Validating the Value Pointed to by a Pointer Argument ##
1056
1057C++ functions often take pointers as arguments. You can use matchers
1058like `NULL`, `NotNull()`, and other comparison matchers to match a
1059pointer, but what if you want to make sure the value _pointed to_ by
1060the pointer, instead of the pointer itself, has a certain property?
1061Well, you can use the `Pointee(m)` matcher.
1062
1063`Pointee(m)` matches a pointer iff `m` matches the value the pointer
1064points to. For example:
1065
1066```
1067using ::testing::Ge;
1068using ::testing::Pointee;
1069...
1070  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
1071```
1072
1073expects `foo.Bar()` to be called with a pointer that points to a value
1074greater than or equal to 3.
1075
1076One nice thing about `Pointee()` is that it treats a `NULL` pointer as
1077a match failure, so you can write `Pointee(m)` instead of
1078
1079```
1080  AllOf(NotNull(), Pointee(m))
1081```
1082
1083without worrying that a `NULL` pointer will crash your test.
1084
1085Also, did we tell you that `Pointee()` works with both raw pointers
1086**and** smart pointers (`linked_ptr`, `shared_ptr`, `scoped_ptr`, and
1087etc)?
1088
1089What if you have a pointer to pointer? You guessed it - you can use
1090nested `Pointee()` to probe deeper inside the value. For example,
1091`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer
1092that points to a number less than 3 (what a mouthful...).
1093
1094## Testing a Certain Property of an Object ##
1095
1096Sometimes you want to specify that an object argument has a certain
1097property, but there is no existing matcher that does this. If you want
1098good error messages, you should define a matcher. If you want to do it
1099quick and dirty, you could get away with writing an ordinary function.
1100
1101Let's say you have a mock function that takes an object of type `Foo`,
1102which has an `int bar()` method and an `int baz()` method, and you
1103want to constrain that the argument's `bar()` value plus its `baz()`
1104value is a given number. Here's how you can define a matcher to do it:
1105
1106```
1107using ::testing::MatcherInterface;
1108using ::testing::MatchResultListener;
1109
1110class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
1111 public:
1112  explicit BarPlusBazEqMatcher(int expected_sum)
1113      : expected_sum_(expected_sum) {}
1114
1115  virtual bool MatchAndExplain(const Foo& foo,
1116                               MatchResultListener* listener) const {
1117    return (foo.bar() + foo.baz()) == expected_sum_;
1118  }
1119
1120  virtual void DescribeTo(::std::ostream* os) const {
1121    *os << "bar() + baz() equals " << expected_sum_;
1122  }
1123
1124  virtual void DescribeNegationTo(::std::ostream* os) const {
1125    *os << "bar() + baz() does not equal " << expected_sum_;
1126  }
1127 private:
1128  const int expected_sum_;
1129};
1130
1131inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
1132  return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
1133}
1134
1135...
1136
1137  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
1138```
1139
1140## Matching Containers ##
1141
1142Sometimes an STL container (e.g. list, vector, map, ...) is passed to
1143a mock function and you may want to validate it. Since most STL
1144containers support the `==` operator, you can write
1145`Eq(expected_container)` or simply `expected_container` to match a
1146container exactly.
1147
1148Sometimes, though, you may want to be more flexible (for example, the
1149first element must be an exact match, but the second element can be
1150any positive number, and so on). Also, containers used in tests often
1151have a small number of elements, and having to define the expected
1152container out-of-line is a bit of a hassle.
1153
1154You can use the `ElementsAre()` matcher in such cases:
1155
1156```
1157using ::testing::_;
1158using ::testing::ElementsAre;
1159using ::testing::Gt;
1160...
1161
1162  MOCK_METHOD1(Foo, void(const vector<int>& numbers));
1163...
1164
1165  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
1166```
1167
1168The above matcher says that the container must have 4 elements, which
1169must be 1, greater than 0, anything, and 5 respectively.
1170
1171`ElementsAre()` is overloaded to take 0 to 10 arguments. If more are
1172needed, you can place them in a C-style array and use
1173`ElementsAreArray()` instead:
1174
1175```
1176using ::testing::ElementsAreArray;
1177...
1178
1179  // ElementsAreArray accepts an array of element values.
1180  const int expected_vector1[] = { 1, 5, 2, 4, ... };
1181  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));
1182
1183  // Or, an array of element matchers.
1184  Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... };
1185  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
1186```
1187
1188In case the array needs to be dynamically created (and therefore the
1189array size cannot be inferred by the compiler), you can give
1190`ElementsAreArray()` an additional argument to specify the array size:
1191
1192```
1193using ::testing::ElementsAreArray;
1194...
1195  int* const expected_vector3 = new int[count];
1196  ... fill expected_vector3 with values ...
1197  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
1198```
1199
1200**Tips:**
1201
1202  * `ElementAre*()` works with _any_ container that implements the STL iterator concept (i.e. it has a `const_iterator` type and supports `begin()/end()`) and supports `size()`, 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.
1203  * You can use nested `ElementAre*()` to match nested (multi-dimensional) containers.
1204  * If the container is passed by pointer instead of by reference, just write `Pointee(ElementsAre*(...))`.
1205  * The order of elements _matters_ for `ElementsAre*()`. Therefore don't use it with containers whose element order is undefined (e.g. `hash_map`).
1206
1207## Sharing Matchers ##
1208
1209Under the hood, a Google Mock matcher object consists of a pointer to
1210a ref-counted implementation object. Copying matchers is allowed and
1211very efficient, as only the pointer is copied. When the last matcher
1212that references the implementation object dies, the implementation
1213object will be deleted.
1214
1215Therefore, if you have some complex matcher that you want to use again
1216and again, there is no need to build it everytime. Just assign it to a
1217matcher variable and use that variable repeatedly! For example,
1218
1219```
1220  Matcher<int> in_range = AllOf(Gt(5), Le(10));
1221  ... use in_range as a matcher in multiple EXPECT_CALLs ...
1222```
1223
1224# Setting Expectations #
1225
1226## Ignoring Uninteresting Calls ##
1227
1228If you are not interested in how a mock method is called, just don't
1229say anything about it. In this case, if the method is ever called,
1230Google Mock will perform its default action to allow the test program
1231to continue. If you are not happy with the default action taken by
1232Google Mock, you can override it using `DefaultValue<T>::Set()`
1233(described later in this document) or `ON_CALL()`.
1234
1235Please note that once you expressed interest in a particular mock
1236method (via `EXPECT_CALL()`), all invocations to it must match some
1237expectation. If this function is called but the arguments don't match
1238any `EXPECT_CALL()` statement, it will be an error.
1239
1240## Disallowing Unexpected Calls ##
1241
1242If a mock method shouldn't be called at all, explicitly say so:
1243
1244```
1245using ::testing::_;
1246...
1247  EXPECT_CALL(foo, Bar(_))
1248      .Times(0);
1249```
1250
1251If some calls to the method are allowed, but the rest are not, just
1252list all the expected calls:
1253
1254```
1255using ::testing::AnyNumber;
1256using ::testing::Gt;
1257...
1258  EXPECT_CALL(foo, Bar(5));
1259  EXPECT_CALL(foo, Bar(Gt(10)))
1260      .Times(AnyNumber());
1261```
1262
1263A call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()`
1264statements will be an error.
1265
1266## Expecting Ordered Calls ##
1267
1268Although an `EXPECT_CALL()` statement defined earlier takes precedence
1269when Google Mock tries to match a function call with an expectation,
1270by default calls don't have to happen in the order `EXPECT_CALL()`
1271statements are written. For example, if the arguments match the
1272matchers in the third `EXPECT_CALL()`, but not those in the first two,
1273then the third expectation will be used.
1274
1275If you would rather have all calls occur in the order of the
1276expectations, put the `EXPECT_CALL()` statements in a block where you
1277define a variable of type `InSequence`:
1278
1279```
1280  using ::testing::_;
1281  using ::testing::InSequence;
1282
1283  {
1284    InSequence s;
1285
1286    EXPECT_CALL(foo, DoThis(5));
1287    EXPECT_CALL(bar, DoThat(_))
1288        .Times(2);
1289    EXPECT_CALL(foo, DoThis(6));
1290  }
1291```
1292
1293In this example, we expect a call to `foo.DoThis(5)`, followed by two
1294calls to `bar.DoThat()` where the argument can be anything, which are
1295in turn followed by a call to `foo.DoThis(6)`. If a call occurred
1296out-of-order, Google Mock will report an error.
1297
1298## Expecting Partially Ordered Calls ##
1299
1300Sometimes requiring everything to occur in a predetermined order can
1301lead to brittle tests. For example, we may care about `A` occurring
1302before both `B` and `C`, but aren't interested in the relative order
1303of `B` and `C`. In this case, the test should reflect our real intent,
1304instead of being overly constraining.
1305
1306Google Mock allows you to impose an arbitrary DAG (directed acyclic
1307graph) on the calls. One way to express the DAG is to use the
1308[After](V1_5_CheatSheet#The_After_Clause.md) clause of `EXPECT_CALL`.
1309
1310Another way is via the `InSequence()` clause (not the same as the
1311`InSequence` class), which we borrowed from jMock 2. It's less
1312flexible than `After()`, but more convenient when you have long chains
1313of sequential calls, as it doesn't require you to come up with
1314different names for the expectations in the chains.  Here's how it
1315works:
1316
1317If we view `EXPECT_CALL()` statements as nodes in a graph, and add an
1318edge from node A to node B wherever A must occur before B, we can get
1319a DAG. We use the term "sequence" to mean a directed path in this
1320DAG. Now, if we decompose the DAG into sequences, we just need to know
1321which sequences each `EXPECT_CALL()` belongs to in order to be able to
1322reconstruct the orginal DAG.
1323
1324So, to specify the partial order on the expectations we need to do two
1325things: first to define some `Sequence` objects, and then for each
1326`EXPECT_CALL()` say which `Sequence` objects it is part
1327of. Expectations in the same sequence must occur in the order they are
1328written. For example,
1329
1330```
1331  using ::testing::Sequence;
1332
1333  Sequence s1, s2;
1334
1335  EXPECT_CALL(foo, A())
1336      .InSequence(s1, s2);
1337  EXPECT_CALL(bar, B())
1338      .InSequence(s1);
1339  EXPECT_CALL(bar, C())
1340      .InSequence(s2);
1341  EXPECT_CALL(foo, D())
1342      .InSequence(s2);
1343```
1344
1345specifies the following DAG (where `s1` is `A -> B`, and `s2` is `A ->
1346C -> D`):
1347
1348```
1349       +---> B
1350       |
1351  A ---|
1352       |
1353       +---> C ---> D
1354```
1355
1356This means that A must occur before B and C, and C must occur before
1357D. There's no restriction about the order other than these.
1358
1359## Controlling When an Expectation Retires ##
1360
1361When a mock method is called, Google Mock only consider expectations
1362that are still active. An expectation is active when created, and
1363becomes inactive (aka _retires_) when a call that has to occur later
1364has occurred. For example, in
1365
1366```
1367  using ::testing::_;
1368  using ::testing::Sequence;
1369
1370  Sequence s1, s2;
1371
1372  EXPECT_CALL(log, Log(WARNING, _, "File too large."))     // #1
1373      .Times(AnyNumber())
1374      .InSequence(s1, s2);
1375  EXPECT_CALL(log, Log(WARNING, _, "Data set is empty."))  // #2
1376      .InSequence(s1);
1377  EXPECT_CALL(log, Log(WARNING, _, "User not found."))     // #3
1378      .InSequence(s2);
1379```
1380
1381as soon as either #2 or #3 is matched, #1 will retire. If a warning
1382`"File too large."` is logged after this, it will be an error.
1383
1384Note that an expectation doesn't retire automatically when it's
1385saturated. For example,
1386
1387```
1388using ::testing::_;
1389...
1390  EXPECT_CALL(log, Log(WARNING, _, _));                  // #1
1391  EXPECT_CALL(log, Log(WARNING, _, "File too large."));  // #2
1392```
1393
1394says that there will be exactly one warning with the message `"File
1395too large."`. If the second warning contains this message too, #2 will
1396match again and result in an upper-bound-violated error.
1397
1398If this is not what you want, you can ask an expectation to retire as
1399soon as it becomes saturated:
1400
1401```
1402using ::testing::_;
1403...
1404  EXPECT_CALL(log, Log(WARNING, _, _));                 // #1
1405  EXPECT_CALL(log, Log(WARNING, _, "File too large."))  // #2
1406      .RetiresOnSaturation();
1407```
1408
1409Here #2 can be used only once, so if you have two warnings with the
1410message `"File too large."`, the first will match #2 and the second
1411will match #1 - there will be no error.
1412
1413# Using Actions #
1414
1415## Returning References from Mock Methods ##
1416
1417If a mock function's return type is a reference, you need to use
1418`ReturnRef()` instead of `Return()` to return a result:
1419
1420```
1421using ::testing::ReturnRef;
1422
1423class MockFoo : public Foo {
1424 public:
1425  MOCK_METHOD0(GetBar, Bar&());
1426};
1427...
1428
1429  MockFoo foo;
1430  Bar bar;
1431  EXPECT_CALL(foo, GetBar())
1432      .WillOnce(ReturnRef(bar));
1433```
1434
1435## Combining Actions ##
1436
1437Want to do more than one thing when a function is called? That's
1438fine. `DoAll()` allow you to do sequence of actions every time. Only
1439the return value of the last action in the sequence will be used.
1440
1441```
1442using ::testing::DoAll;
1443
1444class MockFoo : public Foo {
1445 public:
1446  MOCK_METHOD1(Bar, bool(int n));
1447};
1448...
1449
1450  EXPECT_CALL(foo, Bar(_))
1451      .WillOnce(DoAll(action_1,
1452                      action_2,
1453                      ...
1454                      action_n));
1455```
1456
1457## Mocking Side Effects ##
1458
1459Sometimes a method exhibits its effect not via returning a value but
1460via side effects. For example, it may change some global state or
1461modify an output argument. To mock side effects, in general you can
1462define your own action by implementing `::testing::ActionInterface`.
1463
1464If all you need to do is to change an output argument, the built-in
1465`SetArgumentPointee()` action is convenient:
1466
1467```
1468using ::testing::SetArgumentPointee;
1469
1470class MockMutator : public Mutator {
1471 public:
1472  MOCK_METHOD2(Mutate, void(bool mutate, int* value));
1473  ...
1474};
1475...
1476
1477  MockMutator mutator;
1478  EXPECT_CALL(mutator, Mutate(true, _))
1479      .WillOnce(SetArgumentPointee<1>(5));
1480```
1481
1482In this example, when `mutator.Mutate()` is called, we will assign 5
1483to the `int` variable pointed to by argument #1
1484(0-based).
1485
1486`SetArgumentPointee()` conveniently makes an internal copy of the
1487value you pass to it, removing the need to keep the value in scope and
1488alive. The implication however is that the value must have a copy
1489constructor and assignment operator.
1490
1491If the mock method also needs to return a value as well, you can chain
1492`SetArgumentPointee()` with `Return()` using `DoAll()`:
1493
1494```
1495using ::testing::_;
1496using ::testing::Return;
1497using ::testing::SetArgumentPointee;
1498
1499class MockMutator : public Mutator {
1500 public:
1501  ...
1502  MOCK_METHOD1(MutateInt, bool(int* value));
1503};
1504...
1505
1506  MockMutator mutator;
1507  EXPECT_CALL(mutator, MutateInt(_))
1508      .WillOnce(DoAll(SetArgumentPointee<0>(5),
1509                      Return(true)));
1510```
1511
1512If the output argument is an array, use the
1513`SetArrayArgument<N>(first, last)` action instead. It copies the
1514elements in source range `[first, last)` to the array pointed to by
1515the `N`-th (0-based) argument:
1516
1517```
1518using ::testing::NotNull;
1519using ::testing::SetArrayArgument;
1520
1521class MockArrayMutator : public ArrayMutator {
1522 public:
1523  MOCK_METHOD2(Mutate, void(int* values, int num_values));
1524  ...
1525};
1526...
1527
1528  MockArrayMutator mutator;
1529  int values[5] = { 1, 2, 3, 4, 5 };
1530  EXPECT_CALL(mutator, Mutate(NotNull(), 5))
1531      .WillOnce(SetArrayArgument<0>(values, values + 5));
1532```
1533
1534This also works when the argument is an output iterator:
1535
1536```
1537using ::testing::_;
1538using ::testing::SeArrayArgument;
1539
1540class MockRolodex : public Rolodex {
1541 public:
1542  MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >));
1543  ...
1544};
1545...
1546
1547  MockRolodex rolodex;
1548  vector<string> names;
1549  names.push_back("George");
1550  names.push_back("John");
1551  names.push_back("Thomas");
1552  EXPECT_CALL(rolodex, GetNames(_))
1553      .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
1554```
1555
1556## Changing a Mock Object's Behavior Based on the State ##
1557
1558If 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:
1559
1560```
1561using ::testing::InSequence;
1562using ::testing::Return;
1563
1564...
1565  {
1566    InSequence seq;
1567    EXPECT_CALL(my_mock, IsDirty())
1568        .WillRepeatedly(Return(true));
1569    EXPECT_CALL(my_mock, Flush());
1570    EXPECT_CALL(my_mock, IsDirty())
1571        .WillRepeatedly(Return(false));
1572  }
1573  my_mock.FlushIfDirty();
1574```
1575
1576This makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called and return `false` afterwards.
1577
1578If 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:
1579
1580```
1581using ::testing::_;
1582using ::testing::SaveArg;
1583using ::testing::Return;
1584
1585ACTION_P(ReturnPointee, p) { return *p; }
1586...
1587  int previous_value = 0;
1588  EXPECT_CALL(my_mock, GetPrevValue())
1589      .WillRepeatedly(ReturnPointee(&previous_value));
1590  EXPECT_CALL(my_mock, UpdateValue(_))
1591      .WillRepeatedly(SaveArg<0>(&previous_value));
1592  my_mock.DoSomethingToUpdateValue();
1593```
1594
1595Here `my_mock.GetPrevValue()` will always return the argument of the last `UpdateValue()` call.
1596
1597## Setting the Default Value for a Return Type ##
1598
1599If a mock method's return type is a built-in C++ type or pointer, by
1600default it will return 0 when invoked. You only need to specify an
1601action if this default value doesn't work for you.
1602
1603Sometimes, you may want to change this default value, or you may want
1604to specify a default value for types Google Mock doesn't know
1605about. You can do this using the `::testing::DefaultValue` class
1606template:
1607
1608```
1609class MockFoo : public Foo {
1610 public:
1611  MOCK_METHOD0(CalculateBar, Bar());
1612};
1613...
1614
1615  Bar default_bar;
1616  // Sets the default return value for type Bar.
1617  DefaultValue<Bar>::Set(default_bar);
1618
1619  MockFoo foo;
1620
1621  // We don't need to specify an action here, as the default
1622  // return value works for us.
1623  EXPECT_CALL(foo, CalculateBar());
1624
1625  foo.CalculateBar();  // This should return default_bar.
1626
1627  // Unsets the default return value.
1628  DefaultValue<Bar>::Clear();
1629```
1630
1631Please note that changing the default value for a type can make you
1632tests hard to understand. We recommend you to use this feature
1633judiciously. For example, you may want to make sure the `Set()` and
1634`Clear()` calls are right next to the code that uses your mock.
1635
1636## Setting the Default Actions for a Mock Method ##
1637
1638You've learned how to change the default value of a given
1639type. However, this may be too coarse for your purpose: perhaps you
1640have two mock methods with the same return type and you want them to
1641have different behaviors. The `ON_CALL()` macro allows you to
1642customize your mock's behavior at the method level:
1643
1644```
1645using ::testing::_;
1646using ::testing::AnyNumber;
1647using ::testing::Gt;
1648using ::testing::Return;
1649...
1650  ON_CALL(foo, Sign(_))
1651      .WillByDefault(Return(-1));
1652  ON_CALL(foo, Sign(0))
1653      .WillByDefault(Return(0));
1654  ON_CALL(foo, Sign(Gt(0)))
1655      .WillByDefault(Return(1));
1656
1657  EXPECT_CALL(foo, Sign(_))
1658      .Times(AnyNumber());
1659
1660  foo.Sign(5);   // This should return 1.
1661  foo.Sign(-9);  // This should return -1.
1662  foo.Sign(0);   // This should return 0.
1663```
1664
1665As you may have guessed, when there are more than one `ON_CALL()`
1666statements, the news order take precedence over the older ones. In
1667other words, the **last** one that matches the function arguments will
1668be used. This matching order allows you to set up the common behavior
1669in a mock object's constructor or the test fixture's set-up phase and
1670specialize the mock's behavior later.
1671
1672## Using Functions/Methods/Functors as Actions ##
1673
1674If the built-in actions don't suit you, you can easily use an existing
1675function, method, or functor as an action:
1676
1677```
1678using ::testing::_;
1679using ::testing::Invoke;
1680
1681class MockFoo : public Foo {
1682 public:
1683  MOCK_METHOD2(Sum, int(int x, int y));
1684  MOCK_METHOD1(ComplexJob, bool(int x));
1685};
1686
1687int CalculateSum(int x, int y) { return x + y; }
1688
1689class Helper {
1690 public:
1691  bool ComplexJob(int x);
1692};
1693...
1694
1695  MockFoo foo;
1696  Helper helper;
1697  EXPECT_CALL(foo, Sum(_, _))
1698      .WillOnce(Invoke(CalculateSum));
1699  EXPECT_CALL(foo, ComplexJob(_))
1700      .WillOnce(Invoke(&helper, &Helper::ComplexJob));
1701
1702  foo.Sum(5, 6);       // Invokes CalculateSum(5, 6).
1703  foo.ComplexJob(10);  // Invokes helper.ComplexJob(10);
1704```
1705
1706The only requirement is that the type of the function, etc must be
1707_compatible_ with the signature of the mock function, meaning that the
1708latter's arguments can be implicitly converted to the corresponding
1709arguments of the former, and the former's return type can be
1710implicitly converted to that of the latter. So, you can invoke
1711something whose type is _not_ exactly the same as the mock function,
1712as long as it's safe to do so - nice, huh?
1713
1714## Invoking a Function/Method/Functor Without Arguments ##
1715
1716`Invoke()` is very useful for doing actions that are more complex. It
1717passes the mock function's arguments to the function or functor being
1718invoked such that the callee has the full context of the call to work
1719with. If the invoked function is not interested in some or all of the
1720arguments, it can simply ignore them.
1721
1722Yet, a common pattern is that a test author wants to invoke a function
1723without the arguments of the mock function. `Invoke()` allows her to
1724do that using a wrapper function that throws away the arguments before
1725invoking an underlining nullary function. Needless to say, this can be
1726tedious and obscures the intent of the test.
1727
1728`InvokeWithoutArgs()` solves this problem. It's like `Invoke()` except
1729that it doesn't pass the mock function's arguments to the
1730callee. Here's an example:
1731
1732```
1733using ::testing::_;
1734using ::testing::InvokeWithoutArgs;
1735
1736class MockFoo : public Foo {
1737 public:
1738  MOCK_METHOD1(ComplexJob, bool(int n));
1739};
1740
1741bool Job1() { ... }
1742...
1743
1744  MockFoo foo;
1745  EXPECT_CALL(foo, ComplexJob(_))
1746      .WillOnce(InvokeWithoutArgs(Job1));
1747
1748  foo.ComplexJob(10);  // Invokes Job1().
1749```
1750
1751## Invoking an Argument of the Mock Function ##
1752
1753Sometimes a mock function will receive a function pointer or a functor
1754(in other words, a "callable") as an argument, e.g.
1755
1756```
1757class MockFoo : public Foo {
1758 public:
1759  MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int)));
1760};
1761```
1762
1763and you may want to invoke this callable argument:
1764
1765```
1766using ::testing::_;
1767...
1768  MockFoo foo;
1769  EXPECT_CALL(foo, DoThis(_, _))
1770      .WillOnce(...);
1771  // Will execute (*fp)(5), where fp is the
1772  // second argument DoThis() receives.
1773```
1774
1775Arghh, you need to refer to a mock function argument but C++ has no
1776lambda (yet), so you have to define your own action. :-( Or do you
1777really?
1778
1779Well, Google Mock has an action to solve _exactly_ this problem:
1780
1781```
1782  InvokeArgument<N>(arg_1, arg_2, ..., arg_m)
1783```
1784
1785will invoke the `N`-th (0-based) argument the mock function receives,
1786with `arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is
1787a function pointer or a functor, Google Mock handles them both.
1788
1789With that, you could write:
1790
1791```
1792using ::testing::_;
1793using ::testing::InvokeArgument;
1794...
1795  EXPECT_CALL(foo, DoThis(_, _))
1796      .WillOnce(InvokeArgument<1>(5));
1797  // Will execute (*fp)(5), where fp is the
1798  // second argument DoThis() receives.
1799```
1800
1801What if the callable takes an argument by reference? No problem - just
1802wrap it inside `ByRef()`:
1803
1804```
1805...
1806  MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&)));
1807...
1808using ::testing::_;
1809using ::testing::ByRef;
1810using ::testing::InvokeArgument;
1811...
1812
1813  MockFoo foo;
1814  Helper helper;
1815  ...
1816  EXPECT_CALL(foo, Bar(_))
1817      .WillOnce(InvokeArgument<0>(5, ByRef(helper)));
1818  // ByRef(helper) guarantees that a reference to helper, not a copy of it,
1819  // will be passed to the callable.
1820```
1821
1822What if the callable takes an argument by reference and we do **not**
1823wrap the argument in `ByRef()`? Then `InvokeArgument()` will _make a
1824copy_ of the argument, and pass a _reference to the copy_, instead of
1825a reference to the original value, to the callable. This is especially
1826handy when the argument is a temporary value:
1827
1828```
1829...
1830  MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s)));
1831...
1832using ::testing::_;
1833using ::testing::InvokeArgument;
1834...
1835
1836  MockFoo foo;
1837  ...
1838  EXPECT_CALL(foo, DoThat(_))
1839      .WillOnce(InvokeArgument<0>(5.0, string("Hi")));
1840  // Will execute (*f)(5.0, string("Hi")), where f is the function pointer
1841  // DoThat() receives.  Note that the values 5.0 and string("Hi") are
1842  // temporary and dead once the EXPECT_CALL() statement finishes.  Yet
1843  // it's fine to perform this action later, since a copy of the values
1844  // are kept inside the InvokeArgument action.
1845```
1846
1847## Ignoring an Action's Result ##
1848
1849Sometimes you have an action that returns _something_, but you need an
1850action that returns `void` (perhaps you want to use it in a mock
1851function that returns `void`, or perhaps it needs to be used in
1852`DoAll()` and it's not the last in the list). `IgnoreResult()` lets
1853you do that. For example:
1854
1855```
1856using ::testing::_;
1857using ::testing::Invoke;
1858using ::testing::Return;
1859
1860int Process(const MyData& data);
1861string DoSomething();
1862
1863class MockFoo : public Foo {
1864 public:
1865  MOCK_METHOD1(Abc, void(const MyData& data));
1866  MOCK_METHOD0(Xyz, bool());
1867};
1868...
1869
1870  MockFoo foo;
1871  EXPECT_CALL(foo, Abc(_))
1872  // .WillOnce(Invoke(Process));
1873  // The above line won't compile as Process() returns int but Abc() needs
1874  // to return void.
1875      .WillOnce(IgnoreResult(Invoke(Process)));
1876
1877  EXPECT_CALL(foo, Xyz())
1878      .WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)),
1879      // Ignores the string DoSomething() returns.
1880                      Return(true)));
1881```
1882
1883Note that you **cannot** use `IgnoreResult()` on an action that already
1884returns `void`. Doing so will lead to ugly compiler errors.
1885
1886## Selecting an Action's Arguments ##
1887
1888Say you have a mock function `Foo()` that takes seven arguments, and
1889you have a custom action that you want to invoke when `Foo()` is
1890called. Trouble is, the custom action only wants three arguments:
1891
1892```
1893using ::testing::_;
1894using ::testing::Invoke;
1895...
1896  MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y,
1897                         const map<pair<int, int>, double>& weight,
1898                         double min_weight, double max_wight));
1899...
1900
1901bool IsVisibleInQuadrant1(bool visible, int x, int y) {
1902  return visible && x >= 0 && y >= 0;
1903}
1904...
1905
1906  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
1907      .WillOnce(Invoke(IsVisibleInQuadrant1));  // Uh, won't compile. :-(
1908```
1909
1910To please the compiler God, you can to define an "adaptor" that has
1911the same signature as `Foo()` and calls the custom action with the
1912right arguments:
1913
1914```
1915using ::testing::_;
1916using ::testing::Invoke;
1917
1918bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,
1919                            const map<pair<int, int>, double>& weight,
1920                            double min_weight, double max_wight) {
1921  return IsVisibleInQuadrant1(visible, x, y);
1922}
1923...
1924
1925  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
1926      .WillOnce(Invoke(MyIsVisibleInQuadrant1));  // Now it works.
1927```
1928
1929But isn't this awkward?
1930
1931Google Mock provides a generic _action adaptor_, so you can spend your
1932time minding more important business than writing your own
1933adaptors. Here's the syntax:
1934
1935```
1936  WithArgs<N1, N2, ..., Nk>(action)
1937```
1938
1939creates an action that passes the arguments of the mock function at
1940the given indices (0-based) to the inner `action` and performs
1941it. Using `WithArgs`, our original example can be written as:
1942
1943```
1944using ::testing::_;
1945using ::testing::Invoke;
1946using ::testing::WithArgs;
1947...
1948  EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
1949      .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));
1950      // No need to define your own adaptor.
1951```
1952
1953For better readability, Google Mock also gives you:
1954
1955  * `WithoutArgs(action)` when the inner `action` takes _no_ argument, and
1956  * `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes _one_ argument.
1957
1958As you may have realized, `InvokeWithoutArgs(...)` is just syntactic
1959sugar for `WithoutArgs(Inovke(...))`.
1960
1961Here are more tips:
1962
1963  * The inner action used in `WithArgs` and friends does not have to be `Invoke()` -- it can be anything.
1964  * You can repeat an argument in the argument list if necessary, e.g. `WithArgs<2, 3, 3, 5>(...)`.
1965  * You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`.
1966  * 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.
1967
1968## Ignoring Arguments in Action Functions ##
1969
1970The selecting-an-action's-arguments recipe showed us one way to make a
1971mock function and an action with incompatible argument lists fit
1972together. The downside is that wrapping the action in
1973`WithArgs<...>()` can get tedious for people writing the tests.
1974
1975If you are defining a function, method, or functor to be used with
1976`Invoke*()`, and you are not interested in some of its arguments, an
1977alternative to `WithArgs` is to declare the uninteresting arguments as
1978`Unused`. This makes the definition less cluttered and less fragile in
1979case the types of the uninteresting arguments change. It could also
1980increase the chance the action function can be reused. For example,
1981given
1982
1983```
1984  MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1985  MOCK_METHOD3(Bar, double(int index, double x, double y));
1986```
1987
1988instead of
1989
1990```
1991using ::testing::_;
1992using ::testing::Invoke;
1993
1994double DistanceToOriginWithLabel(const string& label, double x, double y) {
1995  return sqrt(x*x + y*y);
1996}
1997
1998double DistanceToOriginWithIndex(int index, double x, double y) {
1999  return sqrt(x*x + y*y);
2000}
2001...
2002
2003  EXEPCT_CALL(mock, Foo("abc", _, _))
2004      .WillOnce(Invoke(DistanceToOriginWithLabel));
2005  EXEPCT_CALL(mock, Bar(5, _, _))
2006      .WillOnce(Invoke(DistanceToOriginWithIndex));
2007```
2008
2009you could write
2010
2011```
2012using ::testing::_;
2013using ::testing::Invoke;
2014using ::testing::Unused;
2015
2016double DistanceToOrigin(Unused, double x, double y) {
2017  return sqrt(x*x + y*y);
2018}
2019...
2020
2021  EXEPCT_CALL(mock, Foo("abc", _, _))
2022      .WillOnce(Invoke(DistanceToOrigin));
2023  EXEPCT_CALL(mock, Bar(5, _, _))
2024      .WillOnce(Invoke(DistanceToOrigin));
2025```
2026
2027## Sharing Actions ##
2028
2029Just like matchers, a Google Mock action object consists of a pointer
2030to a ref-counted implementation object. Therefore copying actions is
2031also allowed and very efficient. When the last action that references
2032the implementation object dies, the implementation object will be
2033deleted.
2034
2035If you have some complex action that you want to use again and again,
2036you may not have to build it from scratch everytime. If the action
2037doesn't have an internal state (i.e. if it always does the same thing
2038no matter how many times it has been called), you can assign it to an
2039action variable and use that variable repeatedly. For example:
2040
2041```
2042  Action<bool(int*)> set_flag = DoAll(SetArgumentPointee<0>(5),
2043                                      Return(true));
2044  ... use set_flag in .WillOnce() and .WillRepeatedly() ...
2045```
2046
2047However, if the action has its own state, you may be surprised if you
2048share the action object. Suppose you have an action factory
2049`IncrementCounter(init)` which creates an action that increments and
2050returns a counter whose initial value is `init`, using two actions
2051created from the same expression and using a shared action will
2052exihibit different behaviors. Example:
2053
2054```
2055  EXPECT_CALL(foo, DoThis())
2056      .WillRepeatedly(IncrementCounter(0));
2057  EXPECT_CALL(foo, DoThat())
2058      .WillRepeatedly(IncrementCounter(0));
2059  foo.DoThis();  // Returns 1.
2060  foo.DoThis();  // Returns 2.
2061  foo.DoThat();  // Returns 1 - Blah() uses a different
2062                 // counter than Bar()'s.
2063```
2064
2065versus
2066
2067```
2068  Action<int()> increment = IncrementCounter(0);
2069
2070  EXPECT_CALL(foo, DoThis())
2071      .WillRepeatedly(increment);
2072  EXPECT_CALL(foo, DoThat())
2073      .WillRepeatedly(increment);
2074  foo.DoThis();  // Returns 1.
2075  foo.DoThis();  // Returns 2.
2076  foo.DoThat();  // Returns 3 - the counter is shared.
2077```
2078
2079# Misc Recipes on Using Google Mock #
2080
2081## Forcing a Verification ##
2082
2083When it's being destoyed, your friendly mock object will automatically
2084verify that all expectations on it have been satisfied, and will
2085generate [Google Test](http://code.google.com/p/googletest/) failures
2086if not. This is convenient as it leaves you with one less thing to
2087worry about. That is, unless you are not sure if your mock object will
2088be destoyed.
2089
2090How could it be that your mock object won't eventually be destroyed?
2091Well, it might be created on the heap and owned by the code you are
2092testing. Suppose there's a bug in that code and it doesn't delete the
2093mock object properly - you could end up with a passing test when
2094there's actually a bug.
2095
2096Using a heap checker is a good idea and can alleviate the concern, but
2097its implementation may not be 100% reliable. So, sometimes you do want
2098to _force_ Google Mock to verify a mock object before it is
2099(hopefully) destructed. You can do this with
2100`Mock::VerifyAndClearExpectations(&mock_object)`:
2101
2102```
2103TEST(MyServerTest, ProcessesRequest) {
2104  using ::testing::Mock;
2105
2106  MockFoo* const foo = new MockFoo;
2107  EXPECT_CALL(*foo, ...)...;
2108  // ... other expectations ...
2109
2110  // server now owns foo.
2111  MyServer server(foo);
2112  server.ProcessRequest(...);
2113
2114  // In case that server's destructor will forget to delete foo,
2115  // this will verify the expectations anyway.
2116  Mock::VerifyAndClearExpectations(foo);
2117}  // server is destroyed when it goes out of scope here.
2118```
2119
2120**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a
2121`bool` to indicate whether the verification was successful (`true` for
2122yes), so you can wrap that function call inside a `ASSERT_TRUE()` if
2123there is no point going further when the verification has failed.
2124
2125## Using Check Points ##
2126
2127Sometimes you may want to "reset" a mock object at various check
2128points in your test: at each check point, you verify that all existing
2129expectations on the mock object have been satisfied, and then you set
2130some new expectations on it as if it's newly created. This allows you
2131to work with a mock object in "phases" whose sizes are each
2132manageable.
2133
2134One such scenario is that in your test's `SetUp()` function, you may
2135want to put the object you are testing into a certain state, with the
2136help from a mock object. Once in the desired state, you want to clear
2137all expectations on the mock, such that in the `TEST_F` body you can
2138set fresh expectations on it.
2139
2140As you may have figured out, the `Mock::VerifyAndClearExpectations()`
2141function we saw in the previous recipe can help you here. Or, if you
2142are using `ON_CALL()` to set default actions on the mock object and
2143want to clear the default actions as well, use
2144`Mock::VerifyAndClear(&mock_object)` instead. This function does what
2145`Mock::VerifyAndClearExpectations(&mock_object)` does and returns the
2146same `bool`, **plus** it clears the `ON_CALL()` statements on
2147`mock_object` too.
2148
2149Another trick you can use to achieve the same effect is to put the
2150expectations in sequences and insert calls to a dummy "check-point"
2151function at specific places. Then you can verify that the mock
2152function calls do happen at the right time. For example, if you are
2153exercising code:
2154
2155```
2156Foo(1);
2157Foo(2);
2158Foo(3);
2159```
2160
2161and want to verify that `Foo(1)` and `Foo(3)` both invoke
2162`mock.Bar("a")`, but `Foo(2)` doesn't invoke anything. You can write:
2163
2164```
2165using ::testing::MockFunction;
2166
2167TEST(FooTest, InvokesBarCorrectly) {
2168  MyMock mock;
2169  // Class MockFunction<F> has exactly one mock method.  It is named
2170  // Call() and has type F.
2171  MockFunction<void(string check_point_name)> check;
2172  {
2173    InSequence s;
2174
2175    EXPECT_CALL(mock, Bar("a"));
2176    EXPECT_CALL(check, Call("1"));
2177    EXPECT_CALL(check, Call("2"));
2178    EXPECT_CALL(mock, Bar("a"));
2179  }
2180  Foo(1);
2181  check.Call("1");
2182  Foo(2);
2183  check.Call("2");
2184  Foo(3);
2185}
2186```
2187
2188The expectation spec says that the first `Bar("a")` must happen before
2189check point "1", the second `Bar("a")` must happen after check point "2",
2190and nothing should happen between the two check points. The explicit
2191check points make it easy to tell which `Bar("a")` is called by which
2192call to `Foo()`.
2193
2194## Mocking Destructors ##
2195
2196Sometimes you want to make sure a mock object is destructed at the
2197right time, e.g. after `bar->A()` is called but before `bar->B()` is
2198called. We already know that you can specify constraints on the order
2199of mock function calls, so all we need to do is to mock the destructor
2200of the mock function.
2201
2202This sounds simple, except for one problem: a destructor is a special
2203function with special syntax and special semantics, and the
2204`MOCK_METHOD0` macro doesn't work for it:
2205
2206```
2207  MOCK_METHOD0(~MockFoo, void());  // Won't compile!
2208```
2209
2210The good news is that you can use a simple pattern to achieve the same
2211effect. First, add a mock function `Die()` to your mock class and call
2212it in the destructor, like this:
2213
2214```
2215class MockFoo : public Foo {
2216  ...
2217  // Add the following two lines to the mock class.
2218  MOCK_METHOD0(Die, void());
2219  virtual ~MockFoo() { Die(); }
2220};
2221```
2222
2223(If the name `Die()` clashes with an existing symbol, choose another
2224name.) Now, we have translated the problem of testing when a `MockFoo`
2225object dies to testing when its `Die()` method is called:
2226
2227```
2228  MockFoo* foo = new MockFoo;
2229  MockBar* bar = new MockBar;
2230  ...
2231  {
2232    InSequence s;
2233
2234    // Expects *foo to die after bar->A() and before bar->B().
2235    EXPECT_CALL(*bar, A());
2236    EXPECT_CALL(*foo, Die());
2237    EXPECT_CALL(*bar, B());
2238  }
2239```
2240
2241And that's that.
2242
2243## Using Google Mock and Threads ##
2244
2245**IMPORTANT NOTE:** What we describe in this recipe is **NOT** true yet,
2246as Google Mock is not currently thread-safe.  However, all we need to
2247make it thread-safe is to implement some synchronization operations in
2248`<gtest/internal/gtest-port.h>` - and then the information below will
2249become true.
2250
2251In a **unit** test, it's best if you could isolate and test a piece of
2252code in a single-threaded context. That avoids race conditions and
2253dead locks, and makes debugging your test much easier.
2254
2255Yet many programs are multi-threaded, and sometimes to test something
2256we need to pound on it from more than one thread. Google Mock works
2257for this purpose too.
2258
2259Remember the steps for using a mock:
2260
2261  1. Create a mock object `foo`.
2262  1. Set its default actions and expectations using `ON_CALL()` and `EXPECT_CALL()`.
2263  1. The code under test calls methods of `foo`.
2264  1. Optionally, verify and reset the mock.
2265  1. Destroy the mock yourself, or let the code under test destroy it. The destructor will automatically verify it.
2266
2267If you follow the following simple rules, your mocks and threads can
2268live happily togeter:
2269
2270  * Execute your _test code_ (as opposed to the code being tested) in _one_ thread. This makes your test easy to follow.
2271  * Obviously, you can do step #1 without locking.
2272  * When doing step #2 and #5, make sure no other thread is accessing `foo`. Obvious too, huh?
2273  * #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.
2274
2275If you violate the rules (for example, if you set expectations on a
2276mock while another thread is calling its methods), you get undefined
2277behavior. That's not fun, so don't do it.
2278
2279Google Mock guarantees that the action for a mock function is done in
2280the same thread that called the mock function. For example, in
2281
2282```
2283  EXPECT_CALL(mock, Foo(1))
2284      .WillOnce(action1);
2285  EXPECT_CALL(mock, Foo(2))
2286      .WillOnce(action2);
2287```
2288
2289if `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2,
2290Google Mock will execute `action1` in thread 1 and `action2` in thread
22912.
2292
2293Google Mock does _not_ impose a sequence on actions performed in
2294different threads (doing so may create deadlocks as the actions may
2295need to cooperate). This means that the execution of `action1` and
2296`action2` in the above example _may_ interleave. If this is a problem,
2297you should add proper synchronization logic to `action1` and `action2`
2298to make the test thread-safe.
2299
2300
2301Also, remember that `DefaultValue<T>` is a global resource that
2302potentially affects _all_ living mock objects in your
2303program. Naturally, you won't want to mess with it from multiple
2304threads or when there still are mocks in action.
2305
2306## Controlling How Much Information Google Mock Prints ##
2307
2308When Google Mock sees something that has the potential of being an
2309error (e.g. a mock function with no expectation is called, a.k.a. an
2310uninteresting call, which is allowed but perhaps you forgot to
2311explicitly ban the call), it prints some warning messages, including
2312the arguments of the function and the return value. Hopefully this
2313will remind you to take a look and see if there is indeed a problem.
2314
2315Sometimes you are confident that your tests are correct and may not
2316appreciate such friendly messages. Some other times, you are debugging
2317your tests or learning about the behavior of the code you are testing,
2318and wish you could observe every mock call that happens (including
2319argument values and the return value). Clearly, one size doesn't fit
2320all.
2321
2322You can control how much Google Mock tells you using the
2323`--gmock_verbose=LEVEL` command-line flag, where `LEVEL` is a string
2324with three possible values:
2325
2326  * `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.
2327  * `warning`: Google Mock will print both warnings and errors (less verbose). This is the default.
2328  * `error`: Google Mock will print errors only (least verbose).
2329
2330Alternatively, you can adjust the value of that flag from within your
2331tests like so:
2332
2333```
2334  ::testing::FLAGS_gmock_verbose = "error";
2335```
2336
2337Now, judiciously use the right flag to enable Google Mock serve you better!
2338
2339## Running Tests in Emacs ##
2340
2341If you build and run your tests in Emacs, the source file locations of
2342Google Mock and [Google Test](http://code.google.com/p/googletest/)
2343errors will be highlighted. Just press `<Enter>` on one of them and
2344you'll be taken to the offending line. Or, you can just type `C-x ``
2345to jump to the next error.
2346
2347To make it even easier, you can add the following lines to your
2348`~/.emacs` file:
2349
2350```
2351(global-set-key "\M-m"   'compile)  ; m is for make
2352(global-set-key [M-down] 'next-error)
2353(global-set-key [M-up]   '(lambda () (interactive) (next-error -1)))
2354```
2355
2356Then you can type `M-m` to start a build, or `M-up`/`M-down` to move
2357back and forth between errors.
2358
2359## Fusing Google Mock Source Files ##
2360
2361Google Mock's implementation consists of dozens of files (excluding
2362its own tests).  Sometimes you may want them to be packaged up in
2363fewer files instead, such that you can easily copy them to a new
2364machine and start hacking there.  For this we provide an experimental
2365Python script `fuse_gmock_files.py` in the `scripts/` directory
2366(starting with release 1.2.0).  Assuming you have Python 2.4 or above
2367installed on your machine, just go to that directory and run
2368```
2369python fuse_gmock_files.py OUTPUT_DIR
2370```
2371
2372and you should see an `OUTPUT_DIR` directory being created with files
2373`gtest/gtest.h`, `gmock/gmock.h`, and `gmock-gtest-all.cc` in it.
2374These three files contain everything you need to use Google Mock (and
2375Google Test).  Just copy them to anywhere you want and you are ready
2376to write tests and use mocks.  You can use the
2377[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
2378against them.
2379
2380# Extending Google Mock #
2381
2382## Writing New Matchers Quickly ##
2383
2384The `MATCHER*` family of macros can be used to define custom matchers
2385easily.  The syntax:
2386
2387```
2388MATCHER(name, "description string") { statements; }
2389```
2390
2391will define a matcher with the given name that executes the
2392statements, which must return a `bool` to indicate if the match
2393succeeds.  Inside the statements, you can refer to the value being
2394matched by `arg`, and refer to its type by `arg_type`.
2395
2396The description string documents what the matcher does, and is used to
2397generate the failure message when the match fails.  Since a
2398`MATCHER()` is usually defined in a header file shared by multiple C++
2399source files, we require the description to be a C-string _literal_ to
2400avoid possible side effects.  It can be empty (`""`), in which case
2401Google Mock will use the sequence of words in the matcher name as the
2402description.
2403
2404For example:
2405```
2406MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
2407```
2408allows you to write
2409```
2410  // Expects mock_foo.Bar(n) to be called where n is divisible by 7.
2411  EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));
2412```
2413or,
2414```
2415  // Verifies that the value of some_expression is divisible by 7.
2416  EXPECT_THAT(some_expression, IsDivisibleBy7());
2417```
2418If the above assertion fails, it will print something like:
2419```
2420  Value of: some_expression
2421  Expected: is divisible by 7
2422    Actual: 27
2423```
2424where the description `"is divisible by 7"` is automatically calculated from the
2425matcher name `IsDivisibleBy7`.
2426
2427Optionally, you can stream additional information to a hidden argument
2428named `result_listener` to explain the match result. For example, a
2429better definition of `IsDivisibleBy7` is:
2430```
2431MATCHER(IsDivisibleBy7, "") {
2432  if ((arg % 7) == 0)
2433    return true;
2434
2435  *result_listener << "the remainder is " << (arg % 7);
2436  return false;
2437}
2438```
2439
2440With this definition, the above assertion will give a better message:
2441```
2442  Value of: some_expression
2443  Expected: is divisible by 7
2444    Actual: 27 (the remainder is 6)
2445```
2446
2447You should let `MatchAndExplain()` print _any additional information_
2448that can help a user understand the match result. Note that it should
2449explain why the match succeeds in case of a success (unless it's
2450obvious) - this is useful when the matcher is used inside
2451`Not()`. There is no need to print the argument value itself, as
2452Google Mock already prints it for you.
2453
2454**Notes:**
2455
2456  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.
2457  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.
2458
2459## Writing New Parameterized Matchers Quickly ##
2460
2461Sometimes you'll want to define a matcher that has parameters.  For that you
2462can use the macro:
2463```
2464MATCHER_P(name, param_name, "description string") { statements; }
2465```
2466
2467For example:
2468```
2469MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
2470```
2471will allow you to write:
2472```
2473  EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
2474```
2475which may lead to this message (assuming `n` is 10):
2476```
2477  Value of: Blah("a")
2478  Expected: has absolute value 10
2479    Actual: -9
2480```
2481
2482Note that both the matcher description and its parameter are
2483printed, making the message human-friendly.
2484
2485In the matcher definition body, you can write `foo_type` to
2486reference the type of a parameter named `foo`.  For example, in the
2487body of `MATCHER_P(HasAbsoluteValue, value)` above, you can write
2488`value_type` to refer to the type of `value`.
2489
2490Google Mock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to
2491`MATCHER_P10` to support multi-parameter matchers:
2492```
2493MATCHER_Pk(name, param_1, ..., param_k, "description string") { statements; }
2494```
2495
2496Please note that the custom description string is for a particular
2497**instance** of the matcher, where the parameters have been bound to
2498actual values.  Therefore usually you'll want the parameter values to
2499be part of the description.  Google Mock lets you do that using
2500Python-style interpolations.  The following syntaxes are supported
2501currently:
2502
2503| `%%` | a single `%` character |
2504|:-----|:-----------------------|
2505| `%(*)s` | all parameters of the matcher printed as a tuple |
2506| `%(foo)s` | value of the matcher parameter named `foo` |
2507
2508For example,
2509```
2510  MATCHER_P2(InClosedRange, low, hi, "is in range [%(low)s, %(hi)s]") {
2511    return low <= arg && arg <= hi;
2512  }
2513  ...
2514  EXPECT_THAT(3, InClosedRange(4, 6));
2515```
2516would generate a failure that contains the message:
2517```
2518  Expected: is in range [4, 6]
2519```
2520
2521If you specify `""` as the description, the failure message will
2522contain the sequence of words in the matcher name followed by the
2523parameter values printed as a tuple.  For example,
2524```
2525  MATCHER_P2(InClosedRange, low, hi, "") { ... }
2526  ...
2527  EXPECT_THAT(3, InClosedRange(4, 6));
2528```
2529would generate a failure that contains the text:
2530```
2531  Expected: in closed range (4, 6)
2532```
2533
2534For the purpose of typing, you can view
2535```
2536MATCHER_Pk(Foo, p1, ..., pk, "description string") { ... }
2537```
2538as shorthand for
2539```
2540template <typename p1_type, ..., typename pk_type>
2541FooMatcherPk<p1_type, ..., pk_type>
2542Foo(p1_type p1, ..., pk_type pk) { ... }
2543```
2544
2545When you write `Foo(v1, ..., vk)`, the compiler infers the types of
2546the parameters `v1`, ..., and `vk` for you.  If you are not happy with
2547the result of the type inference, you can specify the types by
2548explicitly instantiating the template, as in `Foo<long, bool>(5, false)`.
2549As said earlier, you don't get to (or need to) specify
2550`arg_type` as that's determined by the context in which the matcher
2551is used.
2552
2553You can assign the result of expression `Foo(p1, ..., pk)` to a
2554variable of type `FooMatcherPk<p1_type, ..., pk_type>`.  This can be
2555useful when composing matchers.  Matchers that don't have a parameter
2556or have only one parameter have special types: you can assign `Foo()`
2557to a `FooMatcher`-typed variable, and assign `Foo(p)` to a
2558`FooMatcherP<p_type>`-typed variable.
2559
2560While you can instantiate a matcher template with reference types,
2561passing the parameters by pointer usually makes your code more
2562readable.  If, however, you still want to pass a parameter by
2563reference, be aware that in the failure message generated by the
2564matcher you will see the value of the referenced object but not its
2565address.
2566
2567You can overload matchers with different numbers of parameters:
2568```
2569MATCHER_P(Blah, a, "description string 1") { ... }
2570MATCHER_P2(Blah, a, b, "description string 2") { ... }
2571```
2572
2573While it's tempting to always use the `MATCHER*` macros when defining
2574a new matcher, you should also consider implementing
2575`MatcherInterface` or using `MakePolymorphicMatcher()` instead (see
2576the recipes that follow), especially if you need to use the matcher a
2577lot.  While these approaches require more work, they give you more
2578control on the types of the value being matched and the matcher
2579parameters, which in general leads to better compiler error messages
2580that pay off in the long run.  They also allow overloading matchers
2581based on parameter types (as opposed to just based on the number of
2582parameters).
2583
2584## Writing New Monomorphic Matchers ##
2585
2586A matcher of argument type `T` implements
2587`::testing::MatcherInterface<T>` and does two things: it tests whether a
2588value of type `T` matches the matcher, and can describe what kind of
2589values it matches. The latter ability is used for generating readable
2590error messages when expectations are violated.
2591
2592The interface looks like this:
2593
2594```
2595class MatchResultListener {
2596 public:
2597  ...
2598  // Streams x to the underlying ostream; does nothing if the ostream
2599  // is NULL.
2600  template <typename T>
2601  MatchResultListener& operator<<(const T& x);
2602
2603  // Returns the underlying ostream.
2604  ::std::ostream* stream();
2605};
2606
2607template <typename T>
2608class MatcherInterface {
2609 public:
2610  virtual ~MatcherInterface();
2611
2612  // Returns true iff the matcher matches x; also explains the match
2613  // result to 'listener'.
2614  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
2615
2616  // Describes this matcher to an ostream.
2617  virtual void DescribeTo(::std::ostream* os) const = 0;
2618
2619  // Describes the negation of this matcher to an ostream.
2620  virtual void DescribeNegationTo(::std::ostream* os) const;
2621};
2622```
2623
2624If you need a custom matcher but `Truly()` is not a good option (for
2625example, you may not be happy with the way `Truly(predicate)`
2626describes itself, or you may want your matcher to be polymorphic as
2627`Eq(value)` is), you can define a matcher to do whatever you want in
2628two steps: first implement the matcher interface, and then define a
2629factory function to create a matcher instance. The second step is not
2630strictly needed but it makes the syntax of using the matcher nicer.
2631
2632For example, you can define a matcher to test whether an `int` is
2633divisible by 7 and then use it like this:
2634```
2635using ::testing::MakeMatcher;
2636using ::testing::Matcher;
2637using ::testing::MatcherInterface;
2638using ::testing::MatchResultListener;
2639
2640class DivisibleBy7Matcher : public MatcherInterface<int> {
2641 public:
2642  virtual bool MatchAndExplain(int n, MatchResultListener* listener) const {
2643    return (n % 7) == 0;
2644  }
2645
2646  virtual void DescribeTo(::std::ostream* os) const {
2647    *os << "is divisible by 7";
2648  }
2649
2650  virtual void DescribeNegationTo(::std::ostream* os) const {
2651    *os << "is not divisible by 7";
2652  }
2653};
2654
2655inline Matcher<int> DivisibleBy7() {
2656  return MakeMatcher(new DivisibleBy7Matcher);
2657}
2658...
2659
2660  EXPECT_CALL(foo, Bar(DivisibleBy7()));
2661```
2662
2663You may improve the matcher message by streaming additional
2664information to the `listener` argument in `MatchAndExplain()`:
2665
2666```
2667class DivisibleBy7Matcher : public MatcherInterface<int> {
2668 public:
2669  virtual bool MatchAndExplain(int n,
2670                               MatchResultListener* listener) const {
2671    const int remainder = n % 7;
2672    if (remainder != 0) {
2673      *listener << "the remainder is " << remainder;
2674    }
2675    return remainder == 0;
2676  }
2677  ...
2678};
2679```
2680
2681Then, `EXPECT_THAT(x, DivisibleBy7());` may general a message like this:
2682```
2683Value of: x
2684Expected: is divisible by 7
2685  Actual: 23 (the remainder is 2)
2686```
2687
2688## Writing New Polymorphic Matchers ##
2689
2690You've learned how to write your own matchers in the previous
2691recipe. Just one problem: a matcher created using `MakeMatcher()` only
2692works for one particular type of arguments. If you want a
2693_polymorphic_ matcher that works with arguments of several types (for
2694instance, `Eq(x)` can be used to match a `value` as long as `value` ==
2695`x` compiles -- `value` and `x` don't have to share the same type),
2696you can learn the trick from `<gmock/gmock-matchers.h>` but it's a bit
2697involved.
2698
2699Fortunately, most of the time you can define a polymorphic matcher
2700easily with the help of `MakePolymorphicMatcher()`. Here's how you can
2701define `NotNull()` as an example:
2702
2703```
2704using ::testing::MakePolymorphicMatcher;
2705using ::testing::MatchResultListener;
2706using ::testing::NotNull;
2707using ::testing::PolymorphicMatcher;
2708
2709class NotNullMatcher {
2710 public:
2711  // To implement a polymorphic matcher, first define a COPYABLE class
2712  // that has three members MatchAndExplain(), DescribeTo(), and
2713  // DescribeNegationTo(), like the following.
2714
2715  // In this example, we want to use NotNull() with any pointer, so
2716  // MatchAndExplain() accepts a pointer of any type as its first argument.
2717  // In general, you can define MatchAndExplain() as an ordinary method or
2718  // a method template, or even overload it.
2719  template <typename T>
2720  bool MatchAndExplain(T* p,
2721                       MatchResultListener* /* listener */) const {
2722    return p != NULL;
2723  }
2724
2725  // Describes the property of a value matching this matcher.
2726  void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
2727
2728  // Describes the property of a value NOT matching this matcher.
2729  void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
2730};
2731
2732// To construct a polymorphic matcher, pass an instance of the class
2733// to MakePolymorphicMatcher().  Note the return type.
2734inline PolymorphicMatcher<NotNullMatcher> NotNull() {
2735  return MakePolymorphicMatcher(NotNullMatcher());
2736}
2737...
2738
2739  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.
2740```
2741
2742**Note:** Your polymorphic matcher class does **not** need to inherit from
2743`MatcherInterface` or any other class, and its methods do **not** need
2744to be virtual.
2745
2746Like in a monomorphic matcher, you may explain the match result by
2747streaming additional information to the `listener` argument in
2748`MatchAndExplain()`.
2749
2750## Writing New Cardinalities ##
2751
2752A cardinality is used in `Times()` to tell Google Mock how many times
2753you expect a call to occur. It doesn't have to be exact. For example,
2754you can say `AtLeast(5)` or `Between(2, 4)`.
2755
2756If the built-in set of cardinalities doesn't suit you, you are free to
2757define your own by implementing the following interface (in namespace
2758`testing`):
2759
2760```
2761class CardinalityInterface {
2762 public:
2763  virtual ~CardinalityInterface();
2764
2765  // Returns true iff call_count calls will satisfy this cardinality.
2766  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
2767
2768  // Returns true iff call_count calls will saturate this cardinality.
2769  virtual bool IsSaturatedByCallCount(int call_count) const = 0;
2770
2771  // Describes self to an ostream.
2772  virtual void DescribeTo(::std::ostream* os) const = 0;
2773};
2774```
2775
2776For example, to specify that a call must occur even number of times,
2777you can write
2778
2779```
2780using ::testing::Cardinality;
2781using ::testing::CardinalityInterface;
2782using ::testing::MakeCardinality;
2783
2784class EvenNumberCardinality : public CardinalityInterface {
2785 public:
2786  virtual bool IsSatisfiedByCallCount(int call_count) const {
2787    return (call_count % 2) == 0;
2788  }
2789
2790  virtual bool IsSaturatedByCallCount(int call_count) const {
2791    return false;
2792  }
2793
2794  virtual void DescribeTo(::std::ostream* os) const {
2795    *os << "called even number of times";
2796  }
2797};
2798
2799Cardinality EvenNumber() {
2800  return MakeCardinality(new EvenNumberCardinality);
2801}
2802...
2803
2804  EXPECT_CALL(foo, Bar(3))
2805      .Times(EvenNumber());
2806```
2807
2808## Writing New Actions Quickly ##
2809
2810If the built-in actions don't work for you, and you find it
2811inconvenient to use `Invoke()`, you can use a macro from the `ACTION*`
2812family to quickly define a new action that can be used in your code as
2813if it's a built-in action.
2814
2815By writing
2816```
2817ACTION(name) { statements; }
2818```
2819in a namespace scope (i.e. not inside a class or function), you will
2820define an action with the given name that executes the statements.
2821The value returned by `statements` will be used as the return value of
2822the action.  Inside the statements, you can refer to the K-th
2823(0-based) argument of the mock function as `argK`.  For example:
2824```
2825ACTION(IncrementArg1) { return ++(*arg1); }
2826```
2827allows you to write
2828```
2829... WillOnce(IncrementArg1());
2830```
2831
2832Note that you don't need to specify the types of the mock function
2833arguments.  Rest assured that your code is type-safe though:
2834you'll get a compiler error if `*arg1` doesn't support the `++`
2835operator, or if the type of `++(*arg1)` isn't compatible with the mock
2836function's return type.
2837
2838Another example:
2839```
2840ACTION(Foo) {
2841  (*arg2)(5);
2842  Blah();
2843  *arg1 = 0;
2844  return arg0;
2845}
2846```
2847defines an action `Foo()` that invokes argument #2 (a function pointer)
2848with 5, calls function `Blah()`, sets the value pointed to by argument
2849#1 to 0, and returns argument #0.
2850
2851For more convenience and flexibility, you can also use the following
2852pre-defined symbols in the body of `ACTION`:
2853
2854| `argK_type` | The type of the K-th (0-based) argument of the mock function |
2855|:------------|:-------------------------------------------------------------|
2856| `args`      | All arguments of the mock function as a tuple                |
2857| `args_type` | The type of all arguments of the mock function as a tuple    |
2858| `return_type` | The return type of the mock function                         |
2859| `function_type` | The type of the mock function                                |
2860
2861For example, when using an `ACTION` as a stub action for mock function:
2862```
2863int DoSomething(bool flag, int* ptr);
2864```
2865we have:
2866| **Pre-defined Symbol** | **Is Bound To** |
2867|:-----------------------|:----------------|
2868| `arg0`                 | the value of `flag` |
2869| `arg0_type`            | the type `bool` |
2870| `arg1`                 | the value of `ptr` |
2871| `arg1_type`            | the type `int*` |
2872| `args`                 | the tuple `(flag, ptr)` |
2873| `args_type`            | the type `std::tr1::tuple<bool, int*>` |
2874| `return_type`          | the type `int`  |
2875| `function_type`        | the type `int(bool, int*)` |
2876
2877## Writing New Parameterized Actions Quickly ##
2878
2879Sometimes you'll want to parameterize an action you define.  For that
2880we have another macro
2881```
2882ACTION_P(name, param) { statements; }
2883```
2884
2885For example,
2886```
2887ACTION_P(Add, n) { return arg0 + n; }
2888```
2889will allow you to write
2890```
2891// Returns argument #0 + 5.
2892... WillOnce(Add(5));
2893```
2894
2895For convenience, we use the term _arguments_ for the values used to
2896invoke the mock function, and the term _parameters_ for the values
2897used to instantiate an action.
2898
2899Note that you don't need to provide the type of the parameter either.
2900Suppose the parameter is named `param`, you can also use the
2901Google-Mock-defined symbol `param_type` to refer to the type of the
2902parameter as inferred by the compiler.  For example, in the body of
2903`ACTION_P(Add, n)` above, you can write `n_type` for the type of `n`.
2904
2905Google Mock also provides `ACTION_P2`, `ACTION_P3`, and etc to support
2906multi-parameter actions.  For example,
2907```
2908ACTION_P2(ReturnDistanceTo, x, y) {
2909  double dx = arg0 - x;
2910  double dy = arg1 - y;
2911  return sqrt(dx*dx + dy*dy);
2912}
2913```
2914lets you write
2915```
2916... WillOnce(ReturnDistanceTo(5.0, 26.5));
2917```
2918
2919You can view `ACTION` as a degenerated parameterized action where the
2920number of parameters is 0.
2921
2922You can also easily define actions overloaded on the number of parameters:
2923```
2924ACTION_P(Plus, a) { ... }
2925ACTION_P2(Plus, a, b) { ... }
2926```
2927
2928## Restricting the Type of an Argument or Parameter in an ACTION ##
2929
2930For maximum brevity and reusability, the `ACTION*` macros don't ask
2931you to provide the types of the mock function arguments and the action
2932parameters.  Instead, we let the compiler infer the types for us.
2933
2934Sometimes, however, we may want to be more explicit about the types.
2935There are several tricks to do that.  For example:
2936```
2937ACTION(Foo) {
2938  // Makes sure arg0 can be converted to int.
2939  int n = arg0;
2940  ... use n instead of arg0 here ...
2941}
2942
2943ACTION_P(Bar, param) {
2944  // Makes sure the type of arg1 is const char*.
2945  ::testing::StaticAssertTypeEq<const char*, arg1_type>();
2946
2947  // Makes sure param can be converted to bool.
2948  bool flag = param;
2949}
2950```
2951where `StaticAssertTypeEq` is a compile-time assertion in Google Test
2952that verifies two types are the same.
2953
2954## Writing New Action Templates Quickly ##
2955
2956Sometimes you want to give an action explicit template parameters that
2957cannot be inferred from its value parameters.  `ACTION_TEMPLATE()`
2958supports that and can be viewed as an extension to `ACTION()` and
2959`ACTION_P*()`.
2960
2961The syntax:
2962```
2963ACTION_TEMPLATE(ActionName,
2964                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
2965                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
2966```
2967
2968defines an action template that takes _m_ explicit template parameters
2969and _n_ value parameters, where _m_ is between 1 and 10, and _n_ is
2970between 0 and 10.  `name_i` is the name of the i-th template
2971parameter, and `kind_i` specifies whether it's a `typename`, an
2972integral constant, or a template.  `p_i` is the name of the i-th value
2973parameter.
2974
2975Example:
2976```
2977// DuplicateArg<k, T>(output) converts the k-th argument of the mock
2978// function to type T and copies it to *output.
2979ACTION_TEMPLATE(DuplicateArg,
2980                // Note the comma between int and k:
2981                HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
2982                AND_1_VALUE_PARAMS(output)) {
2983  *output = T(std::tr1::get<k>(args));
2984}
2985```
2986
2987To create an instance of an action template, write:
2988```
2989  ActionName<t1, ..., t_m>(v1, ..., v_n)
2990```
2991where the `t`s are the template arguments and the
2992`v`s are the value arguments.  The value argument
2993types are inferred by the compiler.  For example:
2994```
2995using ::testing::_;
2996...
2997  int n;
2998  EXPECT_CALL(mock, Foo(_, _))
2999      .WillOnce(DuplicateArg<1, unsigned char>(&n));
3000```
3001
3002If you want to explicitly specify the value argument types, you can
3003provide additional template arguments:
3004```
3005  ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
3006```
3007where `u_i` is the desired type of `v_i`.
3008
3009`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the
3010number of value parameters, but not on the number of template
3011parameters.  Without the restriction, the meaning of the following is
3012unclear:
3013
3014```
3015  OverloadedAction<int, bool>(x);
3016```
3017
3018Are we using a single-template-parameter action where `bool` refers to
3019the type of `x`, or a two-template-parameter action where the compiler
3020is asked to infer the type of `x`?
3021
3022## Using the ACTION Object's Type ##
3023
3024If you are writing a function that returns an `ACTION` object, you'll
3025need to know its type.  The type depends on the macro used to define
3026the action and the parameter types.  The rule is relatively simple:
3027| **Given Definition** | **Expression** | **Has Type** |
3028|:---------------------|:---------------|:-------------|
3029| `ACTION(Foo)`        | `Foo()`        | `FooAction`  |
3030| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` |	`Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |
3031| `ACTION_P(Bar, param)` | `Bar(int_value)` | `BarActionP<int>` |
3032| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `FooActionP<t1, ..., t_m, int>` |
3033| `ACTION_P2(Baz, p1, p2)` | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |
3034| `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>` |
3035| ...                  | ...            | ...          |
3036
3037Note that we have to pick different suffixes (`Action`, `ActionP`,
3038`ActionP2`, and etc) for actions with different numbers of value
3039parameters, or the action definitions cannot be overloaded on the
3040number of them.
3041
3042## Writing New Monomorphic Actions ##
3043
3044While the `ACTION*` macros are very convenient, sometimes they are
3045inappropriate.  For example, despite the tricks shown in the previous
3046recipes, they don't let you directly specify the types of the mock
3047function arguments and the action parameters, which in general leads
3048to unoptimized compiler error messages that can baffle unfamiliar
3049users.  They also don't allow overloading actions based on parameter
3050types without jumping through some hoops.
3051
3052An alternative to the `ACTION*` macros is to implement
3053`::testing::ActionInterface<F>`, where `F` is the type of the mock
3054function in which the action will be used. For example:
3055
3056```
3057template <typename F>class ActionInterface {
3058 public:
3059  virtual ~ActionInterface();
3060
3061  // Performs the action.  Result is the return type of function type
3062  // F, and ArgumentTuple is the tuple of arguments of F.
3063  //
3064  // For example, if F is int(bool, const string&), then Result would
3065  // be int, and ArgumentTuple would be tr1::tuple<bool, const string&>.
3066  virtual Result Perform(const ArgumentTuple& args) = 0;
3067};
3068
3069using ::testing::_;
3070using ::testing::Action;
3071using ::testing::ActionInterface;
3072using ::testing::MakeAction;
3073
3074typedef int IncrementMethod(int*);
3075
3076class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
3077 public:
3078  virtual int Perform(const tr1::tuple<int*>& args) {
3079    int* p = tr1::get<0>(args);  // Grabs the first argument.
3080    return *p++;
3081  }
3082};
3083
3084Action<IncrementMethod> IncrementArgument() {
3085  return MakeAction(new IncrementArgumentAction);
3086}
3087...
3088
3089  EXPECT_CALL(foo, Baz(_))
3090      .WillOnce(IncrementArgument());
3091
3092  int n = 5;
3093  foo.Baz(&n);  // Should return 5 and change n to 6.
3094```
3095
3096## Writing New Polymorphic Actions ##
3097
3098The previous recipe showed you how to define your own action. This is
3099all good, except that you need to know the type of the function in
3100which the action will be used. Sometimes that can be a problem. For
3101example, if you want to use the action in functions with _different_
3102types (e.g. like `Return()` and `SetArgumentPointee()`).
3103
3104If an action can be used in several types of mock functions, we say
3105it's _polymorphic_. The `MakePolymorphicAction()` function template
3106makes it easy to define such an action:
3107
3108```
3109namespace testing {
3110
3111template <typename Impl>
3112PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);
3113
3114}  // namespace testing
3115```
3116
3117As an example, let's define an action that returns the second argument
3118in the mock function's argument list. The first step is to define an
3119implementation class:
3120
3121```
3122class ReturnSecondArgumentAction {
3123 public:
3124  template <typename Result, typename ArgumentTuple>
3125  Result Perform(const ArgumentTuple& args) const {
3126    // To get the i-th (0-based) argument, use tr1::get<i>(args).
3127    return tr1::get<1>(args);
3128  }
3129};
3130```
3131
3132This implementation class does _not_ need to inherit from any
3133particular class. What matters is that it must have a `Perform()`
3134method template. This method template takes the mock function's
3135arguments as a tuple in a **single** argument, and returns the result of
3136the action. It can be either `const` or not, but must be invokable
3137with exactly one template argument, which is the result type. In other
3138words, you must be able to call `Perform<R>(args)` where `R` is the
3139mock function's return type and `args` is its arguments in a tuple.
3140
3141Next, we use `MakePolymorphicAction()` to turn an instance of the
3142implementation class into the polymorphic action we need. It will be
3143convenient to have a wrapper for this:
3144
3145```
3146using ::testing::MakePolymorphicAction;
3147using ::testing::PolymorphicAction;
3148
3149PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
3150  return MakePolymorphicAction(ReturnSecondArgumentAction());
3151}
3152```
3153
3154Now, you can use this polymorphic action the same way you use the
3155built-in ones:
3156
3157```
3158using ::testing::_;
3159
3160class MockFoo : public Foo {
3161 public:
3162  MOCK_METHOD2(DoThis, int(bool flag, int n));
3163  MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2));
3164};
3165...
3166
3167  MockFoo foo;
3168  EXPECT_CALL(foo, DoThis(_, _))
3169      .WillOnce(ReturnSecondArgument());
3170  EXPECT_CALL(foo, DoThat(_, _, _))
3171      .WillOnce(ReturnSecondArgument());
3172  ...
3173  foo.DoThis(true, 5);         // Will return 5.
3174  foo.DoThat(1, "Hi", "Bye");  // Will return "Hi".
3175```
3176
3177## Teaching Google Mock How to Print Your Values ##
3178
3179When an uninteresting or unexpected call occurs, Google Mock prints
3180the argument values to help you debug.  The `EXPECT_THAT` and
3181`ASSERT_THAT` assertions also print the value being validated when the
3182test fails.  Google Mock does this using the user-extensible value
3183printer defined in `<gmock/gmock-printers.h>`.
3184
3185This printer knows how to print the built-in C++ types, native arrays,
3186STL containers, and any type that supports the `<<` operator. For
3187other types, it prints the raw bytes in the value and hope you the
3188user can figure it out.
3189
3190Did I say that the printer is `extensible`? That means you can teach
3191it to do a better job at printing your particular type than to dump
3192the bytes. To do that, you just need to define `<<` for your type:
3193
3194```
3195#include <iostream>
3196
3197namespace foo {
3198
3199class Foo { ... };
3200
3201// It's important that the << operator is defined in the SAME
3202// namespace that defines Foo.  C++'s look-up rules rely on that.
3203::std::ostream& operator<<(::std::ostream& os, const Foo& foo) {
3204  return os << foo.DebugString();  // Whatever needed to print foo to os.
3205}
3206
3207}  // namespace foo
3208```
3209
3210Sometimes, this might not be an option. For example, your team may
3211consider it dangerous or bad style to have a `<<` operator for `Foo`,
3212or `Foo` may already have a `<<` operator that doesn't do what you
3213want (and you cannot change it). Don't despair though - Google Mock
3214gives you a second chance to get it right. Namely, you can define a
3215`PrintTo()` function like this:
3216
3217```
3218#include <iostream>
3219
3220namespace foo {
3221
3222class Foo { ... };
3223
3224// It's important that PrintTo() is defined in the SAME
3225// namespace that defines Foo.  C++'s look-up rules rely on that.
3226void PrintTo(const Foo& foo, ::std::ostream* os) {
3227  *os << foo.DebugString();  // Whatever needed to print foo to os.
3228}
3229
3230}  // namespace foo
3231```
3232
3233What if you have both `<<` and `PrintTo()`? In this case, the latter
3234will override the former when Google Mock is concerned. This allows
3235you to customize how the value should appear in Google Mock's output
3236without affecting code that relies on the behavior of its `<<`
3237operator.
3238
3239**Note:** When printing a pointer of type `T*`, Google Mock calls
3240`PrintTo(T*, std::ostream* os)` instead of `operator<<(std::ostream&, T*)`.
3241Therefore the only way to affect how a pointer is printed by Google
3242Mock is to define `PrintTo()` for it. Also note that `T*` and `const T*`
3243are different types, so you may need to define `PrintTo()` for both.
3244
3245Why does Google Mock treat pointers specially? There are several reasons:
3246
3247  * We cannot use `operator<<` to print a `signed char*` or `unsigned char*`, since it will print the pointer as a NUL-terminated C string, which likely will cause an access violation.
3248  * We want `NULL` pointers to be printed as `"NULL"`, but `operator<<` prints it as `"0"`, `"nullptr"`, or something else, depending on the compiler.
3249  * With some compilers, printing a `NULL` `char*` using `operator<<` will segfault.
3250  * `operator<<` prints a function pointer as a `bool` (hence it always prints `"1"`), which is not very useful.