1 // Copyright 2007, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 // 30 // Author: wan (at) google.com (Zhanyong Wan) 31 32 // Google Mock - a framework for writing C++ mock classes. 33 // 34 // This file implements the ON_CALL() and EXPECT_CALL() macros. 35 // 36 // A user can use the ON_CALL() macro to specify the default action of 37 // a mock method. The syntax is: 38 // 39 // ON_CALL(mock_object, Method(argument-matchers)) 40 // .With(multi-argument-matcher) 41 // .WillByDefault(action); 42 // 43 // where the .With() clause is optional. 44 // 45 // A user can use the EXPECT_CALL() macro to specify an expectation on 46 // a mock method. The syntax is: 47 // 48 // EXPECT_CALL(mock_object, Method(argument-matchers)) 49 // .With(multi-argument-matchers) 50 // .Times(cardinality) 51 // .InSequence(sequences) 52 // .After(expectations) 53 // .WillOnce(action) 54 // .WillRepeatedly(action) 55 // .RetiresOnSaturation(); 56 // 57 // where all clauses are optional, and .InSequence()/.After()/ 58 // .WillOnce() can appear any number of times. 59 60 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ 61 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ 62 63 #include <map> 64 #include <set> 65 #include <sstream> 66 #include <string> 67 #include <vector> 68 69 #if GTEST_HAS_EXCEPTIONS 70 # include <stdexcept> // NOLINT 71 #endif 72 73 #include "gmock/gmock-actions.h" 74 #include "gmock/gmock-cardinalities.h" 75 #include "gmock/gmock-matchers.h" 76 #include "gmock/internal/gmock-internal-utils.h" 77 #include "gmock/internal/gmock-port.h" 78 #include "gtest/gtest.h" 79 80 namespace testing { 81 82 // An abstract handle of an expectation. 83 class Expectation; 84 85 // A set of expectation handles. 86 class ExpectationSet; 87 88 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION 89 // and MUST NOT BE USED IN USER CODE!!! 90 namespace internal { 91 92 // Implements a mock function. 93 template <typename F> class FunctionMocker; 94 95 // Base class for expectations. 96 class ExpectationBase; 97 98 // Implements an expectation. 99 template <typename F> class TypedExpectation; 100 101 // Helper class for testing the Expectation class template. 102 class ExpectationTester; 103 104 // Base class for function mockers. 105 template <typename F> class FunctionMockerBase; 106 107 // Protects the mock object registry (in class Mock), all function 108 // mockers, and all expectations. 109 // 110 // The reason we don't use more fine-grained protection is: when a 111 // mock function Foo() is called, it needs to consult its expectations 112 // to see which one should be picked. If another thread is allowed to 113 // call a mock function (either Foo() or a different one) at the same 114 // time, it could affect the "retired" attributes of Foo()'s 115 // expectations when InSequence() is used, and thus affect which 116 // expectation gets picked. Therefore, we sequence all mock function 117 // calls to ensure the integrity of the mock objects' states. 118 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex); 119 120 // Untyped base class for ActionResultHolder<R>. 121 class UntypedActionResultHolderBase; 122 123 // Abstract base class of FunctionMockerBase. This is the 124 // type-agnostic part of the function mocker interface. Its pure 125 // virtual methods are implemented by FunctionMockerBase. 126 class GTEST_API_ UntypedFunctionMockerBase { 127 public: 128 UntypedFunctionMockerBase(); 129 virtual ~UntypedFunctionMockerBase(); 130 131 // Verifies that all expectations on this mock function have been 132 // satisfied. Reports one or more Google Test non-fatal failures 133 // and returns false if not. 134 bool VerifyAndClearExpectationsLocked() 135 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); 136 137 // Clears the ON_CALL()s set on this mock function. 138 virtual void ClearDefaultActionsLocked() 139 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0; 140 141 // In all of the following Untyped* functions, it's the caller's 142 // responsibility to guarantee the correctness of the arguments' 143 // types. 144 145 // Performs the default action with the given arguments and returns 146 // the action's result. The call description string will be used in 147 // the error message to describe the call in the case the default 148 // action fails. 149 // L = * 150 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( 151 const void* untyped_args, const std::string& call_description) const = 0; 152 153 // Performs the given action with the given arguments and returns 154 // the action's result. 155 // L = * 156 virtual UntypedActionResultHolderBase* UntypedPerformAction( 157 const void* untyped_action, 158 const void* untyped_args) const = 0; 159 160 // Writes a message that the call is uninteresting (i.e. neither 161 // explicitly expected nor explicitly unexpected) to the given 162 // ostream. 163 virtual void UntypedDescribeUninterestingCall( 164 const void* untyped_args, 165 ::std::ostream* os) const 166 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; 167 168 // Returns the expectation that matches the given function arguments 169 // (or NULL is there's no match); when a match is found, 170 // untyped_action is set to point to the action that should be 171 // performed (or NULL if the action is "do default"), and 172 // is_excessive is modified to indicate whether the call exceeds the 173 // expected number. 174 virtual const ExpectationBase* UntypedFindMatchingExpectation( 175 const void* untyped_args, 176 const void** untyped_action, bool* is_excessive, 177 ::std::ostream* what, ::std::ostream* why) 178 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; 179 180 // Prints the given function arguments to the ostream. 181 virtual void UntypedPrintArgs(const void* untyped_args, 182 ::std::ostream* os) const = 0; 183 184 // Sets the mock object this mock method belongs to, and registers 185 // this information in the global mock registry. Will be called 186 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock 187 // method. 188 // TODO(wan (at) google.com): rename to SetAndRegisterOwner(). 189 void RegisterOwner(const void* mock_obj) 190 GTEST_LOCK_EXCLUDED_(g_gmock_mutex); 191 192 // Sets the mock object this mock method belongs to, and sets the 193 // name of the mock function. Will be called upon each invocation 194 // of this mock function. 195 void SetOwnerAndName(const void* mock_obj, const char* name) 196 GTEST_LOCK_EXCLUDED_(g_gmock_mutex); 197 198 // Returns the mock object this mock method belongs to. Must be 199 // called after RegisterOwner() or SetOwnerAndName() has been 200 // called. 201 const void* MockObject() const 202 GTEST_LOCK_EXCLUDED_(g_gmock_mutex); 203 204 // Returns the name of this mock method. Must be called after 205 // SetOwnerAndName() has been called. 206 const char* Name() const 207 GTEST_LOCK_EXCLUDED_(g_gmock_mutex); 208 209 // Returns the result of invoking this mock function with the given 210 // arguments. This function can be safely called from multiple 211 // threads concurrently. The caller is responsible for deleting the 212 // result. 213 UntypedActionResultHolderBase* UntypedInvokeWith( 214 const void* untyped_args) 215 GTEST_LOCK_EXCLUDED_(g_gmock_mutex); 216 217 protected: 218 typedef std::vector<const void*> UntypedOnCallSpecs; 219 220 typedef std::vector<internal::linked_ptr<ExpectationBase> > 221 UntypedExpectations; 222 223 // Returns an Expectation object that references and co-owns exp, 224 // which must be an expectation on this mock function. 225 Expectation GetHandleOf(ExpectationBase* exp); 226 227 // Address of the mock object this mock method belongs to. Only 228 // valid after this mock method has been called or 229 // ON_CALL/EXPECT_CALL has been invoked on it. 230 const void* mock_obj_; // Protected by g_gmock_mutex. 231 232 // Name of the function being mocked. Only valid after this mock 233 // method has been called. 234 const char* name_; // Protected by g_gmock_mutex. 235 236 // All default action specs for this function mocker. 237 UntypedOnCallSpecs untyped_on_call_specs_; 238 239 // All expectations for this function mocker. 240 UntypedExpectations untyped_expectations_; 241 }; // class UntypedFunctionMockerBase 242 243 // Untyped base class for OnCallSpec<F>. 244 class UntypedOnCallSpecBase { 245 public: 246 // The arguments are the location of the ON_CALL() statement. 247 UntypedOnCallSpecBase(const char* a_file, int a_line) 248 : file_(a_file), line_(a_line), last_clause_(kNone) {} 249 250 // Where in the source file was the default action spec defined? 251 const char* file() const { return file_; } 252 int line() const { return line_; } 253 254 protected: 255 // Gives each clause in the ON_CALL() statement a name. 256 enum Clause { 257 // Do not change the order of the enum members! The run-time 258 // syntax checking relies on it. 259 kNone, 260 kWith, 261 kWillByDefault 262 }; 263 264 // Asserts that the ON_CALL() statement has a certain property. 265 void AssertSpecProperty(bool property, 266 const std::string& failure_message) const { 267 Assert(property, file_, line_, failure_message); 268 } 269 270 // Expects that the ON_CALL() statement has a certain property. 271 void ExpectSpecProperty(bool property, 272 const std::string& failure_message) const { 273 Expect(property, file_, line_, failure_message); 274 } 275 276 const char* file_; 277 int line_; 278 279 // The last clause in the ON_CALL() statement as seen so far. 280 // Initially kNone and changes as the statement is parsed. 281 Clause last_clause_; 282 }; // class UntypedOnCallSpecBase 283 284 // This template class implements an ON_CALL spec. 285 template <typename F> 286 class OnCallSpec : public UntypedOnCallSpecBase { 287 public: 288 typedef typename Function<F>::ArgumentTuple ArgumentTuple; 289 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; 290 291 // Constructs an OnCallSpec object from the information inside 292 // the parenthesis of an ON_CALL() statement. 293 OnCallSpec(const char* a_file, int a_line, 294 const ArgumentMatcherTuple& matchers) 295 : UntypedOnCallSpecBase(a_file, a_line), 296 matchers_(matchers), 297 // By default, extra_matcher_ should match anything. However, 298 // we cannot initialize it with _ as that triggers a compiler 299 // bug in Symbian's C++ compiler (cannot decide between two 300 // overloaded constructors of Matcher<const ArgumentTuple&>). 301 extra_matcher_(A<const ArgumentTuple&>()) { 302 } 303 304 // Implements the .With() clause. 305 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) { 306 // Makes sure this is called at most once. 307 ExpectSpecProperty(last_clause_ < kWith, 308 ".With() cannot appear " 309 "more than once in an ON_CALL()."); 310 last_clause_ = kWith; 311 312 extra_matcher_ = m; 313 return *this; 314 } 315 316 // Implements the .WillByDefault() clause. 317 OnCallSpec& WillByDefault(const Action<F>& action) { 318 ExpectSpecProperty(last_clause_ < kWillByDefault, 319 ".WillByDefault() must appear " 320 "exactly once in an ON_CALL()."); 321 last_clause_ = kWillByDefault; 322 323 ExpectSpecProperty(!action.IsDoDefault(), 324 "DoDefault() cannot be used in ON_CALL()."); 325 action_ = action; 326 return *this; 327 } 328 329 // Returns true iff the given arguments match the matchers. 330 bool Matches(const ArgumentTuple& args) const { 331 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); 332 } 333 334 // Returns the action specified by the user. 335 const Action<F>& GetAction() const { 336 AssertSpecProperty(last_clause_ == kWillByDefault, 337 ".WillByDefault() must appear exactly " 338 "once in an ON_CALL()."); 339 return action_; 340 } 341 342 private: 343 // The information in statement 344 // 345 // ON_CALL(mock_object, Method(matchers)) 346 // .With(multi-argument-matcher) 347 // .WillByDefault(action); 348 // 349 // is recorded in the data members like this: 350 // 351 // source file that contains the statement => file_ 352 // line number of the statement => line_ 353 // matchers => matchers_ 354 // multi-argument-matcher => extra_matcher_ 355 // action => action_ 356 ArgumentMatcherTuple matchers_; 357 Matcher<const ArgumentTuple&> extra_matcher_; 358 Action<F> action_; 359 }; // class OnCallSpec 360 361 // Possible reactions on uninteresting calls. 362 enum CallReaction { 363 kAllow, 364 kWarn, 365 kFail, 366 kDefault = kWarn // By default, warn about uninteresting calls. 367 }; 368 369 } // namespace internal 370 371 // Utilities for manipulating mock objects. 372 class GTEST_API_ Mock { 373 public: 374 // The following public methods can be called concurrently. 375 376 // Tells Google Mock to ignore mock_obj when checking for leaked 377 // mock objects. 378 static void AllowLeak(const void* mock_obj) 379 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 380 381 // Verifies and clears all expectations on the given mock object. 382 // If the expectations aren't satisfied, generates one or more 383 // Google Test non-fatal failures and returns false. 384 static bool VerifyAndClearExpectations(void* mock_obj) 385 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 386 387 // Verifies all expectations on the given mock object and clears its 388 // default actions and expectations. Returns true iff the 389 // verification was successful. 390 static bool VerifyAndClear(void* mock_obj) 391 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 392 393 private: 394 friend class internal::UntypedFunctionMockerBase; 395 396 // Needed for a function mocker to register itself (so that we know 397 // how to clear a mock object). 398 template <typename F> 399 friend class internal::FunctionMockerBase; 400 401 template <typename M> 402 friend class NiceMock; 403 404 template <typename M> 405 friend class NaggyMock; 406 407 template <typename M> 408 friend class StrictMock; 409 410 // Tells Google Mock to allow uninteresting calls on the given mock 411 // object. 412 static void AllowUninterestingCalls(const void* mock_obj) 413 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 414 415 // Tells Google Mock to warn the user about uninteresting calls on 416 // the given mock object. 417 static void WarnUninterestingCalls(const void* mock_obj) 418 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 419 420 // Tells Google Mock to fail uninteresting calls on the given mock 421 // object. 422 static void FailUninterestingCalls(const void* mock_obj) 423 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 424 425 // Tells Google Mock the given mock object is being destroyed and 426 // its entry in the call-reaction table should be removed. 427 static void UnregisterCallReaction(const void* mock_obj) 428 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 429 430 // Returns the reaction Google Mock will have on uninteresting calls 431 // made on the given mock object. 432 static internal::CallReaction GetReactionOnUninterestingCalls( 433 const void* mock_obj) 434 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 435 436 // Verifies that all expectations on the given mock object have been 437 // satisfied. Reports one or more Google Test non-fatal failures 438 // and returns false if not. 439 static bool VerifyAndClearExpectationsLocked(void* mock_obj) 440 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); 441 442 // Clears all ON_CALL()s set on the given mock object. 443 static void ClearDefaultActionsLocked(void* mock_obj) 444 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); 445 446 // Registers a mock object and a mock method it owns. 447 static void Register( 448 const void* mock_obj, 449 internal::UntypedFunctionMockerBase* mocker) 450 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 451 452 // Tells Google Mock where in the source code mock_obj is used in an 453 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this 454 // information helps the user identify which object it is. 455 static void RegisterUseByOnCallOrExpectCall( 456 const void* mock_obj, const char* file, int line) 457 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); 458 459 // Unregisters a mock method; removes the owning mock object from 460 // the registry when the last mock method associated with it has 461 // been unregistered. This is called only in the destructor of 462 // FunctionMockerBase. 463 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) 464 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); 465 }; // class Mock 466 467 // An abstract handle of an expectation. Useful in the .After() 468 // clause of EXPECT_CALL() for setting the (partial) order of 469 // expectations. The syntax: 470 // 471 // Expectation e1 = EXPECT_CALL(...)...; 472 // EXPECT_CALL(...).After(e1)...; 473 // 474 // sets two expectations where the latter can only be matched after 475 // the former has been satisfied. 476 // 477 // Notes: 478 // - This class is copyable and has value semantics. 479 // - Constness is shallow: a const Expectation object itself cannot 480 // be modified, but the mutable methods of the ExpectationBase 481 // object it references can be called via expectation_base(). 482 // - The constructors and destructor are defined out-of-line because 483 // the Symbian WINSCW compiler wants to otherwise instantiate them 484 // when it sees this class definition, at which point it doesn't have 485 // ExpectationBase available yet, leading to incorrect destruction 486 // in the linked_ptr (or compilation errors if using a checking 487 // linked_ptr). 488 class GTEST_API_ Expectation { 489 public: 490 // Constructs a null object that doesn't reference any expectation. 491 Expectation(); 492 493 ~Expectation(); 494 495 // This single-argument ctor must not be explicit, in order to support the 496 // Expectation e = EXPECT_CALL(...); 497 // syntax. 498 // 499 // A TypedExpectation object stores its pre-requisites as 500 // Expectation objects, and needs to call the non-const Retire() 501 // method on the ExpectationBase objects they reference. Therefore 502 // Expectation must receive a *non-const* reference to the 503 // ExpectationBase object. 504 Expectation(internal::ExpectationBase& exp); // NOLINT 505 506 // The compiler-generated copy ctor and operator= work exactly as 507 // intended, so we don't need to define our own. 508 509 // Returns true iff rhs references the same expectation as this object does. 510 bool operator==(const Expectation& rhs) const { 511 return expectation_base_ == rhs.expectation_base_; 512 } 513 514 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); } 515 516 private: 517 friend class ExpectationSet; 518 friend class Sequence; 519 friend class ::testing::internal::ExpectationBase; 520 friend class ::testing::internal::UntypedFunctionMockerBase; 521 522 template <typename F> 523 friend class ::testing::internal::FunctionMockerBase; 524 525 template <typename F> 526 friend class ::testing::internal::TypedExpectation; 527 528 // This comparator is needed for putting Expectation objects into a set. 529 class Less { 530 public: 531 bool operator()(const Expectation& lhs, const Expectation& rhs) const { 532 return lhs.expectation_base_.get() < rhs.expectation_base_.get(); 533 } 534 }; 535 536 typedef ::std::set<Expectation, Less> Set; 537 538 Expectation( 539 const internal::linked_ptr<internal::ExpectationBase>& expectation_base); 540 541 // Returns the expectation this object references. 542 const internal::linked_ptr<internal::ExpectationBase>& 543 expectation_base() const { 544 return expectation_base_; 545 } 546 547 // A linked_ptr that co-owns the expectation this handle references. 548 internal::linked_ptr<internal::ExpectationBase> expectation_base_; 549 }; 550 551 // A set of expectation handles. Useful in the .After() clause of 552 // EXPECT_CALL() for setting the (partial) order of expectations. The 553 // syntax: 554 // 555 // ExpectationSet es; 556 // es += EXPECT_CALL(...)...; 557 // es += EXPECT_CALL(...)...; 558 // EXPECT_CALL(...).After(es)...; 559 // 560 // sets three expectations where the last one can only be matched 561 // after the first two have both been satisfied. 562 // 563 // This class is copyable and has value semantics. 564 class ExpectationSet { 565 public: 566 // A bidirectional iterator that can read a const element in the set. 567 typedef Expectation::Set::const_iterator const_iterator; 568 569 // An object stored in the set. This is an alias of Expectation. 570 typedef Expectation::Set::value_type value_type; 571 572 // Constructs an empty set. 573 ExpectationSet() {} 574 575 // This single-argument ctor must not be explicit, in order to support the 576 // ExpectationSet es = EXPECT_CALL(...); 577 // syntax. 578 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT 579 *this += Expectation(exp); 580 } 581 582 // This single-argument ctor implements implicit conversion from 583 // Expectation and thus must not be explicit. This allows either an 584 // Expectation or an ExpectationSet to be used in .After(). 585 ExpectationSet(const Expectation& e) { // NOLINT 586 *this += e; 587 } 588 589 // The compiler-generator ctor and operator= works exactly as 590 // intended, so we don't need to define our own. 591 592 // Returns true iff rhs contains the same set of Expectation objects 593 // as this does. 594 bool operator==(const ExpectationSet& rhs) const { 595 return expectations_ == rhs.expectations_; 596 } 597 598 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); } 599 600 // Implements the syntax 601 // expectation_set += EXPECT_CALL(...); 602 ExpectationSet& operator+=(const Expectation& e) { 603 expectations_.insert(e); 604 return *this; 605 } 606 607 int size() const { return static_cast<int>(expectations_.size()); } 608 609 const_iterator begin() const { return expectations_.begin(); } 610 const_iterator end() const { return expectations_.end(); } 611 612 private: 613 Expectation::Set expectations_; 614 }; 615 616 617 // Sequence objects are used by a user to specify the relative order 618 // in which the expectations should match. They are copyable (we rely 619 // on the compiler-defined copy constructor and assignment operator). 620 class GTEST_API_ Sequence { 621 public: 622 // Constructs an empty sequence. 623 Sequence() : last_expectation_(new Expectation) {} 624 625 // Adds an expectation to this sequence. The caller must ensure 626 // that no other thread is accessing this Sequence object. 627 void AddExpectation(const Expectation& expectation) const; 628 629 private: 630 // The last expectation in this sequence. We use a linked_ptr here 631 // because Sequence objects are copyable and we want the copies to 632 // be aliases. The linked_ptr allows the copies to co-own and share 633 // the same Expectation object. 634 internal::linked_ptr<Expectation> last_expectation_; 635 }; // class Sequence 636 637 // An object of this type causes all EXPECT_CALL() statements 638 // encountered in its scope to be put in an anonymous sequence. The 639 // work is done in the constructor and destructor. You should only 640 // create an InSequence object on the stack. 641 // 642 // The sole purpose for this class is to support easy definition of 643 // sequential expectations, e.g. 644 // 645 // { 646 // InSequence dummy; // The name of the object doesn't matter. 647 // 648 // // The following expectations must match in the order they appear. 649 // EXPECT_CALL(a, Bar())...; 650 // EXPECT_CALL(a, Baz())...; 651 // ... 652 // EXPECT_CALL(b, Xyz())...; 653 // } 654 // 655 // You can create InSequence objects in multiple threads, as long as 656 // they are used to affect different mock objects. The idea is that 657 // each thread can create and set up its own mocks as if it's the only 658 // thread. However, for clarity of your tests we recommend you to set 659 // up mocks in the main thread unless you have a good reason not to do 660 // so. 661 class GTEST_API_ InSequence { 662 public: 663 InSequence(); 664 ~InSequence(); 665 private: 666 bool sequence_created_; 667 668 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT 669 } GTEST_ATTRIBUTE_UNUSED_; 670 671 namespace internal { 672 673 // Points to the implicit sequence introduced by a living InSequence 674 // object (if any) in the current thread or NULL. 675 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence; 676 677 // Base class for implementing expectations. 678 // 679 // There are two reasons for having a type-agnostic base class for 680 // Expectation: 681 // 682 // 1. We need to store collections of expectations of different 683 // types (e.g. all pre-requisites of a particular expectation, all 684 // expectations in a sequence). Therefore these expectation objects 685 // must share a common base class. 686 // 687 // 2. We can avoid binary code bloat by moving methods not depending 688 // on the template argument of Expectation to the base class. 689 // 690 // This class is internal and mustn't be used by user code directly. 691 class GTEST_API_ ExpectationBase { 692 public: 693 // source_text is the EXPECT_CALL(...) source that created this Expectation. 694 ExpectationBase(const char* file, int line, const std::string& source_text); 695 696 virtual ~ExpectationBase(); 697 698 // Where in the source file was the expectation spec defined? 699 const char* file() const { return file_; } 700 int line() const { return line_; } 701 const char* source_text() const { return source_text_.c_str(); } 702 // Returns the cardinality specified in the expectation spec. 703 const Cardinality& cardinality() const { return cardinality_; } 704 705 // Describes the source file location of this expectation. 706 void DescribeLocationTo(::std::ostream* os) const { 707 *os << FormatFileLocation(file(), line()) << " "; 708 } 709 710 // Describes how many times a function call matching this 711 // expectation has occurred. 712 void DescribeCallCountTo(::std::ostream* os) const 713 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); 714 715 // If this mock method has an extra matcher (i.e. .With(matcher)), 716 // describes it to the ostream. 717 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0; 718 719 protected: 720 friend class ::testing::Expectation; 721 friend class UntypedFunctionMockerBase; 722 723 enum Clause { 724 // Don't change the order of the enum members! 725 kNone, 726 kWith, 727 kTimes, 728 kInSequence, 729 kAfter, 730 kWillOnce, 731 kWillRepeatedly, 732 kRetiresOnSaturation 733 }; 734 735 typedef std::vector<const void*> UntypedActions; 736 737 // Returns an Expectation object that references and co-owns this 738 // expectation. 739 virtual Expectation GetHandle() = 0; 740 741 // Asserts that the EXPECT_CALL() statement has the given property. 742 void AssertSpecProperty(bool property, 743 const std::string& failure_message) const { 744 Assert(property, file_, line_, failure_message); 745 } 746 747 // Expects that the EXPECT_CALL() statement has the given property. 748 void ExpectSpecProperty(bool property, 749 const std::string& failure_message) const { 750 Expect(property, file_, line_, failure_message); 751 } 752 753 // Explicitly specifies the cardinality of this expectation. Used 754 // by the subclasses to implement the .Times() clause. 755 void SpecifyCardinality(const Cardinality& cardinality); 756 757 // Returns true iff the user specified the cardinality explicitly 758 // using a .Times(). 759 bool cardinality_specified() const { return cardinality_specified_; } 760 761 // Sets the cardinality of this expectation spec. 762 void set_cardinality(const Cardinality& a_cardinality) { 763 cardinality_ = a_cardinality; 764 } 765 766 // The following group of methods should only be called after the 767 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by 768 // the current thread. 769 770 // Retires all pre-requisites of this expectation. 771 void RetireAllPreRequisites() 772 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); 773 774 // Returns true iff this expectation is retired. 775 bool is_retired() const 776 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 777 g_gmock_mutex.AssertHeld(); 778 return retired_; 779 } 780 781 // Retires this expectation. 782 void Retire() 783 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 784 g_gmock_mutex.AssertHeld(); 785 retired_ = true; 786 } 787 788 // Returns true iff this expectation is satisfied. 789 bool IsSatisfied() const 790 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 791 g_gmock_mutex.AssertHeld(); 792 return cardinality().IsSatisfiedByCallCount(call_count_); 793 } 794 795 // Returns true iff this expectation is saturated. 796 bool IsSaturated() const 797 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 798 g_gmock_mutex.AssertHeld(); 799 return cardinality().IsSaturatedByCallCount(call_count_); 800 } 801 802 // Returns true iff this expectation is over-saturated. 803 bool IsOverSaturated() const 804 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 805 g_gmock_mutex.AssertHeld(); 806 return cardinality().IsOverSaturatedByCallCount(call_count_); 807 } 808 809 // Returns true iff all pre-requisites of this expectation are satisfied. 810 bool AllPrerequisitesAreSatisfied() const 811 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); 812 813 // Adds unsatisfied pre-requisites of this expectation to 'result'. 814 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const 815 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); 816 817 // Returns the number this expectation has been invoked. 818 int call_count() const 819 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 820 g_gmock_mutex.AssertHeld(); 821 return call_count_; 822 } 823 824 // Increments the number this expectation has been invoked. 825 void IncrementCallCount() 826 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 827 g_gmock_mutex.AssertHeld(); 828 call_count_++; 829 } 830 831 // Checks the action count (i.e. the number of WillOnce() and 832 // WillRepeatedly() clauses) against the cardinality if this hasn't 833 // been done before. Prints a warning if there are too many or too 834 // few actions. 835 void CheckActionCountIfNotDone() const 836 GTEST_LOCK_EXCLUDED_(mutex_); 837 838 friend class ::testing::Sequence; 839 friend class ::testing::internal::ExpectationTester; 840 841 template <typename Function> 842 friend class TypedExpectation; 843 844 // Implements the .Times() clause. 845 void UntypedTimes(const Cardinality& a_cardinality); 846 847 // This group of fields are part of the spec and won't change after 848 // an EXPECT_CALL() statement finishes. 849 const char* file_; // The file that contains the expectation. 850 int line_; // The line number of the expectation. 851 const std::string source_text_; // The EXPECT_CALL(...) source text. 852 // True iff the cardinality is specified explicitly. 853 bool cardinality_specified_; 854 Cardinality cardinality_; // The cardinality of the expectation. 855 // The immediate pre-requisites (i.e. expectations that must be 856 // satisfied before this expectation can be matched) of this 857 // expectation. We use linked_ptr in the set because we want an 858 // Expectation object to be co-owned by its FunctionMocker and its 859 // successors. This allows multiple mock objects to be deleted at 860 // different times. 861 ExpectationSet immediate_prerequisites_; 862 863 // This group of fields are the current state of the expectation, 864 // and can change as the mock function is called. 865 int call_count_; // How many times this expectation has been invoked. 866 bool retired_; // True iff this expectation has retired. 867 UntypedActions untyped_actions_; 868 bool extra_matcher_specified_; 869 bool repeated_action_specified_; // True if a WillRepeatedly() was specified. 870 bool retires_on_saturation_; 871 Clause last_clause_; 872 mutable bool action_count_checked_; // Under mutex_. 873 mutable Mutex mutex_; // Protects action_count_checked_. 874 875 GTEST_DISALLOW_ASSIGN_(ExpectationBase); 876 }; // class ExpectationBase 877 878 // Impements an expectation for the given function type. 879 template <typename F> 880 class TypedExpectation : public ExpectationBase { 881 public: 882 typedef typename Function<F>::ArgumentTuple ArgumentTuple; 883 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; 884 typedef typename Function<F>::Result Result; 885 886 TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line, 887 const std::string& a_source_text, 888 const ArgumentMatcherTuple& m) 889 : ExpectationBase(a_file, a_line, a_source_text), 890 owner_(owner), 891 matchers_(m), 892 // By default, extra_matcher_ should match anything. However, 893 // we cannot initialize it with _ as that triggers a compiler 894 // bug in Symbian's C++ compiler (cannot decide between two 895 // overloaded constructors of Matcher<const ArgumentTuple&>). 896 extra_matcher_(A<const ArgumentTuple&>()), 897 repeated_action_(DoDefault()) {} 898 899 virtual ~TypedExpectation() { 900 // Check the validity of the action count if it hasn't been done 901 // yet (for example, if the expectation was never used). 902 CheckActionCountIfNotDone(); 903 for (UntypedActions::const_iterator it = untyped_actions_.begin(); 904 it != untyped_actions_.end(); ++it) { 905 delete static_cast<const Action<F>*>(*it); 906 } 907 } 908 909 // Implements the .With() clause. 910 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) { 911 if (last_clause_ == kWith) { 912 ExpectSpecProperty(false, 913 ".With() cannot appear " 914 "more than once in an EXPECT_CALL()."); 915 } else { 916 ExpectSpecProperty(last_clause_ < kWith, 917 ".With() must be the first " 918 "clause in an EXPECT_CALL()."); 919 } 920 last_clause_ = kWith; 921 922 extra_matcher_ = m; 923 extra_matcher_specified_ = true; 924 return *this; 925 } 926 927 // Implements the .Times() clause. 928 TypedExpectation& Times(const Cardinality& a_cardinality) { 929 ExpectationBase::UntypedTimes(a_cardinality); 930 return *this; 931 } 932 933 // Implements the .Times() clause. 934 TypedExpectation& Times(int n) { 935 return Times(Exactly(n)); 936 } 937 938 // Implements the .InSequence() clause. 939 TypedExpectation& InSequence(const Sequence& s) { 940 ExpectSpecProperty(last_clause_ <= kInSequence, 941 ".InSequence() cannot appear after .After()," 942 " .WillOnce(), .WillRepeatedly(), or " 943 ".RetiresOnSaturation()."); 944 last_clause_ = kInSequence; 945 946 s.AddExpectation(GetHandle()); 947 return *this; 948 } 949 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) { 950 return InSequence(s1).InSequence(s2); 951 } 952 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, 953 const Sequence& s3) { 954 return InSequence(s1, s2).InSequence(s3); 955 } 956 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, 957 const Sequence& s3, const Sequence& s4) { 958 return InSequence(s1, s2, s3).InSequence(s4); 959 } 960 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, 961 const Sequence& s3, const Sequence& s4, 962 const Sequence& s5) { 963 return InSequence(s1, s2, s3, s4).InSequence(s5); 964 } 965 966 // Implements that .After() clause. 967 TypedExpectation& After(const ExpectationSet& s) { 968 ExpectSpecProperty(last_clause_ <= kAfter, 969 ".After() cannot appear after .WillOnce()," 970 " .WillRepeatedly(), or " 971 ".RetiresOnSaturation()."); 972 last_clause_ = kAfter; 973 974 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) { 975 immediate_prerequisites_ += *it; 976 } 977 return *this; 978 } 979 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) { 980 return After(s1).After(s2); 981 } 982 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, 983 const ExpectationSet& s3) { 984 return After(s1, s2).After(s3); 985 } 986 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, 987 const ExpectationSet& s3, const ExpectationSet& s4) { 988 return After(s1, s2, s3).After(s4); 989 } 990 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, 991 const ExpectationSet& s3, const ExpectationSet& s4, 992 const ExpectationSet& s5) { 993 return After(s1, s2, s3, s4).After(s5); 994 } 995 996 // Implements the .WillOnce() clause. 997 TypedExpectation& WillOnce(const Action<F>& action) { 998 ExpectSpecProperty(last_clause_ <= kWillOnce, 999 ".WillOnce() cannot appear after " 1000 ".WillRepeatedly() or .RetiresOnSaturation()."); 1001 last_clause_ = kWillOnce; 1002 1003 untyped_actions_.push_back(new Action<F>(action)); 1004 if (!cardinality_specified()) { 1005 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size()))); 1006 } 1007 return *this; 1008 } 1009 1010 // Implements the .WillRepeatedly() clause. 1011 TypedExpectation& WillRepeatedly(const Action<F>& action) { 1012 if (last_clause_ == kWillRepeatedly) { 1013 ExpectSpecProperty(false, 1014 ".WillRepeatedly() cannot appear " 1015 "more than once in an EXPECT_CALL()."); 1016 } else { 1017 ExpectSpecProperty(last_clause_ < kWillRepeatedly, 1018 ".WillRepeatedly() cannot appear " 1019 "after .RetiresOnSaturation()."); 1020 } 1021 last_clause_ = kWillRepeatedly; 1022 repeated_action_specified_ = true; 1023 1024 repeated_action_ = action; 1025 if (!cardinality_specified()) { 1026 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size()))); 1027 } 1028 1029 // Now that no more action clauses can be specified, we check 1030 // whether their count makes sense. 1031 CheckActionCountIfNotDone(); 1032 return *this; 1033 } 1034 1035 // Implements the .RetiresOnSaturation() clause. 1036 TypedExpectation& RetiresOnSaturation() { 1037 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation, 1038 ".RetiresOnSaturation() cannot appear " 1039 "more than once."); 1040 last_clause_ = kRetiresOnSaturation; 1041 retires_on_saturation_ = true; 1042 1043 // Now that no more action clauses can be specified, we check 1044 // whether their count makes sense. 1045 CheckActionCountIfNotDone(); 1046 return *this; 1047 } 1048 1049 // Returns the matchers for the arguments as specified inside the 1050 // EXPECT_CALL() macro. 1051 const ArgumentMatcherTuple& matchers() const { 1052 return matchers_; 1053 } 1054 1055 // Returns the matcher specified by the .With() clause. 1056 const Matcher<const ArgumentTuple&>& extra_matcher() const { 1057 return extra_matcher_; 1058 } 1059 1060 // Returns the action specified by the .WillRepeatedly() clause. 1061 const Action<F>& repeated_action() const { return repeated_action_; } 1062 1063 // If this mock method has an extra matcher (i.e. .With(matcher)), 1064 // describes it to the ostream. 1065 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) { 1066 if (extra_matcher_specified_) { 1067 *os << " Expected args: "; 1068 extra_matcher_.DescribeTo(os); 1069 *os << "\n"; 1070 } 1071 } 1072 1073 private: 1074 template <typename Function> 1075 friend class FunctionMockerBase; 1076 1077 // Returns an Expectation object that references and co-owns this 1078 // expectation. 1079 virtual Expectation GetHandle() { 1080 return owner_->GetHandleOf(this); 1081 } 1082 1083 // The following methods will be called only after the EXPECT_CALL() 1084 // statement finishes and when the current thread holds 1085 // g_gmock_mutex. 1086 1087 // Returns true iff this expectation matches the given arguments. 1088 bool Matches(const ArgumentTuple& args) const 1089 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1090 g_gmock_mutex.AssertHeld(); 1091 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); 1092 } 1093 1094 // Returns true iff this expectation should handle the given arguments. 1095 bool ShouldHandleArguments(const ArgumentTuple& args) const 1096 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1097 g_gmock_mutex.AssertHeld(); 1098 1099 // In case the action count wasn't checked when the expectation 1100 // was defined (e.g. if this expectation has no WillRepeatedly() 1101 // or RetiresOnSaturation() clause), we check it when the 1102 // expectation is used for the first time. 1103 CheckActionCountIfNotDone(); 1104 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args); 1105 } 1106 1107 // Describes the result of matching the arguments against this 1108 // expectation to the given ostream. 1109 void ExplainMatchResultTo( 1110 const ArgumentTuple& args, 1111 ::std::ostream* os) const 1112 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1113 g_gmock_mutex.AssertHeld(); 1114 1115 if (is_retired()) { 1116 *os << " Expected: the expectation is active\n" 1117 << " Actual: it is retired\n"; 1118 } else if (!Matches(args)) { 1119 if (!TupleMatches(matchers_, args)) { 1120 ExplainMatchFailureTupleTo(matchers_, args, os); 1121 } 1122 StringMatchResultListener listener; 1123 if (!extra_matcher_.MatchAndExplain(args, &listener)) { 1124 *os << " Expected args: "; 1125 extra_matcher_.DescribeTo(os); 1126 *os << "\n Actual: don't match"; 1127 1128 internal::PrintIfNotEmpty(listener.str(), os); 1129 *os << "\n"; 1130 } 1131 } else if (!AllPrerequisitesAreSatisfied()) { 1132 *os << " Expected: all pre-requisites are satisfied\n" 1133 << " Actual: the following immediate pre-requisites " 1134 << "are not satisfied:\n"; 1135 ExpectationSet unsatisfied_prereqs; 1136 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs); 1137 int i = 0; 1138 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin(); 1139 it != unsatisfied_prereqs.end(); ++it) { 1140 it->expectation_base()->DescribeLocationTo(os); 1141 *os << "pre-requisite #" << i++ << "\n"; 1142 } 1143 *os << " (end of pre-requisites)\n"; 1144 } else { 1145 // This line is here just for completeness' sake. It will never 1146 // be executed as currently the ExplainMatchResultTo() function 1147 // is called only when the mock function call does NOT match the 1148 // expectation. 1149 *os << "The call matches the expectation.\n"; 1150 } 1151 } 1152 1153 // Returns the action that should be taken for the current invocation. 1154 const Action<F>& GetCurrentAction( 1155 const FunctionMockerBase<F>* mocker, 1156 const ArgumentTuple& args) const 1157 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1158 g_gmock_mutex.AssertHeld(); 1159 const int count = call_count(); 1160 Assert(count >= 1, __FILE__, __LINE__, 1161 "call_count() is <= 0 when GetCurrentAction() is " 1162 "called - this should never happen."); 1163 1164 const int action_count = static_cast<int>(untyped_actions_.size()); 1165 if (action_count > 0 && !repeated_action_specified_ && 1166 count > action_count) { 1167 // If there is at least one WillOnce() and no WillRepeatedly(), 1168 // we warn the user when the WillOnce() clauses ran out. 1169 ::std::stringstream ss; 1170 DescribeLocationTo(&ss); 1171 ss << "Actions ran out in " << source_text() << "...\n" 1172 << "Called " << count << " times, but only " 1173 << action_count << " WillOnce()" 1174 << (action_count == 1 ? " is" : "s are") << " specified - "; 1175 mocker->DescribeDefaultActionTo(args, &ss); 1176 Log(kWarning, ss.str(), 1); 1177 } 1178 1179 return count <= action_count ? 1180 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) : 1181 repeated_action(); 1182 } 1183 1184 // Given the arguments of a mock function call, if the call will 1185 // over-saturate this expectation, returns the default action; 1186 // otherwise, returns the next action in this expectation. Also 1187 // describes *what* happened to 'what', and explains *why* Google 1188 // Mock does it to 'why'. This method is not const as it calls 1189 // IncrementCallCount(). A return value of NULL means the default 1190 // action. 1191 const Action<F>* GetActionForArguments( 1192 const FunctionMockerBase<F>* mocker, 1193 const ArgumentTuple& args, 1194 ::std::ostream* what, 1195 ::std::ostream* why) 1196 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1197 g_gmock_mutex.AssertHeld(); 1198 if (IsSaturated()) { 1199 // We have an excessive call. 1200 IncrementCallCount(); 1201 *what << "Mock function called more times than expected - "; 1202 mocker->DescribeDefaultActionTo(args, what); 1203 DescribeCallCountTo(why); 1204 1205 // TODO(wan (at) google.com): allow the user to control whether 1206 // unexpected calls should fail immediately or continue using a 1207 // flag --gmock_unexpected_calls_are_fatal. 1208 return NULL; 1209 } 1210 1211 IncrementCallCount(); 1212 RetireAllPreRequisites(); 1213 1214 if (retires_on_saturation_ && IsSaturated()) { 1215 Retire(); 1216 } 1217 1218 // Must be done after IncrementCount()! 1219 *what << "Mock function call matches " << source_text() <<"...\n"; 1220 return &(GetCurrentAction(mocker, args)); 1221 } 1222 1223 // All the fields below won't change once the EXPECT_CALL() 1224 // statement finishes. 1225 FunctionMockerBase<F>* const owner_; 1226 ArgumentMatcherTuple matchers_; 1227 Matcher<const ArgumentTuple&> extra_matcher_; 1228 Action<F> repeated_action_; 1229 1230 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation); 1231 }; // class TypedExpectation 1232 1233 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for 1234 // specifying the default behavior of, or expectation on, a mock 1235 // function. 1236 1237 // Note: class MockSpec really belongs to the ::testing namespace. 1238 // However if we define it in ::testing, MSVC will complain when 1239 // classes in ::testing::internal declare it as a friend class 1240 // template. To workaround this compiler bug, we define MockSpec in 1241 // ::testing::internal and import it into ::testing. 1242 1243 // Logs a message including file and line number information. 1244 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, 1245 const char* file, int line, 1246 const std::string& message); 1247 1248 template <typename F> 1249 class MockSpec { 1250 public: 1251 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; 1252 typedef typename internal::Function<F>::ArgumentMatcherTuple 1253 ArgumentMatcherTuple; 1254 1255 // Constructs a MockSpec object, given the function mocker object 1256 // that the spec is associated with. 1257 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker) 1258 : function_mocker_(function_mocker) {} 1259 1260 // Adds a new default action spec to the function mocker and returns 1261 // the newly created spec. 1262 internal::OnCallSpec<F>& InternalDefaultActionSetAt( 1263 const char* file, int line, const char* obj, const char* call) { 1264 LogWithLocation(internal::kInfo, file, line, 1265 std::string("ON_CALL(") + obj + ", " + call + ") invoked"); 1266 return function_mocker_->AddNewOnCallSpec(file, line, matchers_); 1267 } 1268 1269 // Adds a new expectation spec to the function mocker and returns 1270 // the newly created spec. 1271 internal::TypedExpectation<F>& InternalExpectedAt( 1272 const char* file, int line, const char* obj, const char* call) { 1273 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " + 1274 call + ")"); 1275 LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); 1276 return function_mocker_->AddNewExpectation( 1277 file, line, source_text, matchers_); 1278 } 1279 1280 private: 1281 template <typename Function> 1282 friend class internal::FunctionMocker; 1283 1284 void SetMatchers(const ArgumentMatcherTuple& matchers) { 1285 matchers_ = matchers; 1286 } 1287 1288 // The function mocker that owns this spec. 1289 internal::FunctionMockerBase<F>* const function_mocker_; 1290 // The argument matchers specified in the spec. 1291 ArgumentMatcherTuple matchers_; 1292 1293 GTEST_DISALLOW_ASSIGN_(MockSpec); 1294 }; // class MockSpec 1295 1296 // Wrapper type for generically holding an ordinary value or lvalue reference. 1297 // If T is not a reference type, it must be copyable or movable. 1298 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless 1299 // T is a move-only value type (which means that it will always be copyable 1300 // if the current platform does not support move semantics). 1301 // 1302 // The primary template defines handling for values, but function header 1303 // comments describe the contract for the whole template (including 1304 // specializations). 1305 template <typename T> 1306 class ReferenceOrValueWrapper { 1307 public: 1308 // Constructs a wrapper from the given value/reference. 1309 explicit ReferenceOrValueWrapper(T value) 1310 : value_(::testing::internal::move(value)) { 1311 } 1312 1313 // Unwraps and returns the underlying value/reference, exactly as 1314 // originally passed. The behavior of calling this more than once on 1315 // the same object is unspecified. 1316 T Unwrap() { return ::testing::internal::move(value_); } 1317 1318 // Provides nondestructive access to the underlying value/reference. 1319 // Always returns a const reference (more precisely, 1320 // const RemoveReference<T>&). The behavior of calling this after 1321 // calling Unwrap on the same object is unspecified. 1322 const T& Peek() const { 1323 return value_; 1324 } 1325 1326 private: 1327 T value_; 1328 }; 1329 1330 // Specialization for lvalue reference types. See primary template 1331 // for documentation. 1332 template <typename T> 1333 class ReferenceOrValueWrapper<T&> { 1334 public: 1335 // Workaround for debatable pass-by-reference lint warning (c-library-team 1336 // policy precludes NOLINT in this context) 1337 typedef T& reference; 1338 explicit ReferenceOrValueWrapper(reference ref) 1339 : value_ptr_(&ref) {} 1340 T& Unwrap() { return *value_ptr_; } 1341 const T& Peek() const { return *value_ptr_; } 1342 1343 private: 1344 T* value_ptr_; 1345 }; 1346 1347 // MSVC warns about using 'this' in base member initializer list, so 1348 // we need to temporarily disable the warning. We have to do it for 1349 // the entire class to suppress the warning, even though it's about 1350 // the constructor only. 1351 1352 #ifdef _MSC_VER 1353 # pragma warning(push) // Saves the current warning state. 1354 # pragma warning(disable:4355) // Temporarily disables warning 4355. 1355 #endif // _MSV_VER 1356 1357 // C++ treats the void type specially. For example, you cannot define 1358 // a void-typed variable or pass a void value to a function. 1359 // ActionResultHolder<T> holds a value of type T, where T must be a 1360 // copyable type or void (T doesn't need to be default-constructable). 1361 // It hides the syntactic difference between void and other types, and 1362 // is used to unify the code for invoking both void-returning and 1363 // non-void-returning mock functions. 1364 1365 // Untyped base class for ActionResultHolder<T>. 1366 class UntypedActionResultHolderBase { 1367 public: 1368 virtual ~UntypedActionResultHolderBase() {} 1369 1370 // Prints the held value as an action's result to os. 1371 virtual void PrintAsActionResult(::std::ostream* os) const = 0; 1372 }; 1373 1374 // This generic definition is used when T is not void. 1375 template <typename T> 1376 class ActionResultHolder : public UntypedActionResultHolderBase { 1377 public: 1378 // Returns the held value. Must not be called more than once. 1379 T Unwrap() { 1380 return result_.Unwrap(); 1381 } 1382 1383 // Prints the held value as an action's result to os. 1384 virtual void PrintAsActionResult(::std::ostream* os) const { 1385 *os << "\n Returns: "; 1386 // T may be a reference type, so we don't use UniversalPrint(). 1387 UniversalPrinter<T>::Print(result_.Peek(), os); 1388 } 1389 1390 // Performs the given mock function's default action and returns the 1391 // result in a new-ed ActionResultHolder. 1392 template <typename F> 1393 static ActionResultHolder* PerformDefaultAction( 1394 const FunctionMockerBase<F>* func_mocker, 1395 const typename Function<F>::ArgumentTuple& args, 1396 const std::string& call_description) { 1397 return new ActionResultHolder(Wrapper( 1398 func_mocker->PerformDefaultAction(args, call_description))); 1399 } 1400 1401 // Performs the given action and returns the result in a new-ed 1402 // ActionResultHolder. 1403 template <typename F> 1404 static ActionResultHolder* 1405 PerformAction(const Action<F>& action, 1406 const typename Function<F>::ArgumentTuple& args) { 1407 return new ActionResultHolder(Wrapper(action.Perform(args))); 1408 } 1409 1410 private: 1411 typedef ReferenceOrValueWrapper<T> Wrapper; 1412 1413 explicit ActionResultHolder(Wrapper result) 1414 : result_(::testing::internal::move(result)) { 1415 } 1416 1417 Wrapper result_; 1418 1419 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); 1420 }; 1421 1422 // Specialization for T = void. 1423 template <> 1424 class ActionResultHolder<void> : public UntypedActionResultHolderBase { 1425 public: 1426 void Unwrap() { } 1427 1428 virtual void PrintAsActionResult(::std::ostream* /* os */) const {} 1429 1430 // Performs the given mock function's default action and returns ownership 1431 // of an empty ActionResultHolder*. 1432 template <typename F> 1433 static ActionResultHolder* PerformDefaultAction( 1434 const FunctionMockerBase<F>* func_mocker, 1435 const typename Function<F>::ArgumentTuple& args, 1436 const std::string& call_description) { 1437 func_mocker->PerformDefaultAction(args, call_description); 1438 return new ActionResultHolder; 1439 } 1440 1441 // Performs the given action and returns ownership of an empty 1442 // ActionResultHolder*. 1443 template <typename F> 1444 static ActionResultHolder* PerformAction( 1445 const Action<F>& action, 1446 const typename Function<F>::ArgumentTuple& args) { 1447 action.Perform(args); 1448 return new ActionResultHolder; 1449 } 1450 1451 private: 1452 ActionResultHolder() {} 1453 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); 1454 }; 1455 1456 // The base of the function mocker class for the given function type. 1457 // We put the methods in this class instead of its child to avoid code 1458 // bloat. 1459 template <typename F> 1460 class FunctionMockerBase : public UntypedFunctionMockerBase { 1461 public: 1462 typedef typename Function<F>::Result Result; 1463 typedef typename Function<F>::ArgumentTuple ArgumentTuple; 1464 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; 1465 1466 FunctionMockerBase() : current_spec_(this) {} 1467 1468 // The destructor verifies that all expectations on this mock 1469 // function have been satisfied. If not, it will report Google Test 1470 // non-fatal failures for the violations. 1471 virtual ~FunctionMockerBase() 1472 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { 1473 MutexLock l(&g_gmock_mutex); 1474 VerifyAndClearExpectationsLocked(); 1475 Mock::UnregisterLocked(this); 1476 ClearDefaultActionsLocked(); 1477 } 1478 1479 // Returns the ON_CALL spec that matches this mock function with the 1480 // given arguments; returns NULL if no matching ON_CALL is found. 1481 // L = * 1482 const OnCallSpec<F>* FindOnCallSpec( 1483 const ArgumentTuple& args) const { 1484 for (UntypedOnCallSpecs::const_reverse_iterator it 1485 = untyped_on_call_specs_.rbegin(); 1486 it != untyped_on_call_specs_.rend(); ++it) { 1487 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it); 1488 if (spec->Matches(args)) 1489 return spec; 1490 } 1491 1492 return NULL; 1493 } 1494 1495 // Performs the default action of this mock function on the given 1496 // arguments and returns the result. Asserts (or throws if 1497 // exceptions are enabled) with a helpful call descrption if there 1498 // is no valid return value. This method doesn't depend on the 1499 // mutable state of this object, and thus can be called concurrently 1500 // without locking. 1501 // L = * 1502 Result PerformDefaultAction(const ArgumentTuple& args, 1503 const std::string& call_description) const { 1504 const OnCallSpec<F>* const spec = 1505 this->FindOnCallSpec(args); 1506 if (spec != NULL) { 1507 return spec->GetAction().Perform(args); 1508 } 1509 const std::string message = 1510 call_description + 1511 "\n The mock function has no default action " 1512 "set, and its return type has no default value set."; 1513 #if GTEST_HAS_EXCEPTIONS 1514 if (!DefaultValue<Result>::Exists()) { 1515 throw std::runtime_error(message); 1516 } 1517 #else 1518 Assert(DefaultValue<Result>::Exists(), "", -1, message); 1519 #endif 1520 return DefaultValue<Result>::Get(); 1521 } 1522 1523 // Performs the default action with the given arguments and returns 1524 // the action's result. The call description string will be used in 1525 // the error message to describe the call in the case the default 1526 // action fails. The caller is responsible for deleting the result. 1527 // L = * 1528 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( 1529 const void* untyped_args, // must point to an ArgumentTuple 1530 const std::string& call_description) const { 1531 const ArgumentTuple& args = 1532 *static_cast<const ArgumentTuple*>(untyped_args); 1533 return ResultHolder::PerformDefaultAction(this, args, call_description); 1534 } 1535 1536 // Performs the given action with the given arguments and returns 1537 // the action's result. The caller is responsible for deleting the 1538 // result. 1539 // L = * 1540 virtual UntypedActionResultHolderBase* UntypedPerformAction( 1541 const void* untyped_action, const void* untyped_args) const { 1542 // Make a copy of the action before performing it, in case the 1543 // action deletes the mock object (and thus deletes itself). 1544 const Action<F> action = *static_cast<const Action<F>*>(untyped_action); 1545 const ArgumentTuple& args = 1546 *static_cast<const ArgumentTuple*>(untyped_args); 1547 return ResultHolder::PerformAction(action, args); 1548 } 1549 1550 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked(): 1551 // clears the ON_CALL()s set on this mock function. 1552 virtual void ClearDefaultActionsLocked() 1553 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1554 g_gmock_mutex.AssertHeld(); 1555 1556 // Deleting our default actions may trigger other mock objects to be 1557 // deleted, for example if an action contains a reference counted smart 1558 // pointer to that mock object, and that is the last reference. So if we 1559 // delete our actions within the context of the global mutex we may deadlock 1560 // when this method is called again. Instead, make a copy of the set of 1561 // actions to delete, clear our set within the mutex, and then delete the 1562 // actions outside of the mutex. 1563 UntypedOnCallSpecs specs_to_delete; 1564 untyped_on_call_specs_.swap(specs_to_delete); 1565 1566 g_gmock_mutex.Unlock(); 1567 for (UntypedOnCallSpecs::const_iterator it = 1568 specs_to_delete.begin(); 1569 it != specs_to_delete.end(); ++it) { 1570 delete static_cast<const OnCallSpec<F>*>(*it); 1571 } 1572 1573 // Lock the mutex again, since the caller expects it to be locked when we 1574 // return. 1575 g_gmock_mutex.Lock(); 1576 } 1577 1578 protected: 1579 template <typename Function> 1580 friend class MockSpec; 1581 1582 typedef ActionResultHolder<Result> ResultHolder; 1583 1584 // Returns the result of invoking this mock function with the given 1585 // arguments. This function can be safely called from multiple 1586 // threads concurrently. 1587 Result InvokeWith(const ArgumentTuple& args) 1588 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { 1589 scoped_ptr<ResultHolder> holder( 1590 DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args))); 1591 return holder->Unwrap(); 1592 } 1593 1594 // Adds and returns a default action spec for this mock function. 1595 OnCallSpec<F>& AddNewOnCallSpec( 1596 const char* file, int line, 1597 const ArgumentMatcherTuple& m) 1598 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { 1599 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); 1600 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m); 1601 untyped_on_call_specs_.push_back(on_call_spec); 1602 return *on_call_spec; 1603 } 1604 1605 // Adds and returns an expectation spec for this mock function. 1606 TypedExpectation<F>& AddNewExpectation(const char* file, int line, 1607 const std::string& source_text, 1608 const ArgumentMatcherTuple& m) 1609 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { 1610 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); 1611 TypedExpectation<F>* const expectation = 1612 new TypedExpectation<F>(this, file, line, source_text, m); 1613 const linked_ptr<ExpectationBase> untyped_expectation(expectation); 1614 untyped_expectations_.push_back(untyped_expectation); 1615 1616 // Adds this expectation into the implicit sequence if there is one. 1617 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get(); 1618 if (implicit_sequence != NULL) { 1619 implicit_sequence->AddExpectation(Expectation(untyped_expectation)); 1620 } 1621 1622 return *expectation; 1623 } 1624 1625 // The current spec (either default action spec or expectation spec) 1626 // being described on this function mocker. 1627 MockSpec<F>& current_spec() { return current_spec_; } 1628 1629 private: 1630 template <typename Func> friend class TypedExpectation; 1631 1632 // Some utilities needed for implementing UntypedInvokeWith(). 1633 1634 // Describes what default action will be performed for the given 1635 // arguments. 1636 // L = * 1637 void DescribeDefaultActionTo(const ArgumentTuple& args, 1638 ::std::ostream* os) const { 1639 const OnCallSpec<F>* const spec = FindOnCallSpec(args); 1640 1641 if (spec == NULL) { 1642 *os << (internal::type_equals<Result, void>::value ? 1643 "returning directly.\n" : 1644 "returning default value.\n"); 1645 } else { 1646 *os << "taking default action specified at:\n" 1647 << FormatFileLocation(spec->file(), spec->line()) << "\n"; 1648 } 1649 } 1650 1651 // Writes a message that the call is uninteresting (i.e. neither 1652 // explicitly expected nor explicitly unexpected) to the given 1653 // ostream. 1654 virtual void UntypedDescribeUninterestingCall( 1655 const void* untyped_args, 1656 ::std::ostream* os) const 1657 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { 1658 const ArgumentTuple& args = 1659 *static_cast<const ArgumentTuple*>(untyped_args); 1660 *os << "Uninteresting mock function call - "; 1661 DescribeDefaultActionTo(args, os); 1662 *os << " Function call: " << Name(); 1663 UniversalPrint(args, os); 1664 } 1665 1666 // Returns the expectation that matches the given function arguments 1667 // (or NULL is there's no match); when a match is found, 1668 // untyped_action is set to point to the action that should be 1669 // performed (or NULL if the action is "do default"), and 1670 // is_excessive is modified to indicate whether the call exceeds the 1671 // expected number. 1672 // 1673 // Critical section: We must find the matching expectation and the 1674 // corresponding action that needs to be taken in an ATOMIC 1675 // transaction. Otherwise another thread may call this mock 1676 // method in the middle and mess up the state. 1677 // 1678 // However, performing the action has to be left out of the critical 1679 // section. The reason is that we have no control on what the 1680 // action does (it can invoke an arbitrary user function or even a 1681 // mock function) and excessive locking could cause a dead lock. 1682 virtual const ExpectationBase* UntypedFindMatchingExpectation( 1683 const void* untyped_args, 1684 const void** untyped_action, bool* is_excessive, 1685 ::std::ostream* what, ::std::ostream* why) 1686 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { 1687 const ArgumentTuple& args = 1688 *static_cast<const ArgumentTuple*>(untyped_args); 1689 MutexLock l(&g_gmock_mutex); 1690 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args); 1691 if (exp == NULL) { // A match wasn't found. 1692 this->FormatUnexpectedCallMessageLocked(args, what, why); 1693 return NULL; 1694 } 1695 1696 // This line must be done before calling GetActionForArguments(), 1697 // which will increment the call count for *exp and thus affect 1698 // its saturation status. 1699 *is_excessive = exp->IsSaturated(); 1700 const Action<F>* action = exp->GetActionForArguments(this, args, what, why); 1701 if (action != NULL && action->IsDoDefault()) 1702 action = NULL; // Normalize "do default" to NULL. 1703 *untyped_action = action; 1704 return exp; 1705 } 1706 1707 // Prints the given function arguments to the ostream. 1708 virtual void UntypedPrintArgs(const void* untyped_args, 1709 ::std::ostream* os) const { 1710 const ArgumentTuple& args = 1711 *static_cast<const ArgumentTuple*>(untyped_args); 1712 UniversalPrint(args, os); 1713 } 1714 1715 // Returns the expectation that matches the arguments, or NULL if no 1716 // expectation matches them. 1717 TypedExpectation<F>* FindMatchingExpectationLocked( 1718 const ArgumentTuple& args) const 1719 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1720 g_gmock_mutex.AssertHeld(); 1721 for (typename UntypedExpectations::const_reverse_iterator it = 1722 untyped_expectations_.rbegin(); 1723 it != untyped_expectations_.rend(); ++it) { 1724 TypedExpectation<F>* const exp = 1725 static_cast<TypedExpectation<F>*>(it->get()); 1726 if (exp->ShouldHandleArguments(args)) { 1727 return exp; 1728 } 1729 } 1730 return NULL; 1731 } 1732 1733 // Returns a message that the arguments don't match any expectation. 1734 void FormatUnexpectedCallMessageLocked( 1735 const ArgumentTuple& args, 1736 ::std::ostream* os, 1737 ::std::ostream* why) const 1738 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1739 g_gmock_mutex.AssertHeld(); 1740 *os << "\nUnexpected mock function call - "; 1741 DescribeDefaultActionTo(args, os); 1742 PrintTriedExpectationsLocked(args, why); 1743 } 1744 1745 // Prints a list of expectations that have been tried against the 1746 // current mock function call. 1747 void PrintTriedExpectationsLocked( 1748 const ArgumentTuple& args, 1749 ::std::ostream* why) const 1750 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { 1751 g_gmock_mutex.AssertHeld(); 1752 const int count = static_cast<int>(untyped_expectations_.size()); 1753 *why << "Google Mock tried the following " << count << " " 1754 << (count == 1 ? "expectation, but it didn't match" : 1755 "expectations, but none matched") 1756 << ":\n"; 1757 for (int i = 0; i < count; i++) { 1758 TypedExpectation<F>* const expectation = 1759 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get()); 1760 *why << "\n"; 1761 expectation->DescribeLocationTo(why); 1762 if (count > 1) { 1763 *why << "tried expectation #" << i << ": "; 1764 } 1765 *why << expectation->source_text() << "...\n"; 1766 expectation->ExplainMatchResultTo(args, why); 1767 expectation->DescribeCallCountTo(why); 1768 } 1769 } 1770 1771 // The current spec (either default action spec or expectation spec) 1772 // being described on this function mocker. 1773 MockSpec<F> current_spec_; 1774 1775 // There is no generally useful and implementable semantics of 1776 // copying a mock object, so copying a mock is usually a user error. 1777 // Thus we disallow copying function mockers. If the user really 1778 // wants to copy a mock object, he should implement his own copy 1779 // operation, for example: 1780 // 1781 // class MockFoo : public Foo { 1782 // public: 1783 // // Defines a copy constructor explicitly. 1784 // MockFoo(const MockFoo& src) {} 1785 // ... 1786 // }; 1787 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase); 1788 }; // class FunctionMockerBase 1789 1790 #ifdef _MSC_VER 1791 # pragma warning(pop) // Restores the warning state. 1792 #endif // _MSV_VER 1793 1794 // Implements methods of FunctionMockerBase. 1795 1796 // Verifies that all expectations on this mock function have been 1797 // satisfied. Reports one or more Google Test non-fatal failures and 1798 // returns false if not. 1799 1800 // Reports an uninteresting call (whose description is in msg) in the 1801 // manner specified by 'reaction'. 1802 void ReportUninterestingCall(CallReaction reaction, const std::string& msg); 1803 1804 } // namespace internal 1805 1806 // The style guide prohibits "using" statements in a namespace scope 1807 // inside a header file. However, the MockSpec class template is 1808 // meant to be defined in the ::testing namespace. The following line 1809 // is just a trick for working around a bug in MSVC 8.0, which cannot 1810 // handle it if we define MockSpec in ::testing. 1811 using internal::MockSpec; 1812 1813 // Const(x) is a convenient function for obtaining a const reference 1814 // to x. This is useful for setting expectations on an overloaded 1815 // const mock method, e.g. 1816 // 1817 // class MockFoo : public FooInterface { 1818 // public: 1819 // MOCK_METHOD0(Bar, int()); 1820 // MOCK_CONST_METHOD0(Bar, int&()); 1821 // }; 1822 // 1823 // MockFoo foo; 1824 // // Expects a call to non-const MockFoo::Bar(). 1825 // EXPECT_CALL(foo, Bar()); 1826 // // Expects a call to const MockFoo::Bar(). 1827 // EXPECT_CALL(Const(foo), Bar()); 1828 template <typename T> 1829 inline const T& Const(const T& x) { return x; } 1830 1831 // Constructs an Expectation object that references and co-owns exp. 1832 inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT 1833 : expectation_base_(exp.GetHandle().expectation_base()) {} 1834 1835 } // namespace testing 1836 1837 // A separate macro is required to avoid compile errors when the name 1838 // of the method used in call is a result of macro expansion. 1839 // See CompilesWithMethodNameExpandedFromMacro tests in 1840 // internal/gmock-spec-builders_test.cc for more details. 1841 #define GMOCK_ON_CALL_IMPL_(obj, call) \ 1842 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \ 1843 #obj, #call) 1844 #define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call) 1845 1846 #define GMOCK_EXPECT_CALL_IMPL_(obj, call) \ 1847 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call) 1848 #define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call) 1849 1850 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ 1851