1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
30 // Google Mock - a framework for writing C++ mock classes.
32 // This file implements the ON_CALL() and EXPECT_CALL() macros.
34 // A user can use the ON_CALL() macro to specify the default action of
35 // a mock method. The syntax is:
37 // ON_CALL(mock_object, Method(argument-matchers))
38 // .With(multi-argument-matcher)
39 // .WillByDefault(action);
41 // where the .With() clause is optional.
43 // A user can use the EXPECT_CALL() macro to specify an expectation on
44 // a mock method. The syntax is:
46 // EXPECT_CALL(mock_object, Method(argument-matchers))
47 // .With(multi-argument-matchers)
48 // .Times(cardinality)
49 // .InSequence(sequences)
50 // .After(expectations)
52 // .WillRepeatedly(action)
53 // .RetiresOnSaturation();
55 // where all clauses are optional, and .InSequence()/.After()/
56 // .WillOnce() can appear any number of times.
58 // IWYU pragma: private, include "gmock/gmock.h"
59 // IWYU pragma: friend gmock/.*
61 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
71 #include <type_traits>
75 #include "gmock/gmock-actions.h"
76 #include "gmock/gmock-cardinalities.h"
77 #include "gmock/gmock-matchers.h"
78 #include "gmock/internal/gmock-internal-utils.h"
79 #include "gmock/internal/gmock-port.h"
80 #include "gtest/gtest.h"
82 #if GTEST_HAS_EXCEPTIONS
83 #include <stdexcept> // NOLINT
86 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
87 /* class A needs to have dll-interface to be used by clients of class B */)
91 // An abstract handle of an expectation.
94 // A set of expectation handles.
97 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
98 // and MUST NOT BE USED IN USER CODE!!!
101 // Implements a mock function.
102 template <typename F>
103 class FunctionMocker;
105 // Base class for expectations.
106 class ExpectationBase;
108 // Implements an expectation.
109 template <typename F>
110 class TypedExpectation;
112 // Helper class for testing the Expectation class template.
113 class ExpectationTester;
115 // Helper classes for implementing NiceMock, StrictMock, and NaggyMock.
116 template <typename MockClass>
118 template <typename MockClass>
119 class StrictMockImpl;
120 template <typename MockClass>
123 // Protects the mock object registry (in class Mock), all function
124 // mockers, and all expectations.
126 // The reason we don't use more fine-grained protection is: when a
127 // mock function Foo() is called, it needs to consult its expectations
128 // to see which one should be picked. If another thread is allowed to
129 // call a mock function (either Foo() or a different one) at the same
130 // time, it could affect the "retired" attributes of Foo()'s
131 // expectations when InSequence() is used, and thus affect which
132 // expectation gets picked. Therefore, we sequence all mock function
133 // calls to ensure the integrity of the mock objects' states.
134 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
136 // Abstract base class of FunctionMocker. This is the
137 // type-agnostic part of the function mocker interface. Its pure
138 // virtual methods are implemented by FunctionMocker.
139 class GTEST_API_ UntypedFunctionMockerBase {
141 UntypedFunctionMockerBase();
142 virtual ~UntypedFunctionMockerBase();
144 // Verifies that all expectations on this mock function have been
145 // satisfied. Reports one or more Google Test non-fatal failures
146 // and returns false if not.
147 bool VerifyAndClearExpectationsLocked()
148 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
150 // Clears the ON_CALL()s set on this mock function.
151 virtual void ClearDefaultActionsLocked()
152 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
154 // In all of the following Untyped* functions, it's the caller's
155 // responsibility to guarantee the correctness of the arguments'
158 // Writes a message that the call is uninteresting (i.e. neither
159 // explicitly expected nor explicitly unexpected) to the given
161 virtual void UntypedDescribeUninterestingCall(const void* untyped_args,
162 ::std::ostream* os) const
163 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
165 // Returns the expectation that matches the given function arguments
166 // (or NULL is there's no match); when a match is found,
167 // untyped_action is set to point to the action that should be
168 // performed (or NULL if the action is "do default"), and
169 // is_excessive is modified to indicate whether the call exceeds the
171 virtual const ExpectationBase* UntypedFindMatchingExpectation(
172 const void* untyped_args, const void** untyped_action, bool* is_excessive,
173 ::std::ostream* what, ::std::ostream* why)
174 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
176 // Prints the given function arguments to the ostream.
177 virtual void UntypedPrintArgs(const void* untyped_args,
178 ::std::ostream* os) const = 0;
180 // Sets the mock object this mock method belongs to, and registers
181 // this information in the global mock registry. Will be called
182 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
184 void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
186 // Sets the mock object this mock method belongs to, and sets the
187 // name of the mock function. Will be called upon each invocation
188 // of this mock function.
189 void SetOwnerAndName(const void* mock_obj, const char* name)
190 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
192 // Returns the mock object this mock method belongs to. Must be
193 // called after RegisterOwner() or SetOwnerAndName() has been
195 const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
197 // Returns the name of this mock method. Must be called after
198 // SetOwnerAndName() has been called.
199 const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
202 typedef std::vector<const void*> UntypedOnCallSpecs;
204 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
206 // Returns an Expectation object that references and co-owns exp,
207 // which must be an expectation on this mock function.
208 Expectation GetHandleOf(ExpectationBase* exp);
210 // Address of the mock object this mock method belongs to. Only
211 // valid after this mock method has been called or
212 // ON_CALL/EXPECT_CALL has been invoked on it.
213 const void* mock_obj_; // Protected by g_gmock_mutex.
215 // Name of the function being mocked. Only valid after this mock
216 // method has been called.
217 const char* name_; // Protected by g_gmock_mutex.
219 // All default action specs for this function mocker.
220 UntypedOnCallSpecs untyped_on_call_specs_;
222 // All expectations for this function mocker.
224 // It's undefined behavior to interleave expectations (EXPECT_CALLs
225 // or ON_CALLs) and mock function calls. Also, the order of
226 // expectations is important. Therefore it's a logic race condition
227 // to read/write untyped_expectations_ concurrently. In order for
228 // tools like tsan to catch concurrent read/write accesses to
229 // untyped_expectations, we deliberately leave accesses to it
231 UntypedExpectations untyped_expectations_;
232 }; // class UntypedFunctionMockerBase
234 // Untyped base class for OnCallSpec<F>.
235 class UntypedOnCallSpecBase {
237 // The arguments are the location of the ON_CALL() statement.
238 UntypedOnCallSpecBase(const char* a_file, int a_line)
239 : file_(a_file), line_(a_line), last_clause_(kNone) {}
241 // Where in the source file was the default action spec defined?
242 const char* file() const { return file_; }
243 int line() const { return line_; }
246 // Gives each clause in the ON_CALL() statement a name.
248 // Do not change the order of the enum members! The run-time
249 // syntax checking relies on it.
255 // Asserts that the ON_CALL() statement has a certain property.
256 void AssertSpecProperty(bool property,
257 const std::string& failure_message) const {
258 Assert(property, file_, line_, failure_message);
261 // Expects that the ON_CALL() statement has a certain property.
262 void ExpectSpecProperty(bool property,
263 const std::string& failure_message) const {
264 Expect(property, file_, line_, failure_message);
270 // The last clause in the ON_CALL() statement as seen so far.
271 // Initially kNone and changes as the statement is parsed.
273 }; // class UntypedOnCallSpecBase
275 // This template class implements an ON_CALL spec.
276 template <typename F>
277 class OnCallSpec : public UntypedOnCallSpecBase {
279 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
280 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
282 // Constructs an OnCallSpec object from the information inside
283 // the parenthesis of an ON_CALL() statement.
284 OnCallSpec(const char* a_file, int a_line,
285 const ArgumentMatcherTuple& matchers)
286 : UntypedOnCallSpecBase(a_file, a_line),
288 // By default, extra_matcher_ should match anything. However,
289 // we cannot initialize it with _ as that causes ambiguity between
290 // Matcher's copy and move constructor for some argument types.
291 extra_matcher_(A<const ArgumentTuple&>()) {}
293 // Implements the .With() clause.
294 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
295 // Makes sure this is called at most once.
296 ExpectSpecProperty(last_clause_ < kWith,
297 ".With() cannot appear "
298 "more than once in an ON_CALL().");
299 last_clause_ = kWith;
305 // Implements the .WillByDefault() clause.
306 OnCallSpec& WillByDefault(const Action<F>& action) {
307 ExpectSpecProperty(last_clause_ < kWillByDefault,
308 ".WillByDefault() must appear "
309 "exactly once in an ON_CALL().");
310 last_clause_ = kWillByDefault;
312 ExpectSpecProperty(!action.IsDoDefault(),
313 "DoDefault() cannot be used in ON_CALL().");
318 // Returns true if and only if the given arguments match the matchers.
319 bool Matches(const ArgumentTuple& args) const {
320 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
323 // Returns the action specified by the user.
324 const Action<F>& GetAction() const {
325 AssertSpecProperty(last_clause_ == kWillByDefault,
326 ".WillByDefault() must appear exactly "
327 "once in an ON_CALL().");
332 // The information in statement
334 // ON_CALL(mock_object, Method(matchers))
335 // .With(multi-argument-matcher)
336 // .WillByDefault(action);
338 // is recorded in the data members like this:
340 // source file that contains the statement => file_
341 // line number of the statement => line_
342 // matchers => matchers_
343 // multi-argument-matcher => extra_matcher_
345 ArgumentMatcherTuple matchers_;
346 Matcher<const ArgumentTuple&> extra_matcher_;
348 }; // class OnCallSpec
350 // Possible reactions on uninteresting calls.
357 } // namespace internal
359 // Utilities for manipulating mock objects.
360 class GTEST_API_ Mock {
362 // The following public methods can be called concurrently.
364 // Tells Google Mock to ignore mock_obj when checking for leaked
366 static void AllowLeak(const void* mock_obj)
367 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
369 // Verifies and clears all expectations on the given mock object.
370 // If the expectations aren't satisfied, generates one or more
371 // Google Test non-fatal failures and returns false.
372 static bool VerifyAndClearExpectations(void* mock_obj)
373 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
375 // Verifies all expectations on the given mock object and clears its
376 // default actions and expectations. Returns true if and only if the
377 // verification was successful.
378 static bool VerifyAndClear(void* mock_obj)
379 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
381 // Returns whether the mock was created as a naggy mock (default)
382 static bool IsNaggy(void* mock_obj)
383 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
384 // Returns whether the mock was created as a nice mock
385 static bool IsNice(void* mock_obj)
386 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
387 // Returns whether the mock was created as a strict mock
388 static bool IsStrict(void* mock_obj)
389 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
392 friend class internal::UntypedFunctionMockerBase;
394 // Needed for a function mocker to register itself (so that we know
395 // how to clear a mock object).
396 template <typename F>
397 friend class internal::FunctionMocker;
399 template <typename MockClass>
400 friend class internal::NiceMockImpl;
401 template <typename MockClass>
402 friend class internal::NaggyMockImpl;
403 template <typename MockClass>
404 friend class internal::StrictMockImpl;
406 // Tells Google Mock to allow uninteresting calls on the given mock
408 static void AllowUninterestingCalls(uintptr_t mock_obj)
409 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
411 // Tells Google Mock to warn the user about uninteresting calls on
412 // the given mock object.
413 static void WarnUninterestingCalls(uintptr_t mock_obj)
414 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
416 // Tells Google Mock to fail uninteresting calls on the given mock
418 static void FailUninterestingCalls(uintptr_t mock_obj)
419 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
421 // Tells Google Mock the given mock object is being destroyed and
422 // its entry in the call-reaction table should be removed.
423 static void UnregisterCallReaction(uintptr_t mock_obj)
424 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
426 // Returns the reaction Google Mock will have on uninteresting calls
427 // made on the given mock object.
428 static internal::CallReaction GetReactionOnUninterestingCalls(
429 const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
431 // Verifies that all expectations on the given mock object have been
432 // satisfied. Reports one or more Google Test non-fatal failures
433 // and returns false if not.
434 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
435 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
437 // Clears all ON_CALL()s set on the given mock object.
438 static void ClearDefaultActionsLocked(void* mock_obj)
439 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
441 // Registers a mock object and a mock method it owns.
442 static void Register(const void* mock_obj,
443 internal::UntypedFunctionMockerBase* mocker)
444 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
446 // Tells Google Mock where in the source code mock_obj is used in an
447 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
448 // information helps the user identify which object it is.
449 static void RegisterUseByOnCallOrExpectCall(const void* mock_obj,
450 const char* file, int line)
451 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
453 // Unregisters a mock method; removes the owning mock object from
454 // the registry when the last mock method associated with it has
455 // been unregistered. This is called only in the destructor of
457 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
458 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
461 // An abstract handle of an expectation. Useful in the .After()
462 // clause of EXPECT_CALL() for setting the (partial) order of
463 // expectations. The syntax:
465 // Expectation e1 = EXPECT_CALL(...)...;
466 // EXPECT_CALL(...).After(e1)...;
468 // sets two expectations where the latter can only be matched after
469 // the former has been satisfied.
472 // - This class is copyable and has value semantics.
473 // - Constness is shallow: a const Expectation object itself cannot
474 // be modified, but the mutable methods of the ExpectationBase
475 // object it references can be called via expectation_base().
477 class GTEST_API_ Expectation {
479 // Constructs a null object that doesn't reference any expectation.
481 Expectation(Expectation&&) = default;
482 Expectation(const Expectation&) = default;
483 Expectation& operator=(Expectation&&) = default;
484 Expectation& operator=(const Expectation&) = default;
487 // This single-argument ctor must not be explicit, in order to support the
488 // Expectation e = EXPECT_CALL(...);
491 // A TypedExpectation object stores its pre-requisites as
492 // Expectation objects, and needs to call the non-const Retire()
493 // method on the ExpectationBase objects they reference. Therefore
494 // Expectation must receive a *non-const* reference to the
495 // ExpectationBase object.
496 Expectation(internal::ExpectationBase& exp); // NOLINT
498 // The compiler-generated copy ctor and operator= work exactly as
499 // intended, so we don't need to define our own.
501 // Returns true if and only if rhs references the same expectation as this
503 bool operator==(const Expectation& rhs) const {
504 return expectation_base_ == rhs.expectation_base_;
507 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
510 friend class ExpectationSet;
511 friend class Sequence;
512 friend class ::testing::internal::ExpectationBase;
513 friend class ::testing::internal::UntypedFunctionMockerBase;
515 template <typename F>
516 friend class ::testing::internal::FunctionMocker;
518 template <typename F>
519 friend class ::testing::internal::TypedExpectation;
521 // This comparator is needed for putting Expectation objects into a set.
524 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
525 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
529 typedef ::std::set<Expectation, Less> Set;
532 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
534 // Returns the expectation this object references.
535 const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
536 return expectation_base_;
539 // A shared_ptr that co-owns the expectation this handle references.
540 std::shared_ptr<internal::ExpectationBase> expectation_base_;
543 // A set of expectation handles. Useful in the .After() clause of
544 // EXPECT_CALL() for setting the (partial) order of expectations. The
547 // ExpectationSet es;
548 // es += EXPECT_CALL(...)...;
549 // es += EXPECT_CALL(...)...;
550 // EXPECT_CALL(...).After(es)...;
552 // sets three expectations where the last one can only be matched
553 // after the first two have both been satisfied.
555 // This class is copyable and has value semantics.
556 class ExpectationSet {
558 // A bidirectional iterator that can read a const element in the set.
559 typedef Expectation::Set::const_iterator const_iterator;
561 // An object stored in the set. This is an alias of Expectation.
562 typedef Expectation::Set::value_type value_type;
564 // Constructs an empty set.
567 // This single-argument ctor must not be explicit, in order to support the
568 // ExpectationSet es = EXPECT_CALL(...);
570 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
571 *this += Expectation(exp);
574 // This single-argument ctor implements implicit conversion from
575 // Expectation and thus must not be explicit. This allows either an
576 // Expectation or an ExpectationSet to be used in .After().
577 ExpectationSet(const Expectation& e) { // NOLINT
581 // The compiler-generator ctor and operator= works exactly as
582 // intended, so we don't need to define our own.
584 // Returns true if and only if rhs contains the same set of Expectation
585 // objects as this does.
586 bool operator==(const ExpectationSet& rhs) const {
587 return expectations_ == rhs.expectations_;
590 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
592 // Implements the syntax
593 // expectation_set += EXPECT_CALL(...);
594 ExpectationSet& operator+=(const Expectation& e) {
595 expectations_.insert(e);
599 int size() const { return static_cast<int>(expectations_.size()); }
601 const_iterator begin() const { return expectations_.begin(); }
602 const_iterator end() const { return expectations_.end(); }
605 Expectation::Set expectations_;
608 // Sequence objects are used by a user to specify the relative order
609 // in which the expectations should match. They are copyable (we rely
610 // on the compiler-defined copy constructor and assignment operator).
611 class GTEST_API_ Sequence {
613 // Constructs an empty sequence.
614 Sequence() : last_expectation_(new Expectation) {}
616 // Adds an expectation to this sequence. The caller must ensure
617 // that no other thread is accessing this Sequence object.
618 void AddExpectation(const Expectation& expectation) const;
621 // The last expectation in this sequence.
622 std::shared_ptr<Expectation> last_expectation_;
625 // An object of this type causes all EXPECT_CALL() statements
626 // encountered in its scope to be put in an anonymous sequence. The
627 // work is done in the constructor and destructor. You should only
628 // create an InSequence object on the stack.
630 // The sole purpose for this class is to support easy definition of
631 // sequential expectations, e.g.
634 // InSequence dummy; // The name of the object doesn't matter.
636 // // The following expectations must match in the order they appear.
637 // EXPECT_CALL(a, Bar())...;
638 // EXPECT_CALL(a, Baz())...;
640 // EXPECT_CALL(b, Xyz())...;
643 // You can create InSequence objects in multiple threads, as long as
644 // they are used to affect different mock objects. The idea is that
645 // each thread can create and set up its own mocks as if it's the only
646 // thread. However, for clarity of your tests we recommend you to set
647 // up mocks in the main thread unless you have a good reason not to do
649 class GTEST_API_ InSequence {
655 bool sequence_created_;
657 InSequence(const InSequence&) = delete;
658 InSequence& operator=(const InSequence&) = delete;
659 } GTEST_ATTRIBUTE_UNUSED_;
663 // Points to the implicit sequence introduced by a living InSequence
664 // object (if any) in the current thread or NULL.
665 GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
667 // Base class for implementing expectations.
669 // There are two reasons for having a type-agnostic base class for
672 // 1. We need to store collections of expectations of different
673 // types (e.g. all pre-requisites of a particular expectation, all
674 // expectations in a sequence). Therefore these expectation objects
675 // must share a common base class.
677 // 2. We can avoid binary code bloat by moving methods not depending
678 // on the template argument of Expectation to the base class.
680 // This class is internal and mustn't be used by user code directly.
681 class GTEST_API_ ExpectationBase {
683 // source_text is the EXPECT_CALL(...) source that created this Expectation.
684 ExpectationBase(const char* file, int line, const std::string& source_text);
686 virtual ~ExpectationBase();
688 // Where in the source file was the expectation spec defined?
689 const char* file() const { return file_; }
690 int line() const { return line_; }
691 const char* source_text() const { return source_text_.c_str(); }
692 // Returns the cardinality specified in the expectation spec.
693 const Cardinality& cardinality() const { return cardinality_; }
695 // Describes the source file location of this expectation.
696 void DescribeLocationTo(::std::ostream* os) const {
697 *os << FormatFileLocation(file(), line()) << " ";
700 // Describes how many times a function call matching this
701 // expectation has occurred.
702 void DescribeCallCountTo(::std::ostream* os) const
703 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
705 // If this mock method has an extra matcher (i.e. .With(matcher)),
706 // describes it to the ostream.
707 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
710 friend class ::testing::Expectation;
711 friend class UntypedFunctionMockerBase;
714 // Don't change the order of the enum members!
725 typedef std::vector<const void*> UntypedActions;
727 // Returns an Expectation object that references and co-owns this
729 virtual Expectation GetHandle() = 0;
731 // Asserts that the EXPECT_CALL() statement has the given property.
732 void AssertSpecProperty(bool property,
733 const std::string& failure_message) const {
734 Assert(property, file_, line_, failure_message);
737 // Expects that the EXPECT_CALL() statement has the given property.
738 void ExpectSpecProperty(bool property,
739 const std::string& failure_message) const {
740 Expect(property, file_, line_, failure_message);
743 // Explicitly specifies the cardinality of this expectation. Used
744 // by the subclasses to implement the .Times() clause.
745 void SpecifyCardinality(const Cardinality& cardinality);
747 // Returns true if and only if the user specified the cardinality
748 // explicitly using a .Times().
749 bool cardinality_specified() const { return cardinality_specified_; }
751 // Sets the cardinality of this expectation spec.
752 void set_cardinality(const Cardinality& a_cardinality) {
753 cardinality_ = a_cardinality;
756 // The following group of methods should only be called after the
757 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
758 // the current thread.
760 // Retires all pre-requisites of this expectation.
761 void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
763 // Returns true if and only if this expectation is retired.
764 bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
765 g_gmock_mutex.AssertHeld();
769 // Retires this expectation.
770 void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
771 g_gmock_mutex.AssertHeld();
775 // Returns true if and only if this expectation is satisfied.
776 bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
777 g_gmock_mutex.AssertHeld();
778 return cardinality().IsSatisfiedByCallCount(call_count_);
781 // Returns true if and only if this expectation is saturated.
782 bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
783 g_gmock_mutex.AssertHeld();
784 return cardinality().IsSaturatedByCallCount(call_count_);
787 // Returns true if and only if this expectation is over-saturated.
788 bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
789 g_gmock_mutex.AssertHeld();
790 return cardinality().IsOverSaturatedByCallCount(call_count_);
793 // Returns true if and only if all pre-requisites of this expectation are
795 bool AllPrerequisitesAreSatisfied() const
796 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
798 // Adds unsatisfied pre-requisites of this expectation to 'result'.
799 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
800 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
802 // Returns the number this expectation has been invoked.
803 int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
804 g_gmock_mutex.AssertHeld();
808 // Increments the number this expectation has been invoked.
809 void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
810 g_gmock_mutex.AssertHeld();
814 // Checks the action count (i.e. the number of WillOnce() and
815 // WillRepeatedly() clauses) against the cardinality if this hasn't
816 // been done before. Prints a warning if there are too many or too
818 void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);
820 friend class ::testing::Sequence;
821 friend class ::testing::internal::ExpectationTester;
823 template <typename Function>
824 friend class TypedExpectation;
826 // Implements the .Times() clause.
827 void UntypedTimes(const Cardinality& a_cardinality);
829 // This group of fields are part of the spec and won't change after
830 // an EXPECT_CALL() statement finishes.
831 const char* file_; // The file that contains the expectation.
832 int line_; // The line number of the expectation.
833 const std::string source_text_; // The EXPECT_CALL(...) source text.
834 // True if and only if the cardinality is specified explicitly.
835 bool cardinality_specified_;
836 Cardinality cardinality_; // The cardinality of the expectation.
837 // The immediate pre-requisites (i.e. expectations that must be
838 // satisfied before this expectation can be matched) of this
839 // expectation. We use std::shared_ptr in the set because we want an
840 // Expectation object to be co-owned by its FunctionMocker and its
841 // successors. This allows multiple mock objects to be deleted at
843 ExpectationSet immediate_prerequisites_;
845 // This group of fields are the current state of the expectation,
846 // and can change as the mock function is called.
847 int call_count_; // How many times this expectation has been invoked.
848 bool retired_; // True if and only if this expectation has retired.
849 UntypedActions untyped_actions_;
850 bool extra_matcher_specified_;
851 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
852 bool retires_on_saturation_;
854 mutable bool action_count_checked_; // Under mutex_.
855 mutable Mutex mutex_; // Protects action_count_checked_.
856 }; // class ExpectationBase
858 template <typename F>
859 class TypedExpectation;
861 // Implements an expectation for the given function type.
862 template <typename R, typename... Args>
863 class TypedExpectation<R(Args...)> : public ExpectationBase {
865 using F = R(Args...);
868 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
869 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
870 typedef typename Function<F>::Result Result;
872 TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
873 const std::string& a_source_text,
874 const ArgumentMatcherTuple& m)
875 : ExpectationBase(a_file, a_line, a_source_text),
878 // By default, extra_matcher_ should match anything. However,
879 // we cannot initialize it with _ as that causes ambiguity between
880 // Matcher's copy and move constructor for some argument types.
881 extra_matcher_(A<const ArgumentTuple&>()),
882 repeated_action_(DoDefault()) {}
884 ~TypedExpectation() override {
885 // Check the validity of the action count if it hasn't been done
886 // yet (for example, if the expectation was never used).
887 CheckActionCountIfNotDone();
888 for (UntypedActions::const_iterator it = untyped_actions_.begin();
889 it != untyped_actions_.end(); ++it) {
890 delete static_cast<const Action<F>*>(*it);
894 // Implements the .With() clause.
895 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
896 if (last_clause_ == kWith) {
897 ExpectSpecProperty(false,
898 ".With() cannot appear "
899 "more than once in an EXPECT_CALL().");
901 ExpectSpecProperty(last_clause_ < kWith,
902 ".With() must be the first "
903 "clause in an EXPECT_CALL().");
905 last_clause_ = kWith;
908 extra_matcher_specified_ = true;
912 // Implements the .Times() clause.
913 TypedExpectation& Times(const Cardinality& a_cardinality) {
914 ExpectationBase::UntypedTimes(a_cardinality);
918 // Implements the .Times() clause.
919 TypedExpectation& Times(int n) { return Times(Exactly(n)); }
921 // Implements the .InSequence() clause.
922 TypedExpectation& InSequence(const Sequence& s) {
923 ExpectSpecProperty(last_clause_ <= kInSequence,
924 ".InSequence() cannot appear after .After(),"
925 " .WillOnce(), .WillRepeatedly(), or "
926 ".RetiresOnSaturation().");
927 last_clause_ = kInSequence;
929 s.AddExpectation(GetHandle());
932 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
933 return InSequence(s1).InSequence(s2);
935 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
936 const Sequence& s3) {
937 return InSequence(s1, s2).InSequence(s3);
939 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
940 const Sequence& s3, const Sequence& s4) {
941 return InSequence(s1, s2, s3).InSequence(s4);
943 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
944 const Sequence& s3, const Sequence& s4,
945 const Sequence& s5) {
946 return InSequence(s1, s2, s3, s4).InSequence(s5);
949 // Implements that .After() clause.
950 TypedExpectation& After(const ExpectationSet& s) {
951 ExpectSpecProperty(last_clause_ <= kAfter,
952 ".After() cannot appear after .WillOnce(),"
953 " .WillRepeatedly(), or "
954 ".RetiresOnSaturation().");
955 last_clause_ = kAfter;
957 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
958 immediate_prerequisites_ += *it;
962 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
963 return After(s1).After(s2);
965 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
966 const ExpectationSet& s3) {
967 return After(s1, s2).After(s3);
969 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
970 const ExpectationSet& s3, const ExpectationSet& s4) {
971 return After(s1, s2, s3).After(s4);
973 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
974 const ExpectationSet& s3, const ExpectationSet& s4,
975 const ExpectationSet& s5) {
976 return After(s1, s2, s3, s4).After(s5);
979 // Preferred, type-safe overload: consume anything that can be directly
980 // converted to a OnceAction, except for Action<F> objects themselves.
981 TypedExpectation& WillOnce(OnceAction<F> once_action) {
982 // Call the overload below, smuggling the OnceAction as a copyable callable.
983 // We know this is safe because a WillOnce action will not be called more
985 return WillOnce(Action<F>(ActionAdaptor{
986 std::make_shared<OnceAction<F>>(std::move(once_action)),
990 // Fallback overload: accept Action<F> objects and those actions that define
991 // `operator Action<F>` but not `operator OnceAction<F>`.
993 // This is templated in order to cause the overload above to be preferred
994 // when the input is convertible to either type.
995 template <int&... ExplicitArgumentBarrier, typename = void>
996 TypedExpectation& WillOnce(Action<F> action) {
997 ExpectSpecProperty(last_clause_ <= kWillOnce,
998 ".WillOnce() cannot appear after "
999 ".WillRepeatedly() or .RetiresOnSaturation().");
1000 last_clause_ = kWillOnce;
1002 untyped_actions_.push_back(new Action<F>(std::move(action)));
1004 if (!cardinality_specified()) {
1005 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
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().");
1017 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1018 ".WillRepeatedly() cannot appear "
1019 "after .RetiresOnSaturation().");
1021 last_clause_ = kWillRepeatedly;
1022 repeated_action_specified_ = true;
1024 repeated_action_ = action;
1025 if (!cardinality_specified()) {
1026 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1029 // Now that no more action clauses can be specified, we check
1030 // whether their count makes sense.
1031 CheckActionCountIfNotDone();
1035 // Implements the .RetiresOnSaturation() clause.
1036 TypedExpectation& RetiresOnSaturation() {
1037 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1038 ".RetiresOnSaturation() cannot appear "
1040 last_clause_ = kRetiresOnSaturation;
1041 retires_on_saturation_ = true;
1043 // Now that no more action clauses can be specified, we check
1044 // whether their count makes sense.
1045 CheckActionCountIfNotDone();
1049 // Returns the matchers for the arguments as specified inside the
1050 // EXPECT_CALL() macro.
1051 const ArgumentMatcherTuple& matchers() const { return matchers_; }
1053 // Returns the matcher specified by the .With() clause.
1054 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1055 return extra_matcher_;
1058 // Returns the action specified by the .WillRepeatedly() clause.
1059 const Action<F>& repeated_action() const { return repeated_action_; }
1061 // If this mock method has an extra matcher (i.e. .With(matcher)),
1062 // describes it to the ostream.
1063 void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
1064 if (extra_matcher_specified_) {
1065 *os << " Expected args: ";
1066 extra_matcher_.DescribeTo(os);
1072 template <typename Function>
1073 friend class FunctionMocker;
1075 // An adaptor that turns a OneAction<F> into something compatible with
1076 // Action<F>. Must be called at most once.
1077 struct ActionAdaptor {
1078 std::shared_ptr<OnceAction<R(Args...)>> once_action;
1080 R operator()(Args&&... args) const {
1081 return std::move(*once_action).Call(std::forward<Args>(args)...);
1085 // Returns an Expectation object that references and co-owns this
1087 Expectation GetHandle() override { return owner_->GetHandleOf(this); }
1089 // The following methods will be called only after the EXPECT_CALL()
1090 // statement finishes and when the current thread holds
1093 // Returns true if and only if this expectation matches the given arguments.
1094 bool Matches(const ArgumentTuple& args) const
1095 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1096 g_gmock_mutex.AssertHeld();
1097 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1100 // Returns true if and only if this expectation should handle the given
1102 bool ShouldHandleArguments(const ArgumentTuple& args) const
1103 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1104 g_gmock_mutex.AssertHeld();
1106 // In case the action count wasn't checked when the expectation
1107 // was defined (e.g. if this expectation has no WillRepeatedly()
1108 // or RetiresOnSaturation() clause), we check it when the
1109 // expectation is used for the first time.
1110 CheckActionCountIfNotDone();
1111 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1114 // Describes the result of matching the arguments against this
1115 // expectation to the given ostream.
1116 void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const
1117 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1118 g_gmock_mutex.AssertHeld();
1121 *os << " Expected: the expectation is active\n"
1122 << " Actual: it is retired\n";
1123 } else if (!Matches(args)) {
1124 if (!TupleMatches(matchers_, args)) {
1125 ExplainMatchFailureTupleTo(matchers_, args, os);
1127 StringMatchResultListener listener;
1128 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1129 *os << " Expected args: ";
1130 extra_matcher_.DescribeTo(os);
1131 *os << "\n Actual: don't match";
1133 internal::PrintIfNotEmpty(listener.str(), os);
1136 } else if (!AllPrerequisitesAreSatisfied()) {
1137 *os << " Expected: all pre-requisites are satisfied\n"
1138 << " Actual: the following immediate pre-requisites "
1139 << "are not satisfied:\n";
1140 ExpectationSet unsatisfied_prereqs;
1141 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1143 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1144 it != unsatisfied_prereqs.end(); ++it) {
1145 it->expectation_base()->DescribeLocationTo(os);
1146 *os << "pre-requisite #" << i++ << "\n";
1148 *os << " (end of pre-requisites)\n";
1150 // This line is here just for completeness' sake. It will never
1151 // be executed as currently the ExplainMatchResultTo() function
1152 // is called only when the mock function call does NOT match the
1154 *os << "The call matches the expectation.\n";
1158 // Returns the action that should be taken for the current invocation.
1159 const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
1160 const ArgumentTuple& args) const
1161 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1162 g_gmock_mutex.AssertHeld();
1163 const int count = call_count();
1164 Assert(count >= 1, __FILE__, __LINE__,
1165 "call_count() is <= 0 when GetCurrentAction() is "
1166 "called - this should never happen.");
1168 const int action_count = static_cast<int>(untyped_actions_.size());
1169 if (action_count > 0 && !repeated_action_specified_ &&
1170 count > action_count) {
1171 // If there is at least one WillOnce() and no WillRepeatedly(),
1172 // we warn the user when the WillOnce() clauses ran out.
1173 ::std::stringstream ss;
1174 DescribeLocationTo(&ss);
1175 ss << "Actions ran out in " << source_text() << "...\n"
1176 << "Called " << count << " times, but only " << action_count
1177 << " WillOnce()" << (action_count == 1 ? " is" : "s are")
1179 mocker->DescribeDefaultActionTo(args, &ss);
1180 Log(kWarning, ss.str(), 1);
1183 return count <= action_count
1184 ? *static_cast<const Action<F>*>(
1185 untyped_actions_[static_cast<size_t>(count - 1)])
1186 : repeated_action();
1189 // Given the arguments of a mock function call, if the call will
1190 // over-saturate this expectation, returns the default action;
1191 // otherwise, returns the next action in this expectation. Also
1192 // describes *what* happened to 'what', and explains *why* Google
1193 // Mock does it to 'why'. This method is not const as it calls
1194 // IncrementCallCount(). A return value of NULL means the default
1196 const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
1197 const ArgumentTuple& args,
1198 ::std::ostream* what,
1199 ::std::ostream* why)
1200 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1201 g_gmock_mutex.AssertHeld();
1202 if (IsSaturated()) {
1203 // We have an excessive call.
1204 IncrementCallCount();
1205 *what << "Mock function called more times than expected - ";
1206 mocker->DescribeDefaultActionTo(args, what);
1207 DescribeCallCountTo(why);
1212 IncrementCallCount();
1213 RetireAllPreRequisites();
1215 if (retires_on_saturation_ && IsSaturated()) {
1219 // Must be done after IncrementCount()!
1220 *what << "Mock function call matches " << source_text() << "...\n";
1221 return &(GetCurrentAction(mocker, args));
1224 // All the fields below won't change once the EXPECT_CALL()
1225 // statement finishes.
1226 FunctionMocker<F>* const owner_;
1227 ArgumentMatcherTuple matchers_;
1228 Matcher<const ArgumentTuple&> extra_matcher_;
1229 Action<F> repeated_action_;
1231 TypedExpectation(const TypedExpectation&) = delete;
1232 TypedExpectation& operator=(const TypedExpectation&) = delete;
1233 }; // class TypedExpectation
1235 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1236 // specifying the default behavior of, or expectation on, a mock
1239 // Note: class MockSpec really belongs to the ::testing namespace.
1240 // However if we define it in ::testing, MSVC will complain when
1241 // classes in ::testing::internal declare it as a friend class
1242 // template. To workaround this compiler bug, we define MockSpec in
1243 // ::testing::internal and import it into ::testing.
1245 // Logs a message including file and line number information.
1246 GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1247 const char* file, int line,
1248 const std::string& message);
1250 template <typename F>
1253 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1255 typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1257 // Constructs a MockSpec object, given the function mocker object
1258 // that the spec is associated with.
1259 MockSpec(internal::FunctionMocker<F>* function_mocker,
1260 const ArgumentMatcherTuple& matchers)
1261 : function_mocker_(function_mocker), matchers_(matchers) {}
1263 // Adds a new default action spec to the function mocker and returns
1264 // the newly created spec.
1265 internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,
1266 int line, const char* obj,
1268 LogWithLocation(internal::kInfo, file, line,
1269 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
1270 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1273 // Adds a new expectation spec to the function mocker and returns
1274 // the newly created spec.
1275 internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line,
1278 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1280 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1281 return function_mocker_->AddNewExpectation(file, line, source_text,
1285 // This operator overload is used to swallow the superfluous parameter list
1286 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1288 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1293 template <typename Function>
1294 friend class internal::FunctionMocker;
1296 // The function mocker that owns this spec.
1297 internal::FunctionMocker<F>* const function_mocker_;
1298 // The argument matchers specified in the spec.
1299 ArgumentMatcherTuple matchers_;
1300 }; // class MockSpec
1302 // Wrapper type for generically holding an ordinary value or lvalue reference.
1303 // If T is not a reference type, it must be copyable or movable.
1304 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1305 // T is a move-only value type (which means that it will always be copyable
1306 // if the current platform does not support move semantics).
1308 // The primary template defines handling for values, but function header
1309 // comments describe the contract for the whole template (including
1310 // specializations).
1311 template <typename T>
1312 class ReferenceOrValueWrapper {
1314 // Constructs a wrapper from the given value/reference.
1315 explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}
1317 // Unwraps and returns the underlying value/reference, exactly as
1318 // originally passed. The behavior of calling this more than once on
1319 // the same object is unspecified.
1320 T Unwrap() { return std::move(value_); }
1322 // Provides nondestructive access to the underlying value/reference.
1323 // Always returns a const reference (more precisely,
1324 // const std::add_lvalue_reference<T>::type). The behavior of calling this
1325 // after calling Unwrap on the same object is unspecified.
1326 const T& Peek() const { return value_; }
1332 // Specialization for lvalue reference types. See primary template
1333 // for documentation.
1334 template <typename T>
1335 class ReferenceOrValueWrapper<T&> {
1337 // Workaround for debatable pass-by-reference lint warning (c-library-team
1338 // policy precludes NOLINT in this context)
1339 typedef T& reference;
1340 explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
1341 T& Unwrap() { return *value_ptr_; }
1342 const T& Peek() const { return *value_ptr_; }
1348 // Prints the held value as an action's result to os.
1349 template <typename T>
1350 void PrintAsActionResult(const T& result, std::ostream& os) {
1351 os << "\n Returns: ";
1352 // T may be a reference type, so we don't use UniversalPrint().
1353 UniversalPrinter<T>::Print(result, &os);
1356 // Reports an uninteresting call (whose description is in msg) in the
1357 // manner specified by 'reaction'.
1358 GTEST_API_ void ReportUninterestingCall(CallReaction reaction,
1359 const std::string& msg);
1361 // A generic RAII type that runs a user-provided function in its destructor.
1362 class Cleanup final {
1364 explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}
1365 ~Cleanup() { f_(); }
1368 std::function<void()> f_;
1371 template <typename F>
1372 class FunctionMocker;
1374 template <typename R, typename... Args>
1375 class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
1376 using F = R(Args...);
1380 using ArgumentTuple = std::tuple<Args...>;
1381 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1385 // There is no generally useful and implementable semantics of
1386 // copying a mock object, so copying a mock is usually a user error.
1387 // Thus we disallow copying function mockers. If the user really
1388 // wants to copy a mock object, they should implement their own copy
1389 // operation, for example:
1391 // class MockFoo : public Foo {
1393 // // Defines a copy constructor explicitly.
1394 // MockFoo(const MockFoo& src) {}
1397 FunctionMocker(const FunctionMocker&) = delete;
1398 FunctionMocker& operator=(const FunctionMocker&) = delete;
1400 // The destructor verifies that all expectations on this mock
1401 // function have been satisfied. If not, it will report Google Test
1402 // non-fatal failures for the violations.
1403 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1404 MutexLock l(&g_gmock_mutex);
1405 VerifyAndClearExpectationsLocked();
1406 Mock::UnregisterLocked(this);
1407 ClearDefaultActionsLocked();
1410 // Returns the ON_CALL spec that matches this mock function with the
1411 // given arguments; returns NULL if no matching ON_CALL is found.
1413 const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {
1414 for (UntypedOnCallSpecs::const_reverse_iterator it =
1415 untyped_on_call_specs_.rbegin();
1416 it != untyped_on_call_specs_.rend(); ++it) {
1417 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1418 if (spec->Matches(args)) return spec;
1424 // Performs the default action of this mock function on the given
1425 // arguments and returns the result. Asserts (or throws if
1426 // exceptions are enabled) with a helpful call description if there
1427 // is no valid return value. This method doesn't depend on the
1428 // mutable state of this object, and thus can be called concurrently
1431 Result PerformDefaultAction(ArgumentTuple&& args,
1432 const std::string& call_description) const {
1433 const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);
1434 if (spec != nullptr) {
1435 return spec->GetAction().Perform(std::move(args));
1437 const std::string message =
1439 "\n The mock function has no default action "
1440 "set, and its return type has no default value set.";
1441 #if GTEST_HAS_EXCEPTIONS
1442 if (!DefaultValue<Result>::Exists()) {
1443 throw std::runtime_error(message);
1446 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1448 return DefaultValue<Result>::Get();
1451 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1452 // clears the ON_CALL()s set on this mock function.
1453 void ClearDefaultActionsLocked() override
1454 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1455 g_gmock_mutex.AssertHeld();
1457 // Deleting our default actions may trigger other mock objects to be
1458 // deleted, for example if an action contains a reference counted smart
1459 // pointer to that mock object, and that is the last reference. So if we
1460 // delete our actions within the context of the global mutex we may deadlock
1461 // when this method is called again. Instead, make a copy of the set of
1462 // actions to delete, clear our set within the mutex, and then delete the
1463 // actions outside of the mutex.
1464 UntypedOnCallSpecs specs_to_delete;
1465 untyped_on_call_specs_.swap(specs_to_delete);
1467 g_gmock_mutex.Unlock();
1468 for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
1469 it != specs_to_delete.end(); ++it) {
1470 delete static_cast<const OnCallSpec<F>*>(*it);
1473 // Lock the mutex again, since the caller expects it to be locked when we
1475 g_gmock_mutex.Lock();
1478 // Returns the result of invoking this mock function with the given
1479 // arguments. This function can be safely called from multiple
1480 // threads concurrently.
1481 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1482 return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));
1485 MockSpec<F> With(Matcher<Args>... m) {
1486 return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
1490 template <typename Function>
1491 friend class MockSpec;
1493 // Adds and returns a default action spec for this mock function.
1494 OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,
1495 const ArgumentMatcherTuple& m)
1496 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1497 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1498 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1499 untyped_on_call_specs_.push_back(on_call_spec);
1500 return *on_call_spec;
1503 // Adds and returns an expectation spec for this mock function.
1504 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1505 const std::string& source_text,
1506 const ArgumentMatcherTuple& m)
1507 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1508 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1509 TypedExpectation<F>* const expectation =
1510 new TypedExpectation<F>(this, file, line, source_text, m);
1511 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1512 // See the definition of untyped_expectations_ for why access to
1513 // it is unprotected here.
1514 untyped_expectations_.push_back(untyped_expectation);
1516 // Adds this expectation into the implicit sequence if there is one.
1517 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1518 if (implicit_sequence != nullptr) {
1519 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1522 return *expectation;
1526 template <typename Func>
1527 friend class TypedExpectation;
1529 // Some utilities needed for implementing UntypedInvokeWith().
1531 // Describes what default action will be performed for the given
1534 void DescribeDefaultActionTo(const ArgumentTuple& args,
1535 ::std::ostream* os) const {
1536 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1538 if (spec == nullptr) {
1539 *os << (std::is_void<Result>::value ? "returning directly.\n"
1540 : "returning default value.\n");
1542 *os << "taking default action specified at:\n"
1543 << FormatFileLocation(spec->file(), spec->line()) << "\n";
1547 // Writes a message that the call is uninteresting (i.e. neither
1548 // explicitly expected nor explicitly unexpected) to the given
1550 void UntypedDescribeUninterestingCall(const void* untyped_args,
1551 ::std::ostream* os) const override
1552 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1553 const ArgumentTuple& args =
1554 *static_cast<const ArgumentTuple*>(untyped_args);
1555 *os << "Uninteresting mock function call - ";
1556 DescribeDefaultActionTo(args, os);
1557 *os << " Function call: " << Name();
1558 UniversalPrint(args, os);
1561 // Returns the expectation that matches the given function arguments
1562 // (or NULL is there's no match); when a match is found,
1563 // untyped_action is set to point to the action that should be
1564 // performed (or NULL if the action is "do default"), and
1565 // is_excessive is modified to indicate whether the call exceeds the
1568 // Critical section: We must find the matching expectation and the
1569 // corresponding action that needs to be taken in an ATOMIC
1570 // transaction. Otherwise another thread may call this mock
1571 // method in the middle and mess up the state.
1573 // However, performing the action has to be left out of the critical
1574 // section. The reason is that we have no control on what the
1575 // action does (it can invoke an arbitrary user function or even a
1576 // mock function) and excessive locking could cause a dead lock.
1577 const ExpectationBase* UntypedFindMatchingExpectation(
1578 const void* untyped_args, const void** untyped_action, bool* is_excessive,
1579 ::std::ostream* what, ::std::ostream* why) override
1580 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1581 const ArgumentTuple& args =
1582 *static_cast<const ArgumentTuple*>(untyped_args);
1583 MutexLock l(&g_gmock_mutex);
1584 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1585 if (exp == nullptr) { // A match wasn't found.
1586 this->FormatUnexpectedCallMessageLocked(args, what, why);
1590 // This line must be done before calling GetActionForArguments(),
1591 // which will increment the call count for *exp and thus affect
1592 // its saturation status.
1593 *is_excessive = exp->IsSaturated();
1594 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1595 if (action != nullptr && action->IsDoDefault())
1596 action = nullptr; // Normalize "do default" to NULL.
1597 *untyped_action = action;
1601 // Prints the given function arguments to the ostream.
1602 void UntypedPrintArgs(const void* untyped_args,
1603 ::std::ostream* os) const override {
1604 const ArgumentTuple& args =
1605 *static_cast<const ArgumentTuple*>(untyped_args);
1606 UniversalPrint(args, os);
1609 // Returns the expectation that matches the arguments, or NULL if no
1610 // expectation matches them.
1611 TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)
1612 const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1613 g_gmock_mutex.AssertHeld();
1614 // See the definition of untyped_expectations_ for why access to
1615 // it is unprotected here.
1616 for (typename UntypedExpectations::const_reverse_iterator it =
1617 untyped_expectations_.rbegin();
1618 it != untyped_expectations_.rend(); ++it) {
1619 TypedExpectation<F>* const exp =
1620 static_cast<TypedExpectation<F>*>(it->get());
1621 if (exp->ShouldHandleArguments(args)) {
1628 // Returns a message that the arguments don't match any expectation.
1629 void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,
1631 ::std::ostream* why) const
1632 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1633 g_gmock_mutex.AssertHeld();
1634 *os << "\nUnexpected mock function call - ";
1635 DescribeDefaultActionTo(args, os);
1636 PrintTriedExpectationsLocked(args, why);
1639 // Prints a list of expectations that have been tried against the
1640 // current mock function call.
1641 void PrintTriedExpectationsLocked(const ArgumentTuple& args,
1642 ::std::ostream* why) const
1643 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1644 g_gmock_mutex.AssertHeld();
1645 const size_t count = untyped_expectations_.size();
1646 *why << "Google Mock tried the following " << count << " "
1647 << (count == 1 ? "expectation, but it didn't match"
1648 : "expectations, but none matched")
1650 for (size_t i = 0; i < count; i++) {
1651 TypedExpectation<F>* const expectation =
1652 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1654 expectation->DescribeLocationTo(why);
1656 *why << "tried expectation #" << i << ": ";
1658 *why << expectation->source_text() << "...\n";
1659 expectation->ExplainMatchResultTo(args, why);
1660 expectation->DescribeCallCountTo(why);
1664 // Performs the given action (or the default if it's null) with the given
1665 // arguments and returns the action's result.
1667 R PerformAction(const void* untyped_action, ArgumentTuple&& args,
1668 const std::string& call_description) const {
1669 if (untyped_action == nullptr) {
1670 return PerformDefaultAction(std::move(args), call_description);
1673 // Make a copy of the action before performing it, in case the
1674 // action deletes the mock object (and thus deletes itself).
1675 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1676 return action.Perform(std::move(args));
1679 // Is it possible to store an object of the supplied type in a local variable
1680 // for the sake of printing it, then return it on to the caller?
1681 template <typename T>
1682 using can_print_result = internal::conjunction<
1683 // void can't be stored as an object (and we also don't need to print it).
1684 internal::negation<std::is_void<T>>,
1685 // Non-moveable types can't be returned on to the user, so there's no way
1686 // for us to intercept and print them.
1687 std::is_move_constructible<T>>;
1689 // Perform the supplied action, printing the result to os.
1690 template <typename T = R,
1691 typename std::enable_if<can_print_result<T>::value, int>::type = 0>
1692 R PerformActionAndPrintResult(const void* const untyped_action,
1693 ArgumentTuple&& args,
1694 const std::string& call_description,
1696 R result = PerformAction(untyped_action, std::move(args), call_description);
1698 PrintAsActionResult(result, os);
1699 return std::forward<R>(result);
1702 // An overload for when it's not possible to print the result. In this case we
1703 // simply perform the action.
1704 template <typename T = R,
1705 typename std::enable_if<
1706 internal::negation<can_print_result<T>>::value, int>::type = 0>
1707 R PerformActionAndPrintResult(const void* const untyped_action,
1708 ArgumentTuple&& args,
1709 const std::string& call_description,
1711 return PerformAction(untyped_action, std::move(args), call_description);
1714 // Returns the result of invoking this mock function with the given
1715 // arguments. This function can be safely called from multiple
1716 // threads concurrently.
1717 R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
1718 }; // class FunctionMocker
1720 // Calculates the result of invoking this mock function with the given
1721 // arguments, prints it, and returns it.
1722 template <typename R, typename... Args>
1723 R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
1724 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1725 // See the definition of untyped_expectations_ for why access to it
1726 // is unprotected here.
1727 if (untyped_expectations_.size() == 0) {
1728 // No expectation is set on this mock method - we have an
1729 // uninteresting call.
1731 // We must get Google Mock's reaction on uninteresting calls
1732 // made on this mock object BEFORE performing the action,
1733 // because the action may DELETE the mock object and make the
1734 // following expression meaningless.
1735 const CallReaction reaction =
1736 Mock::GetReactionOnUninterestingCalls(MockObject());
1738 // True if and only if we need to print this call's arguments and return
1739 // value. This definition must be kept in sync with
1740 // the behavior of ReportUninterestingCall().
1741 const bool need_to_report_uninteresting_call =
1742 // If the user allows this uninteresting call, we print it
1743 // only when they want informational messages.
1744 reaction == kAllow ? LogIsVisible(kInfo) :
1745 // If the user wants this to be a warning, we print
1746 // it only when they want to see warnings.
1748 ? LogIsVisible(kWarning)
1750 // Otherwise, the user wants this to be an error, and we
1751 // should always print detailed information in the error.
1754 if (!need_to_report_uninteresting_call) {
1755 // Perform the action without printing the call information.
1756 return this->PerformDefaultAction(
1757 std::move(args), "Function call: " + std::string(Name()));
1760 // Warns about the uninteresting call.
1761 ::std::stringstream ss;
1762 this->UntypedDescribeUninterestingCall(&args, &ss);
1764 // Perform the action, print the result, and then report the uninteresting
1767 // We use RAII to do the latter in case R is void or a non-moveable type. In
1768 // either case we can't assign it to a local variable.
1769 const Cleanup report_uninteresting_call(
1770 [&] { ReportUninterestingCall(reaction, ss.str()); });
1772 return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);
1775 bool is_excessive = false;
1776 ::std::stringstream ss;
1777 ::std::stringstream why;
1778 ::std::stringstream loc;
1779 const void* untyped_action = nullptr;
1781 // The UntypedFindMatchingExpectation() function acquires and
1782 // releases g_gmock_mutex.
1784 const ExpectationBase* const untyped_expectation =
1785 this->UntypedFindMatchingExpectation(&args, &untyped_action,
1786 &is_excessive, &ss, &why);
1787 const bool found = untyped_expectation != nullptr;
1789 // True if and only if we need to print the call's arguments
1790 // and return value.
1791 // This definition must be kept in sync with the uses of Expect()
1792 // and Log() in this function.
1793 const bool need_to_report_call =
1794 !found || is_excessive || LogIsVisible(kInfo);
1795 if (!need_to_report_call) {
1796 // Perform the action without printing the call information.
1797 return PerformAction(untyped_action, std::move(args), "");
1800 ss << " Function call: " << Name();
1801 this->UntypedPrintArgs(&args, &ss);
1803 // In case the action deletes a piece of the expectation, we
1804 // generate the message beforehand.
1805 if (found && !is_excessive) {
1806 untyped_expectation->DescribeLocationTo(&loc);
1809 // Perform the action, print the result, and then fail or log in whatever way
1812 // We use RAII to do the latter in case R is void or a non-moveable type. In
1813 // either case we can't assign it to a local variable.
1814 const Cleanup handle_failures([&] {
1815 ss << "\n" << why.str();
1818 // No expectation matches this call - reports a failure.
1819 Expect(false, nullptr, -1, ss.str());
1820 } else if (is_excessive) {
1821 // We had an upper-bound violation and the failure message is in ss.
1822 Expect(false, untyped_expectation->file(), untyped_expectation->line(),
1825 // We had an expected call and the matching expectation is
1827 Log(kInfo, loc.str() + ss.str(), 2);
1831 return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
1835 } // namespace internal
1837 namespace internal {
1839 template <typename F>
1842 template <typename R, typename... Args>
1843 class MockFunction<R(Args...)> {
1845 MockFunction(const MockFunction&) = delete;
1846 MockFunction& operator=(const MockFunction&) = delete;
1848 std::function<R(Args...)> AsStdFunction() {
1849 return [this](Args... args) -> R {
1850 return this->Call(std::forward<Args>(args)...);
1854 // Implementation detail: the expansion of the MOCK_METHOD macro.
1855 R Call(Args... args) {
1856 mock_.SetOwnerAndName(this, "Call");
1857 return mock_.Invoke(std::forward<Args>(args)...);
1860 MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1861 mock_.RegisterOwner(this);
1862 return mock_.With(std::move(m)...);
1865 MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {
1866 return this->gmock_Call(::testing::A<Args>()...);
1870 MockFunction() = default;
1871 ~MockFunction() = default;
1874 FunctionMocker<R(Args...)> mock_;
1878 The SignatureOf<F> struct is a meta-function returning function signature
1879 corresponding to the provided F argument.
1881 It makes use of MockFunction easier by allowing it to accept more F arguments
1882 than just function signatures.
1884 Specializations provided here cover a signature type itself and any template
1885 that can be parameterized with a signature, including std::function and
1889 template <typename F, typename = void>
1892 template <typename R, typename... Args>
1893 struct SignatureOf<R(Args...)> {
1894 using type = R(Args...);
1897 template <template <typename> class C, typename F>
1898 struct SignatureOf<C<F>,
1899 typename std::enable_if<std::is_function<F>::value>::type>
1900 : SignatureOf<F> {};
1902 template <typename F>
1903 using SignatureOfT = typename SignatureOf<F>::type;
1905 } // namespace internal
1907 // A MockFunction<F> type has one mock method whose type is
1908 // internal::SignatureOfT<F>. It is useful when you just want your
1909 // test code to emit some messages and have Google Mock verify the
1910 // right messages are sent (and perhaps at the right times). For
1911 // example, if you are exercising code:
1917 // and want to verify that Foo(1) and Foo(3) both invoke
1918 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1920 // TEST(FooTest, InvokesBarCorrectly) {
1922 // MockFunction<void(string check_point_name)> check;
1926 // EXPECT_CALL(mock, Bar("a"));
1927 // EXPECT_CALL(check, Call("1"));
1928 // EXPECT_CALL(check, Call("2"));
1929 // EXPECT_CALL(mock, Bar("a"));
1938 // The expectation spec says that the first Bar("a") must happen
1939 // before check point "1", the second Bar("a") must happen after check
1940 // point "2", and nothing should happen between the two check
1941 // points. The explicit check points make it easy to tell which
1942 // Bar("a") is called by which call to Foo().
1944 // MockFunction<F> can also be used to exercise code that accepts
1945 // std::function<internal::SignatureOfT<F>> callbacks. To do so, use
1946 // AsStdFunction() method to create std::function proxy forwarding to
1947 // original object's Call. Example:
1949 // TEST(FooTest, RunsCallbackWithBarArgument) {
1950 // MockFunction<int(string)> callback;
1951 // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1952 // Foo(callback.AsStdFunction());
1955 // The internal::SignatureOfT<F> indirection allows to use other types
1956 // than just function signature type. This is typically useful when
1957 // providing a mock for a predefined std::function type. Example:
1959 // using FilterPredicate = std::function<bool(string)>;
1960 // void MyFilterAlgorithm(FilterPredicate predicate);
1962 // TEST(FooTest, FilterPredicateAlwaysAccepts) {
1963 // MockFunction<FilterPredicate> predicateMock;
1964 // EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));
1965 // MyFilterAlgorithm(predicateMock.AsStdFunction());
1967 template <typename F>
1968 class MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {
1969 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
1975 // The style guide prohibits "using" statements in a namespace scope
1976 // inside a header file. However, the MockSpec class template is
1977 // meant to be defined in the ::testing namespace. The following line
1978 // is just a trick for working around a bug in MSVC 8.0, which cannot
1979 // handle it if we define MockSpec in ::testing.
1980 using internal::MockSpec;
1982 // Const(x) is a convenient function for obtaining a const reference
1983 // to x. This is useful for setting expectations on an overloaded
1984 // const mock method, e.g.
1986 // class MockFoo : public FooInterface {
1988 // MOCK_METHOD0(Bar, int());
1989 // MOCK_CONST_METHOD0(Bar, int&());
1993 // // Expects a call to non-const MockFoo::Bar().
1994 // EXPECT_CALL(foo, Bar());
1995 // // Expects a call to const MockFoo::Bar().
1996 // EXPECT_CALL(Const(foo), Bar());
1997 template <typename T>
1998 inline const T& Const(const T& x) {
2002 // Constructs an Expectation object that references and co-owns exp.
2003 inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
2004 : expectation_base_(exp.GetHandle().expectation_base()) {}
2006 } // namespace testing
2008 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
2010 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
2011 // required to avoid compile errors when the name of the method used in call is
2012 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
2013 // tests in internal/gmock-spec-builders_test.cc for more details.
2015 // This macro supports statements both with and without parameter matchers. If
2016 // the parameter list is omitted, gMock will accept any parameters, which allows
2017 // tests to be written that don't need to encode the number of method
2018 // parameter. This technique may only be used for non-overloaded methods.
2020 // // These are the same:
2021 // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
2022 // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
2025 // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
2026 // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
2028 // // Can also specify args if you want, of course:
2029 // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
2031 // // Overloads work as long as you specify parameters:
2032 // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
2033 // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
2035 // // Oops! Which overload did you want?
2036 // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
2037 // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
2039 // How this works: The mock class uses two overloads of the gmock_Method
2040 // expectation setter method plus an operator() overload on the MockSpec object.
2041 // In the matcher list form, the macro expands to:
2043 // // This statement:
2044 // ON_CALL(mock, TwoArgsMethod(_, 45))...
2046 // // ...expands to:
2047 // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
2048 // |-------------v---------------||------------v-------------|
2049 // invokes first overload swallowed by operator()
2051 // // ...which is essentially:
2052 // mock.gmock_TwoArgsMethod(_, 45)...
2054 // Whereas the form without a matcher list:
2056 // // This statement:
2057 // ON_CALL(mock, TwoArgsMethod)...
2059 // // ...expands to:
2060 // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
2061 // |-----------------------v--------------------------|
2062 // invokes second overload
2064 // // ...which is essentially:
2065 // mock.gmock_TwoArgsMethod(_, _)...
2067 // The WithoutMatchers() argument is used to disambiguate overloads and to
2068 // block the caller from accidentally invoking the second overload directly. The
2069 // second argument is an internal type derived from the method signature. The
2070 // failure to disambiguate two overloads of this method in the ON_CALL statement
2071 // is how we block callers from setting expectations on overloaded methods.
2072 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
2073 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
2075 .Setter(__FILE__, __LINE__, #mock_expr, #call)
2077 #define ON_CALL(obj, call) \
2078 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
2080 #define EXPECT_CALL(obj, call) \
2081 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
2083 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_