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