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