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 // GOOGLETEST_CM0002 DO NOT DELETE
60 // IWYU pragma: private, include "gmock/gmock.h"
61 // IWYU pragma: friend gmock/.*
63 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
64 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
72 #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
> class FunctionMocker
;
104 // Base class for expectations.
105 class ExpectationBase
;
107 // Implements an expectation.
108 template <typename F
> class TypedExpectation
;
110 // Helper class for testing the Expectation class template.
111 class ExpectationTester
;
113 // Protects the mock object registry (in class Mock), all function
114 // mockers, and all expectations.
116 // The reason we don't use more fine-grained protection is: when a
117 // mock function Foo() is called, it needs to consult its expectations
118 // to see which one should be picked. If another thread is allowed to
119 // call a mock function (either Foo() or a different one) at the same
120 // time, it could affect the "retired" attributes of Foo()'s
121 // expectations when InSequence() is used, and thus affect which
122 // expectation gets picked. Therefore, we sequence all mock function
123 // calls to ensure the integrity of the mock objects' states.
124 GTEST_API_
GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex
);
126 // Untyped base class for ActionResultHolder<R>.
127 class UntypedActionResultHolderBase
;
129 // Abstract base class of FunctionMocker. This is the
130 // type-agnostic part of the function mocker interface. Its pure
131 // virtual methods are implemented by FunctionMocker.
132 class GTEST_API_ UntypedFunctionMockerBase
{
134 UntypedFunctionMockerBase();
135 virtual ~UntypedFunctionMockerBase();
137 // Verifies that all expectations on this mock function have been
138 // satisfied. Reports one or more Google Test non-fatal failures
139 // and returns false if not.
140 bool VerifyAndClearExpectationsLocked()
141 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
143 // Clears the ON_CALL()s set on this mock function.
144 virtual void ClearDefaultActionsLocked()
145 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) = 0;
147 // In all of the following Untyped* functions, it's the caller's
148 // responsibility to guarantee the correctness of the arguments'
151 // Performs the default action with the given arguments and returns
152 // the action's result. The call description string will be used in
153 // the error message to describe the call in the case the default
156 virtual UntypedActionResultHolderBase
* UntypedPerformDefaultAction(
157 void* untyped_args
, const std::string
& call_description
) const = 0;
159 // Performs the given action with the given arguments and returns
160 // the action's result.
162 virtual UntypedActionResultHolderBase
* UntypedPerformAction(
163 const void* untyped_action
, void* untyped_args
) const = 0;
165 // Writes a message that the call is uninteresting (i.e. neither
166 // explicitly expected nor explicitly unexpected) to the given
168 virtual void UntypedDescribeUninterestingCall(
169 const void* untyped_args
,
170 ::std::ostream
* os
) const
171 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) = 0;
173 // Returns the expectation that matches the given function arguments
174 // (or NULL is there's no match); when a match is found,
175 // untyped_action is set to point to the action that should be
176 // performed (or NULL if the action is "do default"), and
177 // is_excessive is modified to indicate whether the call exceeds the
179 virtual const ExpectationBase
* UntypedFindMatchingExpectation(
180 const void* untyped_args
,
181 const void** untyped_action
, bool* is_excessive
,
182 ::std::ostream
* what
, ::std::ostream
* why
)
183 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) = 0;
185 // Prints the given function arguments to the ostream.
186 virtual void UntypedPrintArgs(const void* untyped_args
,
187 ::std::ostream
* os
) const = 0;
189 // Sets the mock object this mock method belongs to, and registers
190 // this information in the global mock registry. Will be called
191 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
193 void RegisterOwner(const void* mock_obj
)
194 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
196 // Sets the mock object this mock method belongs to, and sets the
197 // name of the mock function. Will be called upon each invocation
198 // of this mock function.
199 void SetOwnerAndName(const void* mock_obj
, const char* name
)
200 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
202 // Returns the mock object this mock method belongs to. Must be
203 // called after RegisterOwner() or SetOwnerAndName() has been
205 const void* MockObject() const
206 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
208 // Returns the name of this mock method. Must be called after
209 // SetOwnerAndName() has been called.
210 const char* Name() const
211 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
213 // Returns the result of invoking this mock function with the given
214 // arguments. This function can be safely called from multiple
215 // threads concurrently. The caller is responsible for deleting the
217 UntypedActionResultHolderBase
* UntypedInvokeWith(void* untyped_args
)
218 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
221 typedef std::vector
<const void*> UntypedOnCallSpecs
;
223 using UntypedExpectations
= std::vector
<std::shared_ptr
<ExpectationBase
>>;
225 // Returns an Expectation object that references and co-owns exp,
226 // which must be an expectation on this mock function.
227 Expectation
GetHandleOf(ExpectationBase
* exp
);
229 // Address of the mock object this mock method belongs to. Only
230 // valid after this mock method has been called or
231 // ON_CALL/EXPECT_CALL has been invoked on it.
232 const void* mock_obj_
; // Protected by g_gmock_mutex.
234 // Name of the function being mocked. Only valid after this mock
235 // method has been called.
236 const char* name_
; // Protected by g_gmock_mutex.
238 // All default action specs for this function mocker.
239 UntypedOnCallSpecs untyped_on_call_specs_
;
241 // All expectations for this function mocker.
243 // It's undefined behavior to interleave expectations (EXPECT_CALLs
244 // or ON_CALLs) and mock function calls. Also, the order of
245 // expectations is important. Therefore it's a logic race condition
246 // to read/write untyped_expectations_ concurrently. In order for
247 // tools like tsan to catch concurrent read/write accesses to
248 // untyped_expectations, we deliberately leave accesses to it
250 UntypedExpectations untyped_expectations_
;
251 }; // class UntypedFunctionMockerBase
253 // Untyped base class for OnCallSpec<F>.
254 class UntypedOnCallSpecBase
{
256 // The arguments are the location of the ON_CALL() statement.
257 UntypedOnCallSpecBase(const char* a_file
, int a_line
)
258 : file_(a_file
), line_(a_line
), last_clause_(kNone
) {}
260 // Where in the source file was the default action spec defined?
261 const char* file() const { return file_
; }
262 int line() const { return line_
; }
265 // Gives each clause in the ON_CALL() statement a name.
267 // Do not change the order of the enum members! The run-time
268 // syntax checking relies on it.
274 // Asserts that the ON_CALL() statement has a certain property.
275 void AssertSpecProperty(bool property
,
276 const std::string
& failure_message
) const {
277 Assert(property
, file_
, line_
, failure_message
);
280 // Expects that the ON_CALL() statement has a certain property.
281 void ExpectSpecProperty(bool property
,
282 const std::string
& failure_message
) const {
283 Expect(property
, file_
, line_
, failure_message
);
289 // The last clause in the ON_CALL() statement as seen so far.
290 // Initially kNone and changes as the statement is parsed.
292 }; // class UntypedOnCallSpecBase
294 // This template class implements an ON_CALL spec.
295 template <typename F
>
296 class OnCallSpec
: public UntypedOnCallSpecBase
{
298 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
299 typedef typename Function
<F
>::ArgumentMatcherTuple ArgumentMatcherTuple
;
301 // Constructs an OnCallSpec object from the information inside
302 // the parenthesis of an ON_CALL() statement.
303 OnCallSpec(const char* a_file
, int a_line
,
304 const ArgumentMatcherTuple
& matchers
)
305 : UntypedOnCallSpecBase(a_file
, a_line
),
307 // By default, extra_matcher_ should match anything. However,
308 // we cannot initialize it with _ as that causes ambiguity between
309 // Matcher's copy and move constructor for some argument types.
310 extra_matcher_(A
<const ArgumentTuple
&>()) {}
312 // Implements the .With() clause.
313 OnCallSpec
& With(const Matcher
<const ArgumentTuple
&>& m
) {
314 // Makes sure this is called at most once.
315 ExpectSpecProperty(last_clause_
< kWith
,
316 ".With() cannot appear "
317 "more than once in an ON_CALL().");
318 last_clause_
= kWith
;
324 // Implements the .WillByDefault() clause.
325 OnCallSpec
& WillByDefault(const Action
<F
>& action
) {
326 ExpectSpecProperty(last_clause_
< kWillByDefault
,
327 ".WillByDefault() must appear "
328 "exactly once in an ON_CALL().");
329 last_clause_
= kWillByDefault
;
331 ExpectSpecProperty(!action
.IsDoDefault(),
332 "DoDefault() cannot be used in ON_CALL().");
337 // Returns true if and only if the given arguments match the matchers.
338 bool Matches(const ArgumentTuple
& args
) const {
339 return TupleMatches(matchers_
, args
) && extra_matcher_
.Matches(args
);
342 // Returns the action specified by the user.
343 const Action
<F
>& GetAction() const {
344 AssertSpecProperty(last_clause_
== kWillByDefault
,
345 ".WillByDefault() must appear exactly "
346 "once in an ON_CALL().");
351 // The information in statement
353 // ON_CALL(mock_object, Method(matchers))
354 // .With(multi-argument-matcher)
355 // .WillByDefault(action);
357 // is recorded in the data members like this:
359 // source file that contains the statement => file_
360 // line number of the statement => line_
361 // matchers => matchers_
362 // multi-argument-matcher => extra_matcher_
364 ArgumentMatcherTuple matchers_
;
365 Matcher
<const ArgumentTuple
&> extra_matcher_
;
367 }; // class OnCallSpec
369 // Possible reactions on uninteresting calls.
376 } // namespace internal
378 // Utilities for manipulating mock objects.
379 class GTEST_API_ Mock
{
381 // The following public methods can be called concurrently.
383 // Tells Google Mock to ignore mock_obj when checking for leaked
385 static void AllowLeak(const void* mock_obj
)
386 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
388 // Verifies and clears all expectations on the given mock object.
389 // If the expectations aren't satisfied, generates one or more
390 // Google Test non-fatal failures and returns false.
391 static bool VerifyAndClearExpectations(void* mock_obj
)
392 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
394 // Verifies all expectations on the given mock object and clears its
395 // default actions and expectations. Returns true if and only if the
396 // verification was successful.
397 static bool VerifyAndClear(void* mock_obj
)
398 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
400 // Returns whether the mock was created as a naggy mock (default)
401 static bool IsNaggy(void* mock_obj
)
402 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
403 // Returns whether the mock was created as a nice mock
404 static bool IsNice(void* mock_obj
)
405 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
406 // Returns whether the mock was created as a strict mock
407 static bool IsStrict(void* mock_obj
)
408 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
411 friend class internal::UntypedFunctionMockerBase
;
413 // Needed for a function mocker to register itself (so that we know
414 // how to clear a mock object).
415 template <typename F
>
416 friend class internal::FunctionMocker
;
418 template <typename M
>
419 friend class NiceMock
;
421 template <typename M
>
422 friend class NaggyMock
;
424 template <typename M
>
425 friend class StrictMock
;
427 // Tells Google Mock to allow uninteresting calls on the given mock
429 static void AllowUninterestingCalls(const void* mock_obj
)
430 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
432 // Tells Google Mock to warn the user about uninteresting calls on
433 // the given mock object.
434 static void WarnUninterestingCalls(const void* mock_obj
)
435 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
437 // Tells Google Mock to fail uninteresting calls on the given mock
439 static void FailUninterestingCalls(const void* mock_obj
)
440 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
442 // Tells Google Mock the given mock object is being destroyed and
443 // its entry in the call-reaction table should be removed.
444 static void UnregisterCallReaction(const void* mock_obj
)
445 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
447 // Returns the reaction Google Mock will have on uninteresting calls
448 // made on the given mock object.
449 static internal::CallReaction
GetReactionOnUninterestingCalls(
450 const void* mock_obj
)
451 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
453 // Verifies that all expectations on the given mock object have been
454 // satisfied. Reports one or more Google Test non-fatal failures
455 // and returns false if not.
456 static bool VerifyAndClearExpectationsLocked(void* mock_obj
)
457 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
);
459 // Clears all ON_CALL()s set on the given mock object.
460 static void ClearDefaultActionsLocked(void* mock_obj
)
461 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
);
463 // Registers a mock object and a mock method it owns.
464 static void Register(
465 const void* mock_obj
,
466 internal::UntypedFunctionMockerBase
* mocker
)
467 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
469 // Tells Google Mock where in the source code mock_obj is used in an
470 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
471 // information helps the user identify which object it is.
472 static void RegisterUseByOnCallOrExpectCall(
473 const void* mock_obj
, const char* file
, int line
)
474 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
476 // Unregisters a mock method; removes the owning mock object from
477 // the registry when the last mock method associated with it has
478 // been unregistered. This is called only in the destructor of
480 static void UnregisterLocked(internal::UntypedFunctionMockerBase
* mocker
)
481 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
);
484 // An abstract handle of an expectation. Useful in the .After()
485 // clause of EXPECT_CALL() for setting the (partial) order of
486 // expectations. The syntax:
488 // Expectation e1 = EXPECT_CALL(...)...;
489 // EXPECT_CALL(...).After(e1)...;
491 // sets two expectations where the latter can only be matched after
492 // the former has been satisfied.
495 // - This class is copyable and has value semantics.
496 // - Constness is shallow: a const Expectation object itself cannot
497 // be modified, but the mutable methods of the ExpectationBase
498 // object it references can be called via expectation_base().
500 class GTEST_API_ Expectation
{
502 // Constructs a null object that doesn't reference any expectation.
507 // This single-argument ctor must not be explicit, in order to support the
508 // Expectation e = EXPECT_CALL(...);
511 // A TypedExpectation object stores its pre-requisites as
512 // Expectation objects, and needs to call the non-const Retire()
513 // method on the ExpectationBase objects they reference. Therefore
514 // Expectation must receive a *non-const* reference to the
515 // ExpectationBase object.
516 Expectation(internal::ExpectationBase
& exp
); // NOLINT
518 // The compiler-generated copy ctor and operator= work exactly as
519 // intended, so we don't need to define our own.
521 // Returns true if and only if rhs references the same expectation as this
523 bool operator==(const Expectation
& rhs
) const {
524 return expectation_base_
== rhs
.expectation_base_
;
527 bool operator!=(const Expectation
& rhs
) const { return !(*this == rhs
); }
530 friend class ExpectationSet
;
531 friend class Sequence
;
532 friend class ::testing::internal::ExpectationBase
;
533 friend class ::testing::internal::UntypedFunctionMockerBase
;
535 template <typename F
>
536 friend class ::testing::internal::FunctionMocker
;
538 template <typename F
>
539 friend class ::testing::internal::TypedExpectation
;
541 // This comparator is needed for putting Expectation objects into a set.
544 bool operator()(const Expectation
& lhs
, const Expectation
& rhs
) const {
545 return lhs
.expectation_base_
.get() < rhs
.expectation_base_
.get();
549 typedef ::std::set
<Expectation
, Less
> Set
;
552 const std::shared_ptr
<internal::ExpectationBase
>& expectation_base
);
554 // Returns the expectation this object references.
555 const std::shared_ptr
<internal::ExpectationBase
>& expectation_base() const {
556 return expectation_base_
;
559 // A shared_ptr that co-owns the expectation this handle references.
560 std::shared_ptr
<internal::ExpectationBase
> expectation_base_
;
563 // A set of expectation handles. Useful in the .After() clause of
564 // EXPECT_CALL() for setting the (partial) order of expectations. The
567 // ExpectationSet es;
568 // es += EXPECT_CALL(...)...;
569 // es += EXPECT_CALL(...)...;
570 // EXPECT_CALL(...).After(es)...;
572 // sets three expectations where the last one can only be matched
573 // after the first two have both been satisfied.
575 // This class is copyable and has value semantics.
576 class ExpectationSet
{
578 // A bidirectional iterator that can read a const element in the set.
579 typedef Expectation::Set::const_iterator const_iterator
;
581 // An object stored in the set. This is an alias of Expectation.
582 typedef Expectation::Set::value_type value_type
;
584 // Constructs an empty set.
587 // This single-argument ctor must not be explicit, in order to support the
588 // ExpectationSet es = EXPECT_CALL(...);
590 ExpectationSet(internal::ExpectationBase
& exp
) { // NOLINT
591 *this += Expectation(exp
);
594 // This single-argument ctor implements implicit conversion from
595 // Expectation and thus must not be explicit. This allows either an
596 // Expectation or an ExpectationSet to be used in .After().
597 ExpectationSet(const Expectation
& e
) { // NOLINT
601 // The compiler-generator ctor and operator= works exactly as
602 // intended, so we don't need to define our own.
604 // Returns true if and only if rhs contains the same set of Expectation
605 // objects as this does.
606 bool operator==(const ExpectationSet
& rhs
) const {
607 return expectations_
== rhs
.expectations_
;
610 bool operator!=(const ExpectationSet
& rhs
) const { return !(*this == rhs
); }
612 // Implements the syntax
613 // expectation_set += EXPECT_CALL(...);
614 ExpectationSet
& operator+=(const Expectation
& e
) {
615 expectations_
.insert(e
);
619 int size() const { return static_cast<int>(expectations_
.size()); }
621 const_iterator
begin() const { return expectations_
.begin(); }
622 const_iterator
end() const { return expectations_
.end(); }
625 Expectation::Set expectations_
;
629 // Sequence objects are used by a user to specify the relative order
630 // in which the expectations should match. They are copyable (we rely
631 // on the compiler-defined copy constructor and assignment operator).
632 class GTEST_API_ Sequence
{
634 // Constructs an empty sequence.
635 Sequence() : last_expectation_(new Expectation
) {}
637 // Adds an expectation to this sequence. The caller must ensure
638 // that no other thread is accessing this Sequence object.
639 void AddExpectation(const Expectation
& expectation
) const;
642 // The last expectation in this sequence.
643 std::shared_ptr
<Expectation
> last_expectation_
;
646 // An object of this type causes all EXPECT_CALL() statements
647 // encountered in its scope to be put in an anonymous sequence. The
648 // work is done in the constructor and destructor. You should only
649 // create an InSequence object on the stack.
651 // The sole purpose for this class is to support easy definition of
652 // sequential expectations, e.g.
655 // InSequence dummy; // The name of the object doesn't matter.
657 // // The following expectations must match in the order they appear.
658 // EXPECT_CALL(a, Bar())...;
659 // EXPECT_CALL(a, Baz())...;
661 // EXPECT_CALL(b, Xyz())...;
664 // You can create InSequence objects in multiple threads, as long as
665 // they are used to affect different mock objects. The idea is that
666 // each thread can create and set up its own mocks as if it's the only
667 // thread. However, for clarity of your tests we recommend you to set
668 // up mocks in the main thread unless you have a good reason not to do
670 class GTEST_API_ InSequence
{
675 bool sequence_created_
;
677 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence
); // NOLINT
678 } GTEST_ATTRIBUTE_UNUSED_
;
682 // Points to the implicit sequence introduced by a living InSequence
683 // object (if any) in the current thread or NULL.
684 GTEST_API_
extern ThreadLocal
<Sequence
*> g_gmock_implicit_sequence
;
686 // Base class for implementing expectations.
688 // There are two reasons for having a type-agnostic base class for
691 // 1. We need to store collections of expectations of different
692 // types (e.g. all pre-requisites of a particular expectation, all
693 // expectations in a sequence). Therefore these expectation objects
694 // must share a common base class.
696 // 2. We can avoid binary code bloat by moving methods not depending
697 // on the template argument of Expectation to the base class.
699 // This class is internal and mustn't be used by user code directly.
700 class GTEST_API_ ExpectationBase
{
702 // source_text is the EXPECT_CALL(...) source that created this Expectation.
703 ExpectationBase(const char* file
, int line
, const std::string
& source_text
);
705 virtual ~ExpectationBase();
707 // Where in the source file was the expectation spec defined?
708 const char* file() const { return file_
; }
709 int line() const { return line_
; }
710 const char* source_text() const { return source_text_
.c_str(); }
711 // Returns the cardinality specified in the expectation spec.
712 const Cardinality
& cardinality() const { return cardinality_
; }
714 // Describes the source file location of this expectation.
715 void DescribeLocationTo(::std::ostream
* os
) const {
716 *os
<< FormatFileLocation(file(), line()) << " ";
719 // Describes how many times a function call matching this
720 // expectation has occurred.
721 void DescribeCallCountTo(::std::ostream
* os
) const
722 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
724 // If this mock method has an extra matcher (i.e. .With(matcher)),
725 // describes it to the ostream.
726 virtual void MaybeDescribeExtraMatcherTo(::std::ostream
* os
) = 0;
729 friend class ::testing::Expectation
;
730 friend class UntypedFunctionMockerBase
;
733 // Don't change the order of the enum members!
744 typedef std::vector
<const void*> UntypedActions
;
746 // Returns an Expectation object that references and co-owns this
748 virtual Expectation
GetHandle() = 0;
750 // Asserts that the EXPECT_CALL() statement has the given property.
751 void AssertSpecProperty(bool property
,
752 const std::string
& failure_message
) const {
753 Assert(property
, file_
, line_
, failure_message
);
756 // Expects that the EXPECT_CALL() statement has the given property.
757 void ExpectSpecProperty(bool property
,
758 const std::string
& failure_message
) const {
759 Expect(property
, file_
, line_
, failure_message
);
762 // Explicitly specifies the cardinality of this expectation. Used
763 // by the subclasses to implement the .Times() clause.
764 void SpecifyCardinality(const Cardinality
& cardinality
);
766 // Returns true if and only if the user specified the cardinality
767 // explicitly using a .Times().
768 bool cardinality_specified() const { return cardinality_specified_
; }
770 // Sets the cardinality of this expectation spec.
771 void set_cardinality(const Cardinality
& a_cardinality
) {
772 cardinality_
= a_cardinality
;
775 // The following group of methods should only be called after the
776 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
777 // the current thread.
779 // Retires all pre-requisites of this expectation.
780 void RetireAllPreRequisites()
781 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
783 // Returns true if and only if this expectation is retired.
784 bool is_retired() const
785 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
786 g_gmock_mutex
.AssertHeld();
790 // Retires this expectation.
792 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
793 g_gmock_mutex
.AssertHeld();
797 // Returns true if and only if this expectation is satisfied.
798 bool IsSatisfied() const
799 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
800 g_gmock_mutex
.AssertHeld();
801 return cardinality().IsSatisfiedByCallCount(call_count_
);
804 // Returns true if and only if this expectation is saturated.
805 bool IsSaturated() const
806 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
807 g_gmock_mutex
.AssertHeld();
808 return cardinality().IsSaturatedByCallCount(call_count_
);
811 // Returns true if and only if this expectation is over-saturated.
812 bool IsOverSaturated() const
813 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
814 g_gmock_mutex
.AssertHeld();
815 return cardinality().IsOverSaturatedByCallCount(call_count_
);
818 // Returns true if and only if all pre-requisites of this expectation are
820 bool AllPrerequisitesAreSatisfied() const
821 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
823 // Adds unsatisfied pre-requisites of this expectation to 'result'.
824 void FindUnsatisfiedPrerequisites(ExpectationSet
* result
) const
825 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
827 // Returns the number this expectation has been invoked.
828 int call_count() const
829 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
830 g_gmock_mutex
.AssertHeld();
834 // Increments the number this expectation has been invoked.
835 void IncrementCallCount()
836 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
837 g_gmock_mutex
.AssertHeld();
841 // Checks the action count (i.e. the number of WillOnce() and
842 // WillRepeatedly() clauses) against the cardinality if this hasn't
843 // been done before. Prints a warning if there are too many or too
845 void CheckActionCountIfNotDone() const
846 GTEST_LOCK_EXCLUDED_(mutex_
);
848 friend class ::testing::Sequence
;
849 friend class ::testing::internal::ExpectationTester
;
851 template <typename Function
>
852 friend class TypedExpectation
;
854 // Implements the .Times() clause.
855 void UntypedTimes(const Cardinality
& a_cardinality
);
857 // This group of fields are part of the spec and won't change after
858 // an EXPECT_CALL() statement finishes.
859 const char* file_
; // The file that contains the expectation.
860 int line_
; // The line number of the expectation.
861 const std::string source_text_
; // The EXPECT_CALL(...) source text.
862 // True if and only if the cardinality is specified explicitly.
863 bool cardinality_specified_
;
864 Cardinality cardinality_
; // The cardinality of the expectation.
865 // The immediate pre-requisites (i.e. expectations that must be
866 // satisfied before this expectation can be matched) of this
867 // expectation. We use std::shared_ptr in the set because we want an
868 // Expectation object to be co-owned by its FunctionMocker and its
869 // successors. This allows multiple mock objects to be deleted at
871 ExpectationSet immediate_prerequisites_
;
873 // This group of fields are the current state of the expectation,
874 // and can change as the mock function is called.
875 int call_count_
; // How many times this expectation has been invoked.
876 bool retired_
; // True if and only if this expectation has retired.
877 UntypedActions untyped_actions_
;
878 bool extra_matcher_specified_
;
879 bool repeated_action_specified_
; // True if a WillRepeatedly() was specified.
880 bool retires_on_saturation_
;
882 mutable bool action_count_checked_
; // Under mutex_.
883 mutable Mutex mutex_
; // Protects action_count_checked_.
885 GTEST_DISALLOW_ASSIGN_(ExpectationBase
);
886 }; // class ExpectationBase
888 // Impements an expectation for the given function type.
889 template <typename F
>
890 class TypedExpectation
: public ExpectationBase
{
892 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
893 typedef typename Function
<F
>::ArgumentMatcherTuple ArgumentMatcherTuple
;
894 typedef typename Function
<F
>::Result Result
;
896 TypedExpectation(FunctionMocker
<F
>* owner
, const char* a_file
, int a_line
,
897 const std::string
& a_source_text
,
898 const ArgumentMatcherTuple
& m
)
899 : ExpectationBase(a_file
, a_line
, a_source_text
),
902 // By default, extra_matcher_ should match anything. However,
903 // we cannot initialize it with _ as that causes ambiguity between
904 // Matcher's copy and move constructor for some argument types.
905 extra_matcher_(A
<const ArgumentTuple
&>()),
906 repeated_action_(DoDefault()) {}
908 ~TypedExpectation() override
{
909 // Check the validity of the action count if it hasn't been done
910 // yet (for example, if the expectation was never used).
911 CheckActionCountIfNotDone();
912 for (UntypedActions::const_iterator it
= untyped_actions_
.begin();
913 it
!= untyped_actions_
.end(); ++it
) {
914 delete static_cast<const Action
<F
>*>(*it
);
918 // Implements the .With() clause.
919 TypedExpectation
& With(const Matcher
<const ArgumentTuple
&>& m
) {
920 if (last_clause_
== kWith
) {
921 ExpectSpecProperty(false,
922 ".With() cannot appear "
923 "more than once in an EXPECT_CALL().");
925 ExpectSpecProperty(last_clause_
< kWith
,
926 ".With() must be the first "
927 "clause in an EXPECT_CALL().");
929 last_clause_
= kWith
;
932 extra_matcher_specified_
= true;
936 // Implements the .Times() clause.
937 TypedExpectation
& Times(const Cardinality
& a_cardinality
) {
938 ExpectationBase::UntypedTimes(a_cardinality
);
942 // Implements the .Times() clause.
943 TypedExpectation
& Times(int n
) {
944 return Times(Exactly(n
));
947 // Implements the .InSequence() clause.
948 TypedExpectation
& InSequence(const Sequence
& s
) {
949 ExpectSpecProperty(last_clause_
<= kInSequence
,
950 ".InSequence() cannot appear after .After(),"
951 " .WillOnce(), .WillRepeatedly(), or "
952 ".RetiresOnSaturation().");
953 last_clause_
= kInSequence
;
955 s
.AddExpectation(GetHandle());
958 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
) {
959 return InSequence(s1
).InSequence(s2
);
961 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
962 const Sequence
& s3
) {
963 return InSequence(s1
, s2
).InSequence(s3
);
965 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
966 const Sequence
& s3
, const Sequence
& s4
) {
967 return InSequence(s1
, s2
, s3
).InSequence(s4
);
969 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
970 const Sequence
& s3
, const Sequence
& s4
,
971 const Sequence
& s5
) {
972 return InSequence(s1
, s2
, s3
, s4
).InSequence(s5
);
975 // Implements that .After() clause.
976 TypedExpectation
& After(const ExpectationSet
& s
) {
977 ExpectSpecProperty(last_clause_
<= kAfter
,
978 ".After() cannot appear after .WillOnce(),"
979 " .WillRepeatedly(), or "
980 ".RetiresOnSaturation().");
981 last_clause_
= kAfter
;
983 for (ExpectationSet::const_iterator it
= s
.begin(); it
!= s
.end(); ++it
) {
984 immediate_prerequisites_
+= *it
;
988 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
) {
989 return After(s1
).After(s2
);
991 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
992 const ExpectationSet
& s3
) {
993 return After(s1
, s2
).After(s3
);
995 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
996 const ExpectationSet
& s3
, const ExpectationSet
& s4
) {
997 return After(s1
, s2
, s3
).After(s4
);
999 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
1000 const ExpectationSet
& s3
, const ExpectationSet
& s4
,
1001 const ExpectationSet
& s5
) {
1002 return After(s1
, s2
, s3
, s4
).After(s5
);
1005 // Implements the .WillOnce() clause.
1006 TypedExpectation
& WillOnce(const Action
<F
>& action
) {
1007 ExpectSpecProperty(last_clause_
<= kWillOnce
,
1008 ".WillOnce() cannot appear after "
1009 ".WillRepeatedly() or .RetiresOnSaturation().");
1010 last_clause_
= kWillOnce
;
1012 untyped_actions_
.push_back(new Action
<F
>(action
));
1013 if (!cardinality_specified()) {
1014 set_cardinality(Exactly(static_cast<int>(untyped_actions_
.size())));
1019 // Implements the .WillRepeatedly() clause.
1020 TypedExpectation
& WillRepeatedly(const Action
<F
>& action
) {
1021 if (last_clause_
== kWillRepeatedly
) {
1022 ExpectSpecProperty(false,
1023 ".WillRepeatedly() cannot appear "
1024 "more than once in an EXPECT_CALL().");
1026 ExpectSpecProperty(last_clause_
< kWillRepeatedly
,
1027 ".WillRepeatedly() cannot appear "
1028 "after .RetiresOnSaturation().");
1030 last_clause_
= kWillRepeatedly
;
1031 repeated_action_specified_
= true;
1033 repeated_action_
= action
;
1034 if (!cardinality_specified()) {
1035 set_cardinality(AtLeast(static_cast<int>(untyped_actions_
.size())));
1038 // Now that no more action clauses can be specified, we check
1039 // whether their count makes sense.
1040 CheckActionCountIfNotDone();
1044 // Implements the .RetiresOnSaturation() clause.
1045 TypedExpectation
& RetiresOnSaturation() {
1046 ExpectSpecProperty(last_clause_
< kRetiresOnSaturation
,
1047 ".RetiresOnSaturation() cannot appear "
1049 last_clause_
= kRetiresOnSaturation
;
1050 retires_on_saturation_
= true;
1052 // Now that no more action clauses can be specified, we check
1053 // whether their count makes sense.
1054 CheckActionCountIfNotDone();
1058 // Returns the matchers for the arguments as specified inside the
1059 // EXPECT_CALL() macro.
1060 const ArgumentMatcherTuple
& matchers() const {
1064 // Returns the matcher specified by the .With() clause.
1065 const Matcher
<const ArgumentTuple
&>& extra_matcher() const {
1066 return extra_matcher_
;
1069 // Returns the action specified by the .WillRepeatedly() clause.
1070 const Action
<F
>& repeated_action() const { return repeated_action_
; }
1072 // If this mock method has an extra matcher (i.e. .With(matcher)),
1073 // describes it to the ostream.
1074 void MaybeDescribeExtraMatcherTo(::std::ostream
* os
) override
{
1075 if (extra_matcher_specified_
) {
1076 *os
<< " Expected args: ";
1077 extra_matcher_
.DescribeTo(os
);
1083 template <typename Function
>
1084 friend class FunctionMocker
;
1086 // Returns an Expectation object that references and co-owns this
1088 Expectation
GetHandle() override
{ return owner_
->GetHandleOf(this); }
1090 // The following methods will be called only after the EXPECT_CALL()
1091 // statement finishes and when the current thread holds
1094 // Returns true if and only if this expectation matches the given arguments.
1095 bool Matches(const ArgumentTuple
& args
) const
1096 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1097 g_gmock_mutex
.AssertHeld();
1098 return TupleMatches(matchers_
, args
) && extra_matcher_
.Matches(args
);
1101 // Returns true if and only if this expectation should handle the given
1103 bool ShouldHandleArguments(const ArgumentTuple
& args
) const
1104 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1105 g_gmock_mutex
.AssertHeld();
1107 // In case the action count wasn't checked when the expectation
1108 // was defined (e.g. if this expectation has no WillRepeatedly()
1109 // or RetiresOnSaturation() clause), we check it when the
1110 // expectation is used for the first time.
1111 CheckActionCountIfNotDone();
1112 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args
);
1115 // Describes the result of matching the arguments against this
1116 // expectation to the given ostream.
1117 void ExplainMatchResultTo(
1118 const ArgumentTuple
& args
,
1119 ::std::ostream
* os
) const
1120 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1121 g_gmock_mutex
.AssertHeld();
1124 *os
<< " Expected: the expectation is active\n"
1125 << " Actual: it is retired\n";
1126 } else if (!Matches(args
)) {
1127 if (!TupleMatches(matchers_
, args
)) {
1128 ExplainMatchFailureTupleTo(matchers_
, args
, os
);
1130 StringMatchResultListener listener
;
1131 if (!extra_matcher_
.MatchAndExplain(args
, &listener
)) {
1132 *os
<< " Expected args: ";
1133 extra_matcher_
.DescribeTo(os
);
1134 *os
<< "\n Actual: don't match";
1136 internal::PrintIfNotEmpty(listener
.str(), os
);
1139 } else if (!AllPrerequisitesAreSatisfied()) {
1140 *os
<< " Expected: all pre-requisites are satisfied\n"
1141 << " Actual: the following immediate pre-requisites "
1142 << "are not satisfied:\n";
1143 ExpectationSet unsatisfied_prereqs
;
1144 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs
);
1146 for (ExpectationSet::const_iterator it
= unsatisfied_prereqs
.begin();
1147 it
!= unsatisfied_prereqs
.end(); ++it
) {
1148 it
->expectation_base()->DescribeLocationTo(os
);
1149 *os
<< "pre-requisite #" << i
++ << "\n";
1151 *os
<< " (end of pre-requisites)\n";
1153 // This line is here just for completeness' sake. It will never
1154 // be executed as currently the ExplainMatchResultTo() function
1155 // is called only when the mock function call does NOT match the
1157 *os
<< "The call matches the expectation.\n";
1161 // Returns the action that should be taken for the current invocation.
1162 const Action
<F
>& GetCurrentAction(const FunctionMocker
<F
>* mocker
,
1163 const ArgumentTuple
& args
) const
1164 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1165 g_gmock_mutex
.AssertHeld();
1166 const int count
= call_count();
1167 Assert(count
>= 1, __FILE__
, __LINE__
,
1168 "call_count() is <= 0 when GetCurrentAction() is "
1169 "called - this should never happen.");
1171 const int action_count
= static_cast<int>(untyped_actions_
.size());
1172 if (action_count
> 0 && !repeated_action_specified_
&&
1173 count
> action_count
) {
1174 // If there is at least one WillOnce() and no WillRepeatedly(),
1175 // we warn the user when the WillOnce() clauses ran out.
1176 ::std::stringstream ss
;
1177 DescribeLocationTo(&ss
);
1178 ss
<< "Actions ran out in " << source_text() << "...\n"
1179 << "Called " << count
<< " times, but only "
1180 << action_count
<< " WillOnce()"
1181 << (action_count
== 1 ? " is" : "s are") << " specified - ";
1182 mocker
->DescribeDefaultActionTo(args
, &ss
);
1183 Log(kWarning
, ss
.str(), 1);
1186 return count
<= action_count
1187 ? *static_cast<const Action
<F
>*>(
1188 untyped_actions_
[static_cast<size_t>(count
- 1)])
1189 : repeated_action();
1192 // Given the arguments of a mock function call, if the call will
1193 // over-saturate this expectation, returns the default action;
1194 // otherwise, returns the next action in this expectation. Also
1195 // describes *what* happened to 'what', and explains *why* Google
1196 // Mock does it to 'why'. This method is not const as it calls
1197 // IncrementCallCount(). A return value of NULL means the default
1199 const Action
<F
>* GetActionForArguments(const FunctionMocker
<F
>* mocker
,
1200 const ArgumentTuple
& args
,
1201 ::std::ostream
* what
,
1202 ::std::ostream
* why
)
1203 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1204 g_gmock_mutex
.AssertHeld();
1205 if (IsSaturated()) {
1206 // We have an excessive call.
1207 IncrementCallCount();
1208 *what
<< "Mock function called more times than expected - ";
1209 mocker
->DescribeDefaultActionTo(args
, what
);
1210 DescribeCallCountTo(why
);
1215 IncrementCallCount();
1216 RetireAllPreRequisites();
1218 if (retires_on_saturation_
&& IsSaturated()) {
1222 // Must be done after IncrementCount()!
1223 *what
<< "Mock function call matches " << source_text() <<"...\n";
1224 return &(GetCurrentAction(mocker
, args
));
1227 // All the fields below won't change once the EXPECT_CALL()
1228 // statement finishes.
1229 FunctionMocker
<F
>* const owner_
;
1230 ArgumentMatcherTuple matchers_
;
1231 Matcher
<const ArgumentTuple
&> extra_matcher_
;
1232 Action
<F
> repeated_action_
;
1234 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation
);
1235 }; // class TypedExpectation
1237 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1238 // specifying the default behavior of, or expectation on, a mock
1241 // Note: class MockSpec really belongs to the ::testing namespace.
1242 // However if we define it in ::testing, MSVC will complain when
1243 // classes in ::testing::internal declare it as a friend class
1244 // template. To workaround this compiler bug, we define MockSpec in
1245 // ::testing::internal and import it into ::testing.
1247 // Logs a message including file and line number information.
1248 GTEST_API_
void LogWithLocation(testing::internal::LogSeverity severity
,
1249 const char* file
, int line
,
1250 const std::string
& message
);
1252 template <typename F
>
1255 typedef typename
internal::Function
<F
>::ArgumentTuple ArgumentTuple
;
1256 typedef typename
internal::Function
<F
>::ArgumentMatcherTuple
1257 ArgumentMatcherTuple
;
1259 // Constructs a MockSpec object, given the function mocker object
1260 // that the spec is associated with.
1261 MockSpec(internal::FunctionMocker
<F
>* function_mocker
,
1262 const ArgumentMatcherTuple
& matchers
)
1263 : function_mocker_(function_mocker
), matchers_(matchers
) {}
1265 // Adds a new default action spec to the function mocker and returns
1266 // the newly created spec.
1267 internal::OnCallSpec
<F
>& InternalDefaultActionSetAt(
1268 const char* file
, int line
, const char* obj
, const char* call
) {
1269 LogWithLocation(internal::kInfo
, file
, line
,
1270 std::string("ON_CALL(") + obj
+ ", " + call
+ ") invoked");
1271 return function_mocker_
->AddNewOnCallSpec(file
, line
, matchers_
);
1274 // Adds a new expectation spec to the function mocker and returns
1275 // the newly created spec.
1276 internal::TypedExpectation
<F
>& InternalExpectedAt(
1277 const char* file
, int line
, const char* obj
, const char* call
) {
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(
1282 file
, line
, source_text
, matchers_
);
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
)
1316 : value_(std::move(value
)) {
1319 // Unwraps and returns the underlying value/reference, exactly as
1320 // originally passed. The behavior of calling this more than once on
1321 // the same object is unspecified.
1322 T
Unwrap() { return std::move(value_
); }
1324 // Provides nondestructive access to the underlying value/reference.
1325 // Always returns a const reference (more precisely,
1326 // const std::add_lvalue_reference<T>::type). The behavior of calling this
1327 // after calling Unwrap on the same object is unspecified.
1328 const T
& Peek() const {
1336 // Specialization for lvalue reference types. See primary template
1337 // for documentation.
1338 template <typename T
>
1339 class ReferenceOrValueWrapper
<T
&> {
1341 // Workaround for debatable pass-by-reference lint warning (c-library-team
1342 // policy precludes NOLINT in this context)
1343 typedef T
& reference
;
1344 explicit ReferenceOrValueWrapper(reference ref
)
1345 : value_ptr_(&ref
) {}
1346 T
& Unwrap() { return *value_ptr_
; }
1347 const T
& Peek() const { return *value_ptr_
; }
1353 // MSVC warns about using 'this' in base member initializer list, so
1354 // we need to temporarily disable the warning. We have to do it for
1355 // the entire class to suppress the warning, even though it's about
1356 // the constructor only.
1357 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
1359 // C++ treats the void type specially. For example, you cannot define
1360 // a void-typed variable or pass a void value to a function.
1361 // ActionResultHolder<T> holds a value of type T, where T must be a
1362 // copyable type or void (T doesn't need to be default-constructable).
1363 // It hides the syntactic difference between void and other types, and
1364 // is used to unify the code for invoking both void-returning and
1365 // non-void-returning mock functions.
1367 // Untyped base class for ActionResultHolder<T>.
1368 class UntypedActionResultHolderBase
{
1370 virtual ~UntypedActionResultHolderBase() {}
1372 // Prints the held value as an action's result to os.
1373 virtual void PrintAsActionResult(::std::ostream
* os
) const = 0;
1376 // This generic definition is used when T is not void.
1377 template <typename T
>
1378 class ActionResultHolder
: public UntypedActionResultHolderBase
{
1380 // Returns the held value. Must not be called more than once.
1382 return result_
.Unwrap();
1385 // Prints the held value as an action's result to os.
1386 void PrintAsActionResult(::std::ostream
* os
) const override
{
1387 *os
<< "\n Returns: ";
1388 // T may be a reference type, so we don't use UniversalPrint().
1389 UniversalPrinter
<T
>::Print(result_
.Peek(), os
);
1392 // Performs the given mock function's default action and returns the
1393 // result in a new-ed ActionResultHolder.
1394 template <typename F
>
1395 static ActionResultHolder
* PerformDefaultAction(
1396 const FunctionMocker
<F
>* func_mocker
,
1397 typename Function
<F
>::ArgumentTuple
&& args
,
1398 const std::string
& call_description
) {
1399 return new ActionResultHolder(Wrapper(func_mocker
->PerformDefaultAction(
1400 std::move(args
), call_description
)));
1403 // Performs the given action and returns the result in a new-ed
1404 // ActionResultHolder.
1405 template <typename F
>
1406 static ActionResultHolder
* PerformAction(
1407 const Action
<F
>& action
, typename Function
<F
>::ArgumentTuple
&& args
) {
1408 return new ActionResultHolder(
1409 Wrapper(action
.Perform(std::move(args
))));
1413 typedef ReferenceOrValueWrapper
<T
> Wrapper
;
1415 explicit ActionResultHolder(Wrapper result
)
1416 : result_(std::move(result
)) {
1421 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder
);
1424 // Specialization for T = void.
1426 class ActionResultHolder
<void> : public UntypedActionResultHolderBase
{
1430 void PrintAsActionResult(::std::ostream
* /* os */) const override
{}
1432 // Performs the given mock function's default action and returns ownership
1433 // of an empty ActionResultHolder*.
1434 template <typename F
>
1435 static ActionResultHolder
* PerformDefaultAction(
1436 const FunctionMocker
<F
>* func_mocker
,
1437 typename Function
<F
>::ArgumentTuple
&& args
,
1438 const std::string
& call_description
) {
1439 func_mocker
->PerformDefaultAction(std::move(args
), call_description
);
1440 return new ActionResultHolder
;
1443 // Performs the given action and returns ownership of an empty
1444 // ActionResultHolder*.
1445 template <typename F
>
1446 static ActionResultHolder
* PerformAction(
1447 const Action
<F
>& action
, typename Function
<F
>::ArgumentTuple
&& args
) {
1448 action
.Perform(std::move(args
));
1449 return new ActionResultHolder
;
1453 ActionResultHolder() {}
1454 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder
);
1457 template <typename F
>
1458 class FunctionMocker
;
1460 template <typename R
, typename
... Args
>
1461 class FunctionMocker
<R(Args
...)> final
: public UntypedFunctionMockerBase
{
1462 using F
= R(Args
...);
1466 using ArgumentTuple
= std::tuple
<Args
...>;
1467 using ArgumentMatcherTuple
= std::tuple
<Matcher
<Args
>...>;
1471 // There is no generally useful and implementable semantics of
1472 // copying a mock object, so copying a mock is usually a user error.
1473 // Thus we disallow copying function mockers. If the user really
1474 // wants to copy a mock object, they should implement their own copy
1475 // operation, for example:
1477 // class MockFoo : public Foo {
1479 // // Defines a copy constructor explicitly.
1480 // MockFoo(const MockFoo& src) {}
1483 FunctionMocker(const FunctionMocker
&) = delete;
1484 FunctionMocker
& operator=(const FunctionMocker
&) = delete;
1486 // The destructor verifies that all expectations on this mock
1487 // function have been satisfied. If not, it will report Google Test
1488 // non-fatal failures for the violations.
1489 ~FunctionMocker() override
GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1490 MutexLock
l(&g_gmock_mutex
);
1491 VerifyAndClearExpectationsLocked();
1492 Mock::UnregisterLocked(this);
1493 ClearDefaultActionsLocked();
1496 // Returns the ON_CALL spec that matches this mock function with the
1497 // given arguments; returns NULL if no matching ON_CALL is found.
1499 const OnCallSpec
<F
>* FindOnCallSpec(
1500 const ArgumentTuple
& args
) const {
1501 for (UntypedOnCallSpecs::const_reverse_iterator it
1502 = untyped_on_call_specs_
.rbegin();
1503 it
!= untyped_on_call_specs_
.rend(); ++it
) {
1504 const OnCallSpec
<F
>* spec
= static_cast<const OnCallSpec
<F
>*>(*it
);
1505 if (spec
->Matches(args
))
1512 // Performs the default action of this mock function on the given
1513 // arguments and returns the result. Asserts (or throws if
1514 // exceptions are enabled) with a helpful call descrption if there
1515 // is no valid return value. This method doesn't depend on the
1516 // mutable state of this object, and thus can be called concurrently
1519 Result
PerformDefaultAction(ArgumentTuple
&& args
,
1520 const std::string
& call_description
) const {
1521 const OnCallSpec
<F
>* const spec
=
1522 this->FindOnCallSpec(args
);
1523 if (spec
!= nullptr) {
1524 return spec
->GetAction().Perform(std::move(args
));
1526 const std::string message
=
1528 "\n The mock function has no default action "
1529 "set, and its return type has no default value set.";
1530 #if GTEST_HAS_EXCEPTIONS
1531 if (!DefaultValue
<Result
>::Exists()) {
1532 throw std::runtime_error(message
);
1535 Assert(DefaultValue
<Result
>::Exists(), "", -1, message
);
1537 return DefaultValue
<Result
>::Get();
1540 // Performs the default action with the given arguments and returns
1541 // the action's result. The call description string will be used in
1542 // the error message to describe the call in the case the default
1543 // action fails. The caller is responsible for deleting the result.
1545 UntypedActionResultHolderBase
* UntypedPerformDefaultAction(
1546 void* untyped_args
, // must point to an ArgumentTuple
1547 const std::string
& call_description
) const override
{
1548 ArgumentTuple
* args
= static_cast<ArgumentTuple
*>(untyped_args
);
1549 return ResultHolder::PerformDefaultAction(this, std::move(*args
),
1553 // Performs the given action with the given arguments and returns
1554 // the action's result. The caller is responsible for deleting the
1557 UntypedActionResultHolderBase
* UntypedPerformAction(
1558 const void* untyped_action
, void* untyped_args
) const override
{
1559 // Make a copy of the action before performing it, in case the
1560 // action deletes the mock object (and thus deletes itself).
1561 const Action
<F
> action
= *static_cast<const Action
<F
>*>(untyped_action
);
1562 ArgumentTuple
* args
= static_cast<ArgumentTuple
*>(untyped_args
);
1563 return ResultHolder::PerformAction(action
, std::move(*args
));
1566 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1567 // clears the ON_CALL()s set on this mock function.
1568 void ClearDefaultActionsLocked() override
1569 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1570 g_gmock_mutex
.AssertHeld();
1572 // Deleting our default actions may trigger other mock objects to be
1573 // deleted, for example if an action contains a reference counted smart
1574 // pointer to that mock object, and that is the last reference. So if we
1575 // delete our actions within the context of the global mutex we may deadlock
1576 // when this method is called again. Instead, make a copy of the set of
1577 // actions to delete, clear our set within the mutex, and then delete the
1578 // actions outside of the mutex.
1579 UntypedOnCallSpecs specs_to_delete
;
1580 untyped_on_call_specs_
.swap(specs_to_delete
);
1582 g_gmock_mutex
.Unlock();
1583 for (UntypedOnCallSpecs::const_iterator it
=
1584 specs_to_delete
.begin();
1585 it
!= specs_to_delete
.end(); ++it
) {
1586 delete static_cast<const OnCallSpec
<F
>*>(*it
);
1589 // Lock the mutex again, since the caller expects it to be locked when we
1591 g_gmock_mutex
.Lock();
1594 // Returns the result of invoking this mock function with the given
1595 // arguments. This function can be safely called from multiple
1596 // threads concurrently.
1597 Result
Invoke(Args
... args
) GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1598 ArgumentTuple
tuple(std::forward
<Args
>(args
)...);
1599 std::unique_ptr
<ResultHolder
> holder(DownCast_
<ResultHolder
*>(
1600 this->UntypedInvokeWith(static_cast<void*>(&tuple
))));
1601 return holder
->Unwrap();
1604 MockSpec
<F
> With(Matcher
<Args
>... m
) {
1605 return MockSpec
<F
>(this, ::std::make_tuple(std::move(m
)...));
1609 template <typename Function
>
1610 friend class MockSpec
;
1612 typedef ActionResultHolder
<Result
> ResultHolder
;
1614 // Adds and returns a default action spec for this mock function.
1615 OnCallSpec
<F
>& AddNewOnCallSpec(
1616 const char* file
, int line
,
1617 const ArgumentMatcherTuple
& m
)
1618 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1619 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file
, line
);
1620 OnCallSpec
<F
>* const on_call_spec
= new OnCallSpec
<F
>(file
, line
, m
);
1621 untyped_on_call_specs_
.push_back(on_call_spec
);
1622 return *on_call_spec
;
1625 // Adds and returns an expectation spec for this mock function.
1626 TypedExpectation
<F
>& AddNewExpectation(const char* file
, int line
,
1627 const std::string
& source_text
,
1628 const ArgumentMatcherTuple
& m
)
1629 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1630 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file
, line
);
1631 TypedExpectation
<F
>* const expectation
=
1632 new TypedExpectation
<F
>(this, file
, line
, source_text
, m
);
1633 const std::shared_ptr
<ExpectationBase
> untyped_expectation(expectation
);
1634 // See the definition of untyped_expectations_ for why access to
1635 // it is unprotected here.
1636 untyped_expectations_
.push_back(untyped_expectation
);
1638 // Adds this expectation into the implicit sequence if there is one.
1639 Sequence
* const implicit_sequence
= g_gmock_implicit_sequence
.get();
1640 if (implicit_sequence
!= nullptr) {
1641 implicit_sequence
->AddExpectation(Expectation(untyped_expectation
));
1644 return *expectation
;
1648 template <typename Func
> friend class TypedExpectation
;
1650 // Some utilities needed for implementing UntypedInvokeWith().
1652 // Describes what default action will be performed for the given
1655 void DescribeDefaultActionTo(const ArgumentTuple
& args
,
1656 ::std::ostream
* os
) const {
1657 const OnCallSpec
<F
>* const spec
= FindOnCallSpec(args
);
1659 if (spec
== nullptr) {
1660 *os
<< (std::is_void
<Result
>::value
? "returning directly.\n"
1661 : "returning default value.\n");
1663 *os
<< "taking default action specified at:\n"
1664 << FormatFileLocation(spec
->file(), spec
->line()) << "\n";
1668 // Writes a message that the call is uninteresting (i.e. neither
1669 // explicitly expected nor explicitly unexpected) to the given
1671 void UntypedDescribeUninterestingCall(const void* untyped_args
,
1672 ::std::ostream
* os
) const override
1673 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1674 const ArgumentTuple
& args
=
1675 *static_cast<const ArgumentTuple
*>(untyped_args
);
1676 *os
<< "Uninteresting mock function call - ";
1677 DescribeDefaultActionTo(args
, os
);
1678 *os
<< " Function call: " << Name();
1679 UniversalPrint(args
, os
);
1682 // Returns the expectation that matches the given function arguments
1683 // (or NULL is there's no match); when a match is found,
1684 // untyped_action is set to point to the action that should be
1685 // performed (or NULL if the action is "do default"), and
1686 // is_excessive is modified to indicate whether the call exceeds the
1689 // Critical section: We must find the matching expectation and the
1690 // corresponding action that needs to be taken in an ATOMIC
1691 // transaction. Otherwise another thread may call this mock
1692 // method in the middle and mess up the state.
1694 // However, performing the action has to be left out of the critical
1695 // section. The reason is that we have no control on what the
1696 // action does (it can invoke an arbitrary user function or even a
1697 // mock function) and excessive locking could cause a dead lock.
1698 const ExpectationBase
* UntypedFindMatchingExpectation(
1699 const void* untyped_args
, const void** untyped_action
, bool* is_excessive
,
1700 ::std::ostream
* what
, ::std::ostream
* why
) override
1701 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1702 const ArgumentTuple
& args
=
1703 *static_cast<const ArgumentTuple
*>(untyped_args
);
1704 MutexLock
l(&g_gmock_mutex
);
1705 TypedExpectation
<F
>* exp
= this->FindMatchingExpectationLocked(args
);
1706 if (exp
== nullptr) { // A match wasn't found.
1707 this->FormatUnexpectedCallMessageLocked(args
, what
, why
);
1711 // This line must be done before calling GetActionForArguments(),
1712 // which will increment the call count for *exp and thus affect
1713 // its saturation status.
1714 *is_excessive
= exp
->IsSaturated();
1715 const Action
<F
>* action
= exp
->GetActionForArguments(this, args
, what
, why
);
1716 if (action
!= nullptr && action
->IsDoDefault())
1717 action
= nullptr; // Normalize "do default" to NULL.
1718 *untyped_action
= action
;
1722 // Prints the given function arguments to the ostream.
1723 void UntypedPrintArgs(const void* untyped_args
,
1724 ::std::ostream
* os
) const override
{
1725 const ArgumentTuple
& args
=
1726 *static_cast<const ArgumentTuple
*>(untyped_args
);
1727 UniversalPrint(args
, os
);
1730 // Returns the expectation that matches the arguments, or NULL if no
1731 // expectation matches them.
1732 TypedExpectation
<F
>* FindMatchingExpectationLocked(
1733 const ArgumentTuple
& args
) const
1734 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1735 g_gmock_mutex
.AssertHeld();
1736 // See the definition of untyped_expectations_ for why access to
1737 // it is unprotected here.
1738 for (typename
UntypedExpectations::const_reverse_iterator it
=
1739 untyped_expectations_
.rbegin();
1740 it
!= untyped_expectations_
.rend(); ++it
) {
1741 TypedExpectation
<F
>* const exp
=
1742 static_cast<TypedExpectation
<F
>*>(it
->get());
1743 if (exp
->ShouldHandleArguments(args
)) {
1750 // Returns a message that the arguments don't match any expectation.
1751 void FormatUnexpectedCallMessageLocked(
1752 const ArgumentTuple
& args
,
1754 ::std::ostream
* why
) const
1755 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1756 g_gmock_mutex
.AssertHeld();
1757 *os
<< "\nUnexpected mock function call - ";
1758 DescribeDefaultActionTo(args
, os
);
1759 PrintTriedExpectationsLocked(args
, why
);
1762 // Prints a list of expectations that have been tried against the
1763 // current mock function call.
1764 void PrintTriedExpectationsLocked(
1765 const ArgumentTuple
& args
,
1766 ::std::ostream
* why
) const
1767 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1768 g_gmock_mutex
.AssertHeld();
1769 const size_t count
= untyped_expectations_
.size();
1770 *why
<< "Google Mock tried the following " << count
<< " "
1771 << (count
== 1 ? "expectation, but it didn't match" :
1772 "expectations, but none matched")
1774 for (size_t i
= 0; i
< count
; i
++) {
1775 TypedExpectation
<F
>* const expectation
=
1776 static_cast<TypedExpectation
<F
>*>(untyped_expectations_
[i
].get());
1778 expectation
->DescribeLocationTo(why
);
1780 *why
<< "tried expectation #" << i
<< ": ";
1782 *why
<< expectation
->source_text() << "...\n";
1783 expectation
->ExplainMatchResultTo(args
, why
);
1784 expectation
->DescribeCallCountTo(why
);
1787 }; // class FunctionMocker
1789 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
1791 // Reports an uninteresting call (whose description is in msg) in the
1792 // manner specified by 'reaction'.
1793 void ReportUninterestingCall(CallReaction reaction
, const std::string
& msg
);
1795 } // namespace internal
1797 // A MockFunction<F> class has one mock method whose type is F. It is
1798 // useful when you just want your test code to emit some messages and
1799 // have Google Mock verify the right messages are sent (and perhaps at
1800 // the right times). For example, if you are exercising code:
1806 // and want to verify that Foo(1) and Foo(3) both invoke
1807 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1809 // TEST(FooTest, InvokesBarCorrectly) {
1811 // MockFunction<void(string check_point_name)> check;
1815 // EXPECT_CALL(mock, Bar("a"));
1816 // EXPECT_CALL(check, Call("1"));
1817 // EXPECT_CALL(check, Call("2"));
1818 // EXPECT_CALL(mock, Bar("a"));
1827 // The expectation spec says that the first Bar("a") must happen
1828 // before check point "1", the second Bar("a") must happen after check
1829 // point "2", and nothing should happen between the two check
1830 // points. The explicit check points make it easy to tell which
1831 // Bar("a") is called by which call to Foo().
1833 // MockFunction<F> can also be used to exercise code that accepts
1834 // std::function<F> callbacks. To do so, use AsStdFunction() method
1835 // to create std::function proxy forwarding to original object's Call.
1838 // TEST(FooTest, RunsCallbackWithBarArgument) {
1839 // MockFunction<int(string)> callback;
1840 // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1841 // Foo(callback.AsStdFunction());
1843 template <typename F
>
1846 template <typename R
, typename
... Args
>
1847 class MockFunction
<R(Args
...)> {
1850 MockFunction(const MockFunction
&) = delete;
1851 MockFunction
& operator=(const MockFunction
&) = delete;
1853 std::function
<R(Args
...)> AsStdFunction() {
1854 return [this](Args
... args
) -> R
{
1855 return this->Call(std::forward
<Args
>(args
)...);
1859 // Implementation detail: the expansion of the MOCK_METHOD macro.
1860 R
Call(Args
... args
) {
1861 mock_
.SetOwnerAndName(this, "Call");
1862 return mock_
.Invoke(std::forward
<Args
>(args
)...);
1865 internal::MockSpec
<R(Args
...)> gmock_Call(Matcher
<Args
>... m
) {
1866 mock_
.RegisterOwner(this);
1867 return mock_
.With(std::move(m
)...);
1870 internal::MockSpec
<R(Args
...)> gmock_Call(const internal::WithoutMatchers
&,
1872 return this->gmock_Call(::testing::A
<Args
>()...);
1876 internal::FunctionMocker
<R(Args
...)> mock_
;
1879 // The style guide prohibits "using" statements in a namespace scope
1880 // inside a header file. However, the MockSpec class template is
1881 // meant to be defined in the ::testing namespace. The following line
1882 // is just a trick for working around a bug in MSVC 8.0, which cannot
1883 // handle it if we define MockSpec in ::testing.
1884 using internal::MockSpec
;
1886 // Const(x) is a convenient function for obtaining a const reference
1887 // to x. This is useful for setting expectations on an overloaded
1888 // const mock method, e.g.
1890 // class MockFoo : public FooInterface {
1892 // MOCK_METHOD0(Bar, int());
1893 // MOCK_CONST_METHOD0(Bar, int&());
1897 // // Expects a call to non-const MockFoo::Bar().
1898 // EXPECT_CALL(foo, Bar());
1899 // // Expects a call to const MockFoo::Bar().
1900 // EXPECT_CALL(Const(foo), Bar());
1901 template <typename T
>
1902 inline const T
& Const(const T
& x
) { return x
; }
1904 // Constructs an Expectation object that references and co-owns exp.
1905 inline Expectation::Expectation(internal::ExpectationBase
& exp
) // NOLINT
1906 : expectation_base_(exp
.GetHandle().expectation_base()) {}
1908 } // namespace testing
1910 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1912 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1913 // required to avoid compile errors when the name of the method used in call is
1914 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1915 // tests in internal/gmock-spec-builders_test.cc for more details.
1917 // This macro supports statements both with and without parameter matchers. If
1918 // the parameter list is omitted, gMock will accept any parameters, which allows
1919 // tests to be written that don't need to encode the number of method
1920 // parameter. This technique may only be used for non-overloaded methods.
1922 // // These are the same:
1923 // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1924 // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
1927 // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1928 // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
1930 // // Can also specify args if you want, of course:
1931 // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
1933 // // Overloads work as long as you specify parameters:
1934 // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1935 // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
1937 // // Oops! Which overload did you want?
1938 // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
1939 // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1941 // How this works: The mock class uses two overloads of the gmock_Method
1942 // expectation setter method plus an operator() overload on the MockSpec object.
1943 // In the matcher list form, the macro expands to:
1945 // // This statement:
1946 // ON_CALL(mock, TwoArgsMethod(_, 45))...
1948 // // ...expands to:
1949 // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
1950 // |-------------v---------------||------------v-------------|
1951 // invokes first overload swallowed by operator()
1953 // // ...which is essentially:
1954 // mock.gmock_TwoArgsMethod(_, 45)...
1956 // Whereas the form without a matcher list:
1958 // // This statement:
1959 // ON_CALL(mock, TwoArgsMethod)...
1961 // // ...expands to:
1962 // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
1963 // |-----------------------v--------------------------|
1964 // invokes second overload
1966 // // ...which is essentially:
1967 // mock.gmock_TwoArgsMethod(_, _)...
1969 // The WithoutMatchers() argument is used to disambiguate overloads and to
1970 // block the caller from accidentally invoking the second overload directly. The
1971 // second argument is an internal type derived from the method signature. The
1972 // failure to disambiguate two overloads of this method in the ON_CALL statement
1973 // is how we block callers from setting expectations on overloaded methods.
1974 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1975 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
1977 .Setter(__FILE__, __LINE__, #mock_expr, #call)
1979 #define ON_CALL(obj, call) \
1980 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1982 #define EXPECT_CALL(obj, call) \
1983 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
1985 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_