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.
31 // Google Mock - a framework for writing C++ mock classes.
33 // This file implements the ON_CALL() and EXPECT_CALL() macros.
35 // A user can use the ON_CALL() macro to specify the default action of
36 // a mock method. The syntax is:
38 // ON_CALL(mock_object, Method(argument-matchers))
39 // .With(multi-argument-matcher)
40 // .WillByDefault(action);
42 // where the .With() clause is optional.
44 // A user can use the EXPECT_CALL() macro to specify an expectation on
45 // a mock method. The syntax is:
47 // EXPECT_CALL(mock_object, Method(argument-matchers))
48 // .With(multi-argument-matchers)
49 // .Times(cardinality)
50 // .InSequence(sequences)
51 // .After(expectations)
53 // .WillRepeatedly(action)
54 // .RetiresOnSaturation();
56 // where all clauses are optional, and .InSequence()/.After()/
57 // .WillOnce() can appear any number of times.
59 // GOOGLETEST_CM0002 DO NOT DELETE
61 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
70 #include <type_traits>
73 #include "gmock/gmock-actions.h"
74 #include "gmock/gmock-cardinalities.h"
75 #include "gmock/gmock-matchers.h"
76 #include "gmock/internal/gmock-internal-utils.h"
77 #include "gmock/internal/gmock-port.h"
78 #include "gtest/gtest.h"
80 #if GTEST_HAS_EXCEPTIONS
81 # include <stdexcept> // NOLINT
84 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
85 /* class A needs to have dll-interface to be used by clients of class B */)
89 // An abstract handle of an expectation.
92 // A set of expectation handles.
95 // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
96 // and MUST NOT BE USED IN USER CODE!!!
99 // Implements a mock function.
100 template <typename F
> class FunctionMocker
;
102 // Base class for expectations.
103 class ExpectationBase
;
105 // Implements an expectation.
106 template <typename F
> class TypedExpectation
;
108 // Helper class for testing the Expectation class template.
109 class ExpectationTester
;
111 // Protects the mock object registry (in class Mock), all function
112 // mockers, and all expectations.
114 // The reason we don't use more fine-grained protection is: when a
115 // mock function Foo() is called, it needs to consult its expectations
116 // to see which one should be picked. If another thread is allowed to
117 // call a mock function (either Foo() or a different one) at the same
118 // time, it could affect the "retired" attributes of Foo()'s
119 // expectations when InSequence() is used, and thus affect which
120 // expectation gets picked. Therefore, we sequence all mock function
121 // calls to ensure the integrity of the mock objects' states.
122 GTEST_API_
GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex
);
124 // Untyped base class for ActionResultHolder<R>.
125 class UntypedActionResultHolderBase
;
127 // Abstract base class of FunctionMocker. This is the
128 // type-agnostic part of the function mocker interface. Its pure
129 // virtual methods are implemented by FunctionMocker.
130 class GTEST_API_ UntypedFunctionMockerBase
{
132 UntypedFunctionMockerBase();
133 virtual ~UntypedFunctionMockerBase();
135 // Verifies that all expectations on this mock function have been
136 // satisfied. Reports one or more Google Test non-fatal failures
137 // and returns false if not.
138 bool VerifyAndClearExpectationsLocked()
139 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
141 // Clears the ON_CALL()s set on this mock function.
142 virtual void ClearDefaultActionsLocked()
143 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) = 0;
145 // In all of the following Untyped* functions, it's the caller's
146 // responsibility to guarantee the correctness of the arguments'
149 // Performs the default action with the given arguments and returns
150 // the action's result. The call description string will be used in
151 // the error message to describe the call in the case the default
154 virtual UntypedActionResultHolderBase
* UntypedPerformDefaultAction(
155 void* untyped_args
, const std::string
& call_description
) const = 0;
157 // Performs the given action with the given arguments and returns
158 // the action's result.
160 virtual UntypedActionResultHolderBase
* UntypedPerformAction(
161 const void* untyped_action
, void* untyped_args
) const = 0;
163 // Writes a message that the call is uninteresting (i.e. neither
164 // explicitly expected nor explicitly unexpected) to the given
166 virtual void UntypedDescribeUninterestingCall(
167 const void* untyped_args
,
168 ::std::ostream
* os
) const
169 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) = 0;
171 // Returns the expectation that matches the given function arguments
172 // (or NULL is there's no match); when a match is found,
173 // untyped_action is set to point to the action that should be
174 // performed (or NULL if the action is "do default"), and
175 // is_excessive is modified to indicate whether the call exceeds the
177 virtual const ExpectationBase
* UntypedFindMatchingExpectation(
178 const void* untyped_args
,
179 const void** untyped_action
, bool* is_excessive
,
180 ::std::ostream
* what
, ::std::ostream
* why
)
181 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) = 0;
183 // Prints the given function arguments to the ostream.
184 virtual void UntypedPrintArgs(const void* untyped_args
,
185 ::std::ostream
* os
) const = 0;
187 // Sets the mock object this mock method belongs to, and registers
188 // this information in the global mock registry. Will be called
189 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
191 void RegisterOwner(const void* mock_obj
)
192 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
194 // Sets the mock object this mock method belongs to, and sets the
195 // name of the mock function. Will be called upon each invocation
196 // of this mock function.
197 void SetOwnerAndName(const void* mock_obj
, const char* name
)
198 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
200 // Returns the mock object this mock method belongs to. Must be
201 // called after RegisterOwner() or SetOwnerAndName() has been
203 const void* MockObject() const
204 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
206 // Returns the name of this mock method. Must be called after
207 // SetOwnerAndName() has been called.
208 const char* Name() const
209 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
211 // Returns the result of invoking this mock function with the given
212 // arguments. This function can be safely called from multiple
213 // threads concurrently. The caller is responsible for deleting the
215 UntypedActionResultHolderBase
* UntypedInvokeWith(void* untyped_args
)
216 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
);
219 typedef std::vector
<const void*> UntypedOnCallSpecs
;
221 using UntypedExpectations
= std::vector
<std::shared_ptr
<ExpectationBase
>>;
223 // Returns an Expectation object that references and co-owns exp,
224 // which must be an expectation on this mock function.
225 Expectation
GetHandleOf(ExpectationBase
* exp
);
227 // Address of the mock object this mock method belongs to. Only
228 // valid after this mock method has been called or
229 // ON_CALL/EXPECT_CALL has been invoked on it.
230 const void* mock_obj_
; // Protected by g_gmock_mutex.
232 // Name of the function being mocked. Only valid after this mock
233 // method has been called.
234 const char* name_
; // Protected by g_gmock_mutex.
236 // All default action specs for this function mocker.
237 UntypedOnCallSpecs untyped_on_call_specs_
;
239 // All expectations for this function mocker.
241 // It's undefined behavior to interleave expectations (EXPECT_CALLs
242 // or ON_CALLs) and mock function calls. Also, the order of
243 // expectations is important. Therefore it's a logic race condition
244 // to read/write untyped_expectations_ concurrently. In order for
245 // tools like tsan to catch concurrent read/write accesses to
246 // untyped_expectations, we deliberately leave accesses to it
248 UntypedExpectations untyped_expectations_
;
249 }; // class UntypedFunctionMockerBase
251 // Untyped base class for OnCallSpec<F>.
252 class UntypedOnCallSpecBase
{
254 // The arguments are the location of the ON_CALL() statement.
255 UntypedOnCallSpecBase(const char* a_file
, int a_line
)
256 : file_(a_file
), line_(a_line
), last_clause_(kNone
) {}
258 // Where in the source file was the default action spec defined?
259 const char* file() const { return file_
; }
260 int line() const { return line_
; }
263 // Gives each clause in the ON_CALL() statement a name.
265 // Do not change the order of the enum members! The run-time
266 // syntax checking relies on it.
272 // Asserts that the ON_CALL() statement has a certain property.
273 void AssertSpecProperty(bool property
,
274 const std::string
& failure_message
) const {
275 Assert(property
, file_
, line_
, failure_message
);
278 // Expects that the ON_CALL() statement has a certain property.
279 void ExpectSpecProperty(bool property
,
280 const std::string
& failure_message
) const {
281 Expect(property
, file_
, line_
, failure_message
);
287 // The last clause in the ON_CALL() statement as seen so far.
288 // Initially kNone and changes as the statement is parsed.
290 }; // class UntypedOnCallSpecBase
292 // This template class implements an ON_CALL spec.
293 template <typename F
>
294 class OnCallSpec
: public UntypedOnCallSpecBase
{
296 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
297 typedef typename Function
<F
>::ArgumentMatcherTuple ArgumentMatcherTuple
;
299 // Constructs an OnCallSpec object from the information inside
300 // the parenthesis of an ON_CALL() statement.
301 OnCallSpec(const char* a_file
, int a_line
,
302 const ArgumentMatcherTuple
& matchers
)
303 : UntypedOnCallSpecBase(a_file
, a_line
),
305 // By default, extra_matcher_ should match anything. However,
306 // we cannot initialize it with _ as that causes ambiguity between
307 // Matcher's copy and move constructor for some argument types.
308 extra_matcher_(A
<const ArgumentTuple
&>()) {}
310 // Implements the .With() clause.
311 OnCallSpec
& With(const Matcher
<const ArgumentTuple
&>& m
) {
312 // Makes sure this is called at most once.
313 ExpectSpecProperty(last_clause_
< kWith
,
314 ".With() cannot appear "
315 "more than once in an ON_CALL().");
316 last_clause_
= kWith
;
322 // Implements the .WillByDefault() clause.
323 OnCallSpec
& WillByDefault(const Action
<F
>& action
) {
324 ExpectSpecProperty(last_clause_
< kWillByDefault
,
325 ".WillByDefault() must appear "
326 "exactly once in an ON_CALL().");
327 last_clause_
= kWillByDefault
;
329 ExpectSpecProperty(!action
.IsDoDefault(),
330 "DoDefault() cannot be used in ON_CALL().");
335 // Returns true if and only if the given arguments match the matchers.
336 bool Matches(const ArgumentTuple
& args
) const {
337 return TupleMatches(matchers_
, args
) && extra_matcher_
.Matches(args
);
340 // Returns the action specified by the user.
341 const Action
<F
>& GetAction() const {
342 AssertSpecProperty(last_clause_
== kWillByDefault
,
343 ".WillByDefault() must appear exactly "
344 "once in an ON_CALL().");
349 // The information in statement
351 // ON_CALL(mock_object, Method(matchers))
352 // .With(multi-argument-matcher)
353 // .WillByDefault(action);
355 // is recorded in the data members like this:
357 // source file that contains the statement => file_
358 // line number of the statement => line_
359 // matchers => matchers_
360 // multi-argument-matcher => extra_matcher_
362 ArgumentMatcherTuple matchers_
;
363 Matcher
<const ArgumentTuple
&> extra_matcher_
;
365 }; // class OnCallSpec
367 // Possible reactions on uninteresting calls.
374 } // namespace internal
376 // Utilities for manipulating mock objects.
377 class GTEST_API_ Mock
{
379 // The following public methods can be called concurrently.
381 // Tells Google Mock to ignore mock_obj when checking for leaked
383 static void AllowLeak(const void* mock_obj
)
384 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
386 // Verifies and clears all expectations on the given mock object.
387 // If the expectations aren't satisfied, generates one or more
388 // Google Test non-fatal failures and returns false.
389 static bool VerifyAndClearExpectations(void* mock_obj
)
390 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
392 // Verifies all expectations on the given mock object and clears its
393 // default actions and expectations. Returns true if and only if the
394 // verification was successful.
395 static bool VerifyAndClear(void* mock_obj
)
396 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
398 // Returns whether the mock was created as a naggy mock (default)
399 static bool IsNaggy(void* mock_obj
)
400 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
401 // Returns whether the mock was created as a nice mock
402 static bool IsNice(void* mock_obj
)
403 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
404 // Returns whether the mock was created as a strict mock
405 static bool IsStrict(void* mock_obj
)
406 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
409 friend class internal::UntypedFunctionMockerBase
;
411 // Needed for a function mocker to register itself (so that we know
412 // how to clear a mock object).
413 template <typename F
>
414 friend class internal::FunctionMocker
;
416 template <typename M
>
417 friend class NiceMock
;
419 template <typename M
>
420 friend class NaggyMock
;
422 template <typename M
>
423 friend class StrictMock
;
425 // Tells Google Mock to allow uninteresting calls on the given mock
427 static void AllowUninterestingCalls(const void* mock_obj
)
428 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
430 // Tells Google Mock to warn the user about uninteresting calls on
431 // the given mock object.
432 static void WarnUninterestingCalls(const void* mock_obj
)
433 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
435 // Tells Google Mock to fail uninteresting calls on the given mock
437 static void FailUninterestingCalls(const void* mock_obj
)
438 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
440 // Tells Google Mock the given mock object is being destroyed and
441 // its entry in the call-reaction table should be removed.
442 static void UnregisterCallReaction(const void* mock_obj
)
443 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
445 // Returns the reaction Google Mock will have on uninteresting calls
446 // made on the given mock object.
447 static internal::CallReaction
GetReactionOnUninterestingCalls(
448 const void* mock_obj
)
449 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
451 // Verifies that all expectations on the given mock object have been
452 // satisfied. Reports one or more Google Test non-fatal failures
453 // and returns false if not.
454 static bool VerifyAndClearExpectationsLocked(void* mock_obj
)
455 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
);
457 // Clears all ON_CALL()s set on the given mock object.
458 static void ClearDefaultActionsLocked(void* mock_obj
)
459 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
);
461 // Registers a mock object and a mock method it owns.
462 static void Register(
463 const void* mock_obj
,
464 internal::UntypedFunctionMockerBase
* mocker
)
465 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
467 // Tells Google Mock where in the source code mock_obj is used in an
468 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
469 // information helps the user identify which object it is.
470 static void RegisterUseByOnCallOrExpectCall(
471 const void* mock_obj
, const char* file
, int line
)
472 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
);
474 // Unregisters a mock method; removes the owning mock object from
475 // the registry when the last mock method associated with it has
476 // been unregistered. This is called only in the destructor of
478 static void UnregisterLocked(internal::UntypedFunctionMockerBase
* mocker
)
479 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
);
482 // An abstract handle of an expectation. Useful in the .After()
483 // clause of EXPECT_CALL() for setting the (partial) order of
484 // expectations. The syntax:
486 // Expectation e1 = EXPECT_CALL(...)...;
487 // EXPECT_CALL(...).After(e1)...;
489 // sets two expectations where the latter can only be matched after
490 // the former has been satisfied.
493 // - This class is copyable and has value semantics.
494 // - Constness is shallow: a const Expectation object itself cannot
495 // be modified, but the mutable methods of the ExpectationBase
496 // object it references can be called via expectation_base().
498 class GTEST_API_ Expectation
{
500 // Constructs a null object that doesn't reference any expectation.
505 // This single-argument ctor must not be explicit, in order to support the
506 // Expectation e = EXPECT_CALL(...);
509 // A TypedExpectation object stores its pre-requisites as
510 // Expectation objects, and needs to call the non-const Retire()
511 // method on the ExpectationBase objects they reference. Therefore
512 // Expectation must receive a *non-const* reference to the
513 // ExpectationBase object.
514 Expectation(internal::ExpectationBase
& exp
); // NOLINT
516 // The compiler-generated copy ctor and operator= work exactly as
517 // intended, so we don't need to define our own.
519 // Returns true if and only if rhs references the same expectation as this
521 bool operator==(const Expectation
& rhs
) const {
522 return expectation_base_
== rhs
.expectation_base_
;
525 bool operator!=(const Expectation
& rhs
) const { return !(*this == rhs
); }
528 friend class ExpectationSet
;
529 friend class Sequence
;
530 friend class ::testing::internal::ExpectationBase
;
531 friend class ::testing::internal::UntypedFunctionMockerBase
;
533 template <typename F
>
534 friend class ::testing::internal::FunctionMocker
;
536 template <typename F
>
537 friend class ::testing::internal::TypedExpectation
;
539 // This comparator is needed for putting Expectation objects into a set.
542 bool operator()(const Expectation
& lhs
, const Expectation
& rhs
) const {
543 return lhs
.expectation_base_
.get() < rhs
.expectation_base_
.get();
547 typedef ::std::set
<Expectation
, Less
> Set
;
550 const std::shared_ptr
<internal::ExpectationBase
>& expectation_base
);
552 // Returns the expectation this object references.
553 const std::shared_ptr
<internal::ExpectationBase
>& expectation_base() const {
554 return expectation_base_
;
557 // A shared_ptr that co-owns the expectation this handle references.
558 std::shared_ptr
<internal::ExpectationBase
> expectation_base_
;
561 // A set of expectation handles. Useful in the .After() clause of
562 // EXPECT_CALL() for setting the (partial) order of expectations. The
565 // ExpectationSet es;
566 // es += EXPECT_CALL(...)...;
567 // es += EXPECT_CALL(...)...;
568 // EXPECT_CALL(...).After(es)...;
570 // sets three expectations where the last one can only be matched
571 // after the first two have both been satisfied.
573 // This class is copyable and has value semantics.
574 class ExpectationSet
{
576 // A bidirectional iterator that can read a const element in the set.
577 typedef Expectation::Set::const_iterator const_iterator
;
579 // An object stored in the set. This is an alias of Expectation.
580 typedef Expectation::Set::value_type value_type
;
582 // Constructs an empty set.
585 // This single-argument ctor must not be explicit, in order to support the
586 // ExpectationSet es = EXPECT_CALL(...);
588 ExpectationSet(internal::ExpectationBase
& exp
) { // NOLINT
589 *this += Expectation(exp
);
592 // This single-argument ctor implements implicit conversion from
593 // Expectation and thus must not be explicit. This allows either an
594 // Expectation or an ExpectationSet to be used in .After().
595 ExpectationSet(const Expectation
& e
) { // NOLINT
599 // The compiler-generator ctor and operator= works exactly as
600 // intended, so we don't need to define our own.
602 // Returns true if and only if rhs contains the same set of Expectation
603 // objects as this does.
604 bool operator==(const ExpectationSet
& rhs
) const {
605 return expectations_
== rhs
.expectations_
;
608 bool operator!=(const ExpectationSet
& rhs
) const { return !(*this == rhs
); }
610 // Implements the syntax
611 // expectation_set += EXPECT_CALL(...);
612 ExpectationSet
& operator+=(const Expectation
& e
) {
613 expectations_
.insert(e
);
617 int size() const { return static_cast<int>(expectations_
.size()); }
619 const_iterator
begin() const { return expectations_
.begin(); }
620 const_iterator
end() const { return expectations_
.end(); }
623 Expectation::Set expectations_
;
627 // Sequence objects are used by a user to specify the relative order
628 // in which the expectations should match. They are copyable (we rely
629 // on the compiler-defined copy constructor and assignment operator).
630 class GTEST_API_ Sequence
{
632 // Constructs an empty sequence.
633 Sequence() : last_expectation_(new Expectation
) {}
635 // Adds an expectation to this sequence. The caller must ensure
636 // that no other thread is accessing this Sequence object.
637 void AddExpectation(const Expectation
& expectation
) const;
640 // The last expectation in this sequence.
641 std::shared_ptr
<Expectation
> last_expectation_
;
644 // An object of this type causes all EXPECT_CALL() statements
645 // encountered in its scope to be put in an anonymous sequence. The
646 // work is done in the constructor and destructor. You should only
647 // create an InSequence object on the stack.
649 // The sole purpose for this class is to support easy definition of
650 // sequential expectations, e.g.
653 // InSequence dummy; // The name of the object doesn't matter.
655 // // The following expectations must match in the order they appear.
656 // EXPECT_CALL(a, Bar())...;
657 // EXPECT_CALL(a, Baz())...;
659 // EXPECT_CALL(b, Xyz())...;
662 // You can create InSequence objects in multiple threads, as long as
663 // they are used to affect different mock objects. The idea is that
664 // each thread can create and set up its own mocks as if it's the only
665 // thread. However, for clarity of your tests we recommend you to set
666 // up mocks in the main thread unless you have a good reason not to do
668 class GTEST_API_ InSequence
{
673 bool sequence_created_
;
675 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence
); // NOLINT
676 } GTEST_ATTRIBUTE_UNUSED_
;
680 // Points to the implicit sequence introduced by a living InSequence
681 // object (if any) in the current thread or NULL.
682 GTEST_API_
extern ThreadLocal
<Sequence
*> g_gmock_implicit_sequence
;
684 // Base class for implementing expectations.
686 // There are two reasons for having a type-agnostic base class for
689 // 1. We need to store collections of expectations of different
690 // types (e.g. all pre-requisites of a particular expectation, all
691 // expectations in a sequence). Therefore these expectation objects
692 // must share a common base class.
694 // 2. We can avoid binary code bloat by moving methods not depending
695 // on the template argument of Expectation to the base class.
697 // This class is internal and mustn't be used by user code directly.
698 class GTEST_API_ ExpectationBase
{
700 // source_text is the EXPECT_CALL(...) source that created this Expectation.
701 ExpectationBase(const char* file
, int line
, const std::string
& source_text
);
703 virtual ~ExpectationBase();
705 // Where in the source file was the expectation spec defined?
706 const char* file() const { return file_
; }
707 int line() const { return line_
; }
708 const char* source_text() const { return source_text_
.c_str(); }
709 // Returns the cardinality specified in the expectation spec.
710 const Cardinality
& cardinality() const { return cardinality_
; }
712 // Describes the source file location of this expectation.
713 void DescribeLocationTo(::std::ostream
* os
) const {
714 *os
<< FormatFileLocation(file(), line()) << " ";
717 // Describes how many times a function call matching this
718 // expectation has occurred.
719 void DescribeCallCountTo(::std::ostream
* os
) const
720 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
722 // If this mock method has an extra matcher (i.e. .With(matcher)),
723 // describes it to the ostream.
724 virtual void MaybeDescribeExtraMatcherTo(::std::ostream
* os
) = 0;
727 friend class ::testing::Expectation
;
728 friend class UntypedFunctionMockerBase
;
731 // Don't change the order of the enum members!
742 typedef std::vector
<const void*> UntypedActions
;
744 // Returns an Expectation object that references and co-owns this
746 virtual Expectation
GetHandle() = 0;
748 // Asserts that the EXPECT_CALL() statement has the given property.
749 void AssertSpecProperty(bool property
,
750 const std::string
& failure_message
) const {
751 Assert(property
, file_
, line_
, failure_message
);
754 // Expects that the EXPECT_CALL() statement has the given property.
755 void ExpectSpecProperty(bool property
,
756 const std::string
& failure_message
) const {
757 Expect(property
, file_
, line_
, failure_message
);
760 // Explicitly specifies the cardinality of this expectation. Used
761 // by the subclasses to implement the .Times() clause.
762 void SpecifyCardinality(const Cardinality
& cardinality
);
764 // Returns true if and only if the user specified the cardinality
765 // explicitly using a .Times().
766 bool cardinality_specified() const { return cardinality_specified_
; }
768 // Sets the cardinality of this expectation spec.
769 void set_cardinality(const Cardinality
& a_cardinality
) {
770 cardinality_
= a_cardinality
;
773 // The following group of methods should only be called after the
774 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
775 // the current thread.
777 // Retires all pre-requisites of this expectation.
778 void RetireAllPreRequisites()
779 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
781 // Returns true if and only if this expectation is retired.
782 bool is_retired() const
783 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
784 g_gmock_mutex
.AssertHeld();
788 // Retires this expectation.
790 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
791 g_gmock_mutex
.AssertHeld();
795 // Returns true if and only if this expectation is satisfied.
796 bool IsSatisfied() const
797 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
798 g_gmock_mutex
.AssertHeld();
799 return cardinality().IsSatisfiedByCallCount(call_count_
);
802 // Returns true if and only if this expectation is saturated.
803 bool IsSaturated() const
804 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
805 g_gmock_mutex
.AssertHeld();
806 return cardinality().IsSaturatedByCallCount(call_count_
);
809 // Returns true if and only if this expectation is over-saturated.
810 bool IsOverSaturated() const
811 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
812 g_gmock_mutex
.AssertHeld();
813 return cardinality().IsOverSaturatedByCallCount(call_count_
);
816 // Returns true if and only if all pre-requisites of this expectation are
818 bool AllPrerequisitesAreSatisfied() const
819 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
821 // Adds unsatisfied pre-requisites of this expectation to 'result'.
822 void FindUnsatisfiedPrerequisites(ExpectationSet
* result
) const
823 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
825 // Returns the number this expectation has been invoked.
826 int call_count() const
827 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
828 g_gmock_mutex
.AssertHeld();
832 // Increments the number this expectation has been invoked.
833 void IncrementCallCount()
834 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
835 g_gmock_mutex
.AssertHeld();
839 // Checks the action count (i.e. the number of WillOnce() and
840 // WillRepeatedly() clauses) against the cardinality if this hasn't
841 // been done before. Prints a warning if there are too many or too
843 void CheckActionCountIfNotDone() const
844 GTEST_LOCK_EXCLUDED_(mutex_
);
846 friend class ::testing::Sequence
;
847 friend class ::testing::internal::ExpectationTester
;
849 template <typename Function
>
850 friend class TypedExpectation
;
852 // Implements the .Times() clause.
853 void UntypedTimes(const Cardinality
& a_cardinality
);
855 // This group of fields are part of the spec and won't change after
856 // an EXPECT_CALL() statement finishes.
857 const char* file_
; // The file that contains the expectation.
858 int line_
; // The line number of the expectation.
859 const std::string source_text_
; // The EXPECT_CALL(...) source text.
860 // True if and only if the cardinality is specified explicitly.
861 bool cardinality_specified_
;
862 Cardinality cardinality_
; // The cardinality of the expectation.
863 // The immediate pre-requisites (i.e. expectations that must be
864 // satisfied before this expectation can be matched) of this
865 // expectation. We use std::shared_ptr in the set because we want an
866 // Expectation object to be co-owned by its FunctionMocker and its
867 // successors. This allows multiple mock objects to be deleted at
869 ExpectationSet immediate_prerequisites_
;
871 // This group of fields are the current state of the expectation,
872 // and can change as the mock function is called.
873 int call_count_
; // How many times this expectation has been invoked.
874 bool retired_
; // True if and only if this expectation has retired.
875 UntypedActions untyped_actions_
;
876 bool extra_matcher_specified_
;
877 bool repeated_action_specified_
; // True if a WillRepeatedly() was specified.
878 bool retires_on_saturation_
;
880 mutable bool action_count_checked_
; // Under mutex_.
881 mutable Mutex mutex_
; // Protects action_count_checked_.
883 GTEST_DISALLOW_ASSIGN_(ExpectationBase
);
884 }; // class ExpectationBase
886 // Impements an expectation for the given function type.
887 template <typename F
>
888 class TypedExpectation
: public ExpectationBase
{
890 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
891 typedef typename Function
<F
>::ArgumentMatcherTuple ArgumentMatcherTuple
;
892 typedef typename Function
<F
>::Result Result
;
894 TypedExpectation(FunctionMocker
<F
>* owner
, const char* a_file
, int a_line
,
895 const std::string
& a_source_text
,
896 const ArgumentMatcherTuple
& m
)
897 : ExpectationBase(a_file
, a_line
, a_source_text
),
900 // By default, extra_matcher_ should match anything. However,
901 // we cannot initialize it with _ as that causes ambiguity between
902 // Matcher's copy and move constructor for some argument types.
903 extra_matcher_(A
<const ArgumentTuple
&>()),
904 repeated_action_(DoDefault()) {}
906 ~TypedExpectation() override
{
907 // Check the validity of the action count if it hasn't been done
908 // yet (for example, if the expectation was never used).
909 CheckActionCountIfNotDone();
910 for (UntypedActions::const_iterator it
= untyped_actions_
.begin();
911 it
!= untyped_actions_
.end(); ++it
) {
912 delete static_cast<const Action
<F
>*>(*it
);
916 // Implements the .With() clause.
917 TypedExpectation
& With(const Matcher
<const ArgumentTuple
&>& m
) {
918 if (last_clause_
== kWith
) {
919 ExpectSpecProperty(false,
920 ".With() cannot appear "
921 "more than once in an EXPECT_CALL().");
923 ExpectSpecProperty(last_clause_
< kWith
,
924 ".With() must be the first "
925 "clause in an EXPECT_CALL().");
927 last_clause_
= kWith
;
930 extra_matcher_specified_
= true;
934 // Implements the .Times() clause.
935 TypedExpectation
& Times(const Cardinality
& a_cardinality
) {
936 ExpectationBase::UntypedTimes(a_cardinality
);
940 // Implements the .Times() clause.
941 TypedExpectation
& Times(int n
) {
942 return Times(Exactly(n
));
945 // Implements the .InSequence() clause.
946 TypedExpectation
& InSequence(const Sequence
& s
) {
947 ExpectSpecProperty(last_clause_
<= kInSequence
,
948 ".InSequence() cannot appear after .After(),"
949 " .WillOnce(), .WillRepeatedly(), or "
950 ".RetiresOnSaturation().");
951 last_clause_
= kInSequence
;
953 s
.AddExpectation(GetHandle());
956 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
) {
957 return InSequence(s1
).InSequence(s2
);
959 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
960 const Sequence
& s3
) {
961 return InSequence(s1
, s2
).InSequence(s3
);
963 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
964 const Sequence
& s3
, const Sequence
& s4
) {
965 return InSequence(s1
, s2
, s3
).InSequence(s4
);
967 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
968 const Sequence
& s3
, const Sequence
& s4
,
969 const Sequence
& s5
) {
970 return InSequence(s1
, s2
, s3
, s4
).InSequence(s5
);
973 // Implements that .After() clause.
974 TypedExpectation
& After(const ExpectationSet
& s
) {
975 ExpectSpecProperty(last_clause_
<= kAfter
,
976 ".After() cannot appear after .WillOnce(),"
977 " .WillRepeatedly(), or "
978 ".RetiresOnSaturation().");
979 last_clause_
= kAfter
;
981 for (ExpectationSet::const_iterator it
= s
.begin(); it
!= s
.end(); ++it
) {
982 immediate_prerequisites_
+= *it
;
986 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
) {
987 return After(s1
).After(s2
);
989 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
990 const ExpectationSet
& s3
) {
991 return After(s1
, s2
).After(s3
);
993 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
994 const ExpectationSet
& s3
, const ExpectationSet
& s4
) {
995 return After(s1
, s2
, s3
).After(s4
);
997 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
998 const ExpectationSet
& s3
, const ExpectationSet
& s4
,
999 const ExpectationSet
& s5
) {
1000 return After(s1
, s2
, s3
, s4
).After(s5
);
1003 // Implements the .WillOnce() clause.
1004 TypedExpectation
& WillOnce(const Action
<F
>& action
) {
1005 ExpectSpecProperty(last_clause_
<= kWillOnce
,
1006 ".WillOnce() cannot appear after "
1007 ".WillRepeatedly() or .RetiresOnSaturation().");
1008 last_clause_
= kWillOnce
;
1010 untyped_actions_
.push_back(new Action
<F
>(action
));
1011 if (!cardinality_specified()) {
1012 set_cardinality(Exactly(static_cast<int>(untyped_actions_
.size())));
1017 // Implements the .WillRepeatedly() clause.
1018 TypedExpectation
& WillRepeatedly(const Action
<F
>& action
) {
1019 if (last_clause_
== kWillRepeatedly
) {
1020 ExpectSpecProperty(false,
1021 ".WillRepeatedly() cannot appear "
1022 "more than once in an EXPECT_CALL().");
1024 ExpectSpecProperty(last_clause_
< kWillRepeatedly
,
1025 ".WillRepeatedly() cannot appear "
1026 "after .RetiresOnSaturation().");
1028 last_clause_
= kWillRepeatedly
;
1029 repeated_action_specified_
= true;
1031 repeated_action_
= action
;
1032 if (!cardinality_specified()) {
1033 set_cardinality(AtLeast(static_cast<int>(untyped_actions_
.size())));
1036 // Now that no more action clauses can be specified, we check
1037 // whether their count makes sense.
1038 CheckActionCountIfNotDone();
1042 // Implements the .RetiresOnSaturation() clause.
1043 TypedExpectation
& RetiresOnSaturation() {
1044 ExpectSpecProperty(last_clause_
< kRetiresOnSaturation
,
1045 ".RetiresOnSaturation() cannot appear "
1047 last_clause_
= kRetiresOnSaturation
;
1048 retires_on_saturation_
= true;
1050 // Now that no more action clauses can be specified, we check
1051 // whether their count makes sense.
1052 CheckActionCountIfNotDone();
1056 // Returns the matchers for the arguments as specified inside the
1057 // EXPECT_CALL() macro.
1058 const ArgumentMatcherTuple
& matchers() const {
1062 // Returns the matcher specified by the .With() clause.
1063 const Matcher
<const ArgumentTuple
&>& extra_matcher() const {
1064 return extra_matcher_
;
1067 // Returns the action specified by the .WillRepeatedly() clause.
1068 const Action
<F
>& repeated_action() const { return repeated_action_
; }
1070 // If this mock method has an extra matcher (i.e. .With(matcher)),
1071 // describes it to the ostream.
1072 void MaybeDescribeExtraMatcherTo(::std::ostream
* os
) override
{
1073 if (extra_matcher_specified_
) {
1074 *os
<< " Expected args: ";
1075 extra_matcher_
.DescribeTo(os
);
1081 template <typename Function
>
1082 friend class FunctionMocker
;
1084 // Returns an Expectation object that references and co-owns this
1086 Expectation
GetHandle() override
{ return owner_
->GetHandleOf(this); }
1088 // The following methods will be called only after the EXPECT_CALL()
1089 // statement finishes and when the current thread holds
1092 // Returns true if and only if this expectation matches the given arguments.
1093 bool Matches(const ArgumentTuple
& args
) const
1094 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1095 g_gmock_mutex
.AssertHeld();
1096 return TupleMatches(matchers_
, args
) && extra_matcher_
.Matches(args
);
1099 // Returns true if and only if this expectation should handle the given
1101 bool ShouldHandleArguments(const ArgumentTuple
& args
) const
1102 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1103 g_gmock_mutex
.AssertHeld();
1105 // In case the action count wasn't checked when the expectation
1106 // was defined (e.g. if this expectation has no WillRepeatedly()
1107 // or RetiresOnSaturation() clause), we check it when the
1108 // expectation is used for the first time.
1109 CheckActionCountIfNotDone();
1110 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args
);
1113 // Describes the result of matching the arguments against this
1114 // expectation to the given ostream.
1115 void ExplainMatchResultTo(
1116 const ArgumentTuple
& args
,
1117 ::std::ostream
* os
) const
1118 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1119 g_gmock_mutex
.AssertHeld();
1122 *os
<< " Expected: the expectation is active\n"
1123 << " Actual: it is retired\n";
1124 } else if (!Matches(args
)) {
1125 if (!TupleMatches(matchers_
, args
)) {
1126 ExplainMatchFailureTupleTo(matchers_
, args
, os
);
1128 StringMatchResultListener listener
;
1129 if (!extra_matcher_
.MatchAndExplain(args
, &listener
)) {
1130 *os
<< " Expected args: ";
1131 extra_matcher_
.DescribeTo(os
);
1132 *os
<< "\n Actual: don't match";
1134 internal::PrintIfNotEmpty(listener
.str(), os
);
1137 } else if (!AllPrerequisitesAreSatisfied()) {
1138 *os
<< " Expected: all pre-requisites are satisfied\n"
1139 << " Actual: the following immediate pre-requisites "
1140 << "are not satisfied:\n";
1141 ExpectationSet unsatisfied_prereqs
;
1142 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs
);
1144 for (ExpectationSet::const_iterator it
= unsatisfied_prereqs
.begin();
1145 it
!= unsatisfied_prereqs
.end(); ++it
) {
1146 it
->expectation_base()->DescribeLocationTo(os
);
1147 *os
<< "pre-requisite #" << i
++ << "\n";
1149 *os
<< " (end of pre-requisites)\n";
1151 // This line is here just for completeness' sake. It will never
1152 // be executed as currently the ExplainMatchResultTo() function
1153 // is called only when the mock function call does NOT match the
1155 *os
<< "The call matches the expectation.\n";
1159 // Returns the action that should be taken for the current invocation.
1160 const Action
<F
>& GetCurrentAction(const FunctionMocker
<F
>* mocker
,
1161 const ArgumentTuple
& args
) const
1162 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1163 g_gmock_mutex
.AssertHeld();
1164 const int count
= call_count();
1165 Assert(count
>= 1, __FILE__
, __LINE__
,
1166 "call_count() is <= 0 when GetCurrentAction() is "
1167 "called - this should never happen.");
1169 const int action_count
= static_cast<int>(untyped_actions_
.size());
1170 if (action_count
> 0 && !repeated_action_specified_
&&
1171 count
> action_count
) {
1172 // If there is at least one WillOnce() and no WillRepeatedly(),
1173 // we warn the user when the WillOnce() clauses ran out.
1174 ::std::stringstream ss
;
1175 DescribeLocationTo(&ss
);
1176 ss
<< "Actions ran out in " << source_text() << "...\n"
1177 << "Called " << count
<< " times, but only "
1178 << action_count
<< " WillOnce()"
1179 << (action_count
== 1 ? " is" : "s are") << " specified - ";
1180 mocker
->DescribeDefaultActionTo(args
, &ss
);
1181 Log(kWarning
, ss
.str(), 1);
1184 return count
<= action_count
1185 ? *static_cast<const Action
<F
>*>(
1186 untyped_actions_
[static_cast<size_t>(count
- 1)])
1187 : repeated_action();
1190 // Given the arguments of a mock function call, if the call will
1191 // over-saturate this expectation, returns the default action;
1192 // otherwise, returns the next action in this expectation. Also
1193 // describes *what* happened to 'what', and explains *why* Google
1194 // Mock does it to 'why'. This method is not const as it calls
1195 // IncrementCallCount(). A return value of NULL means the default
1197 const Action
<F
>* GetActionForArguments(const FunctionMocker
<F
>* mocker
,
1198 const ArgumentTuple
& args
,
1199 ::std::ostream
* what
,
1200 ::std::ostream
* why
)
1201 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1202 g_gmock_mutex
.AssertHeld();
1203 if (IsSaturated()) {
1204 // We have an excessive call.
1205 IncrementCallCount();
1206 *what
<< "Mock function called more times than expected - ";
1207 mocker
->DescribeDefaultActionTo(args
, what
);
1208 DescribeCallCountTo(why
);
1213 IncrementCallCount();
1214 RetireAllPreRequisites();
1216 if (retires_on_saturation_
&& IsSaturated()) {
1220 // Must be done after IncrementCount()!
1221 *what
<< "Mock function call matches " << source_text() <<"...\n";
1222 return &(GetCurrentAction(mocker
, args
));
1225 // All the fields below won't change once the EXPECT_CALL()
1226 // statement finishes.
1227 FunctionMocker
<F
>* const owner_
;
1228 ArgumentMatcherTuple matchers_
;
1229 Matcher
<const ArgumentTuple
&> extra_matcher_
;
1230 Action
<F
> repeated_action_
;
1232 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation
);
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
;
1254 typedef typename
internal::Function
<F
>::ArgumentMatcherTuple
1255 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(
1266 const char* file
, int line
, const char* obj
, const char* call
) {
1267 LogWithLocation(internal::kInfo
, file
, line
,
1268 std::string("ON_CALL(") + obj
+ ", " + call
+ ") invoked");
1269 return function_mocker_
->AddNewOnCallSpec(file
, line
, matchers_
);
1272 // Adds a new expectation spec to the function mocker and returns
1273 // the newly created spec.
1274 internal::TypedExpectation
<F
>& InternalExpectedAt(
1275 const char* file
, int line
, const char* obj
, const char* call
) {
1276 const std::string
source_text(std::string("EXPECT_CALL(") + obj
+ ", " +
1278 LogWithLocation(internal::kInfo
, file
, line
, source_text
+ " invoked");
1279 return function_mocker_
->AddNewExpectation(
1280 file
, line
, source_text
, matchers_
);
1283 // This operator overload is used to swallow the superfluous parameter list
1284 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1286 MockSpec
<F
>& operator()(const internal::WithoutMatchers
&, void* const) {
1291 template <typename Function
>
1292 friend class internal::FunctionMocker
;
1294 // The function mocker that owns this spec.
1295 internal::FunctionMocker
<F
>* const function_mocker_
;
1296 // The argument matchers specified in the spec.
1297 ArgumentMatcherTuple matchers_
;
1299 GTEST_DISALLOW_ASSIGN_(MockSpec
);
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 // C++ treats the void type specially. For example, you cannot define
1354 // a void-typed variable or pass a void value to a function.
1355 // ActionResultHolder<T> holds a value of type T, where T must be a
1356 // copyable type or void (T doesn't need to be default-constructable).
1357 // It hides the syntactic difference between void and other types, and
1358 // is used to unify the code for invoking both void-returning and
1359 // non-void-returning mock functions.
1361 // Untyped base class for ActionResultHolder<T>.
1362 class UntypedActionResultHolderBase
{
1364 virtual ~UntypedActionResultHolderBase() {}
1366 // Prints the held value as an action's result to os.
1367 virtual void PrintAsActionResult(::std::ostream
* os
) const = 0;
1370 // This generic definition is used when T is not void.
1371 template <typename T
>
1372 class ActionResultHolder
: public UntypedActionResultHolderBase
{
1374 // Returns the held value. Must not be called more than once.
1376 return result_
.Unwrap();
1379 // Prints the held value as an action's result to os.
1380 void PrintAsActionResult(::std::ostream
* os
) const override
{
1381 *os
<< "\n Returns: ";
1382 // T may be a reference type, so we don't use UniversalPrint().
1383 UniversalPrinter
<T
>::Print(result_
.Peek(), os
);
1386 // Performs the given mock function's default action and returns the
1387 // result in a new-ed ActionResultHolder.
1388 template <typename F
>
1389 static ActionResultHolder
* PerformDefaultAction(
1390 const FunctionMocker
<F
>* func_mocker
,
1391 typename Function
<F
>::ArgumentTuple
&& args
,
1392 const std::string
& call_description
) {
1393 return new ActionResultHolder(Wrapper(func_mocker
->PerformDefaultAction(
1394 std::move(args
), call_description
)));
1397 // Performs the given action and returns the result in a new-ed
1398 // ActionResultHolder.
1399 template <typename F
>
1400 static ActionResultHolder
* PerformAction(
1401 const Action
<F
>& action
, typename Function
<F
>::ArgumentTuple
&& args
) {
1402 return new ActionResultHolder(
1403 Wrapper(action
.Perform(std::move(args
))));
1407 typedef ReferenceOrValueWrapper
<T
> Wrapper
;
1409 explicit ActionResultHolder(Wrapper result
)
1410 : result_(std::move(result
)) {
1415 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder
);
1418 // Specialization for T = void.
1420 class ActionResultHolder
<void> : public UntypedActionResultHolderBase
{
1424 void PrintAsActionResult(::std::ostream
* /* os */) const override
{}
1426 // Performs the given mock function's default action and returns ownership
1427 // of an empty ActionResultHolder*.
1428 template <typename F
>
1429 static ActionResultHolder
* PerformDefaultAction(
1430 const FunctionMocker
<F
>* func_mocker
,
1431 typename Function
<F
>::ArgumentTuple
&& args
,
1432 const std::string
& call_description
) {
1433 func_mocker
->PerformDefaultAction(std::move(args
), call_description
);
1434 return new ActionResultHolder
;
1437 // Performs the given action and returns ownership of an empty
1438 // ActionResultHolder*.
1439 template <typename F
>
1440 static ActionResultHolder
* PerformAction(
1441 const Action
<F
>& action
, typename Function
<F
>::ArgumentTuple
&& args
) {
1442 action
.Perform(std::move(args
));
1443 return new ActionResultHolder
;
1447 ActionResultHolder() {}
1448 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder
);
1451 template <typename F
>
1452 class FunctionMocker
;
1454 template <typename R
, typename
... Args
>
1455 class FunctionMocker
<R(Args
...)> final
: public UntypedFunctionMockerBase
{
1456 using F
= R(Args
...);
1460 using ArgumentTuple
= std::tuple
<Args
...>;
1461 using ArgumentMatcherTuple
= std::tuple
<Matcher
<Args
>...>;
1465 // There is no generally useful and implementable semantics of
1466 // copying a mock object, so copying a mock is usually a user error.
1467 // Thus we disallow copying function mockers. If the user really
1468 // wants to copy a mock object, they should implement their own copy
1469 // operation, for example:
1471 // class MockFoo : public Foo {
1473 // // Defines a copy constructor explicitly.
1474 // MockFoo(const MockFoo& src) {}
1477 FunctionMocker(const FunctionMocker
&) = delete;
1478 FunctionMocker
& operator=(const FunctionMocker
&) = delete;
1480 // The destructor verifies that all expectations on this mock
1481 // function have been satisfied. If not, it will report Google Test
1482 // non-fatal failures for the violations.
1483 ~FunctionMocker() override
GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1484 MutexLock
l(&g_gmock_mutex
);
1485 VerifyAndClearExpectationsLocked();
1486 Mock::UnregisterLocked(this);
1487 ClearDefaultActionsLocked();
1490 // Returns the ON_CALL spec that matches this mock function with the
1491 // given arguments; returns NULL if no matching ON_CALL is found.
1493 const OnCallSpec
<F
>* FindOnCallSpec(
1494 const ArgumentTuple
& args
) const {
1495 for (UntypedOnCallSpecs::const_reverse_iterator it
1496 = untyped_on_call_specs_
.rbegin();
1497 it
!= untyped_on_call_specs_
.rend(); ++it
) {
1498 const OnCallSpec
<F
>* spec
= static_cast<const OnCallSpec
<F
>*>(*it
);
1499 if (spec
->Matches(args
))
1506 // Performs the default action of this mock function on the given
1507 // arguments and returns the result. Asserts (or throws if
1508 // exceptions are enabled) with a helpful call descrption if there
1509 // is no valid return value. This method doesn't depend on the
1510 // mutable state of this object, and thus can be called concurrently
1513 Result
PerformDefaultAction(ArgumentTuple
&& args
,
1514 const std::string
& call_description
) const {
1515 const OnCallSpec
<F
>* const spec
=
1516 this->FindOnCallSpec(args
);
1517 if (spec
!= nullptr) {
1518 return spec
->GetAction().Perform(std::move(args
));
1520 const std::string message
=
1522 "\n The mock function has no default action "
1523 "set, and its return type has no default value set.";
1524 #if GTEST_HAS_EXCEPTIONS
1525 if (!DefaultValue
<Result
>::Exists()) {
1526 throw std::runtime_error(message
);
1529 Assert(DefaultValue
<Result
>::Exists(), "", -1, message
);
1531 return DefaultValue
<Result
>::Get();
1534 // Performs the default action with the given arguments and returns
1535 // the action's result. The call description string will be used in
1536 // the error message to describe the call in the case the default
1537 // action fails. The caller is responsible for deleting the result.
1539 UntypedActionResultHolderBase
* UntypedPerformDefaultAction(
1540 void* untyped_args
, // must point to an ArgumentTuple
1541 const std::string
& call_description
) const override
{
1542 ArgumentTuple
* args
= static_cast<ArgumentTuple
*>(untyped_args
);
1543 return ResultHolder::PerformDefaultAction(this, std::move(*args
),
1547 // Performs the given action with the given arguments and returns
1548 // the action's result. The caller is responsible for deleting the
1551 UntypedActionResultHolderBase
* UntypedPerformAction(
1552 const void* untyped_action
, void* untyped_args
) const override
{
1553 // Make a copy of the action before performing it, in case the
1554 // action deletes the mock object (and thus deletes itself).
1555 const Action
<F
> action
= *static_cast<const Action
<F
>*>(untyped_action
);
1556 ArgumentTuple
* args
= static_cast<ArgumentTuple
*>(untyped_args
);
1557 return ResultHolder::PerformAction(action
, std::move(*args
));
1560 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1561 // clears the ON_CALL()s set on this mock function.
1562 void ClearDefaultActionsLocked() override
1563 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1564 g_gmock_mutex
.AssertHeld();
1566 // Deleting our default actions may trigger other mock objects to be
1567 // deleted, for example if an action contains a reference counted smart
1568 // pointer to that mock object, and that is the last reference. So if we
1569 // delete our actions within the context of the global mutex we may deadlock
1570 // when this method is called again. Instead, make a copy of the set of
1571 // actions to delete, clear our set within the mutex, and then delete the
1572 // actions outside of the mutex.
1573 UntypedOnCallSpecs specs_to_delete
;
1574 untyped_on_call_specs_
.swap(specs_to_delete
);
1576 g_gmock_mutex
.Unlock();
1577 for (UntypedOnCallSpecs::const_iterator it
=
1578 specs_to_delete
.begin();
1579 it
!= specs_to_delete
.end(); ++it
) {
1580 delete static_cast<const OnCallSpec
<F
>*>(*it
);
1583 // Lock the mutex again, since the caller expects it to be locked when we
1585 g_gmock_mutex
.Lock();
1588 // Returns the result of invoking this mock function with the given
1589 // arguments. This function can be safely called from multiple
1590 // threads concurrently.
1591 Result
Invoke(Args
... args
) GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1592 ArgumentTuple
tuple(std::forward
<Args
>(args
)...);
1593 std::unique_ptr
<ResultHolder
> holder(DownCast_
<ResultHolder
*>(
1594 this->UntypedInvokeWith(static_cast<void*>(&tuple
))));
1595 return holder
->Unwrap();
1598 MockSpec
<F
> With(Matcher
<Args
>... m
) {
1599 return MockSpec
<F
>(this, ::std::make_tuple(std::move(m
)...));
1603 template <typename Function
>
1604 friend class MockSpec
;
1606 typedef ActionResultHolder
<Result
> ResultHolder
;
1608 // Adds and returns a default action spec for this mock function.
1609 OnCallSpec
<F
>& AddNewOnCallSpec(
1610 const char* file
, int line
,
1611 const ArgumentMatcherTuple
& m
)
1612 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1613 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file
, line
);
1614 OnCallSpec
<F
>* const on_call_spec
= new OnCallSpec
<F
>(file
, line
, m
);
1615 untyped_on_call_specs_
.push_back(on_call_spec
);
1616 return *on_call_spec
;
1619 // Adds and returns an expectation spec for this mock function.
1620 TypedExpectation
<F
>& AddNewExpectation(const char* file
, int line
,
1621 const std::string
& source_text
,
1622 const ArgumentMatcherTuple
& m
)
1623 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1624 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file
, line
);
1625 TypedExpectation
<F
>* const expectation
=
1626 new TypedExpectation
<F
>(this, file
, line
, source_text
, m
);
1627 const std::shared_ptr
<ExpectationBase
> untyped_expectation(expectation
);
1628 // See the definition of untyped_expectations_ for why access to
1629 // it is unprotected here.
1630 untyped_expectations_
.push_back(untyped_expectation
);
1632 // Adds this expectation into the implicit sequence if there is one.
1633 Sequence
* const implicit_sequence
= g_gmock_implicit_sequence
.get();
1634 if (implicit_sequence
!= nullptr) {
1635 implicit_sequence
->AddExpectation(Expectation(untyped_expectation
));
1638 return *expectation
;
1642 template <typename Func
> friend class TypedExpectation
;
1644 // Some utilities needed for implementing UntypedInvokeWith().
1646 // Describes what default action will be performed for the given
1649 void DescribeDefaultActionTo(const ArgumentTuple
& args
,
1650 ::std::ostream
* os
) const {
1651 const OnCallSpec
<F
>* const spec
= FindOnCallSpec(args
);
1653 if (spec
== nullptr) {
1654 *os
<< (std::is_void
<Result
>::value
? "returning directly.\n"
1655 : "returning default value.\n");
1657 *os
<< "taking default action specified at:\n"
1658 << FormatFileLocation(spec
->file(), spec
->line()) << "\n";
1662 // Writes a message that the call is uninteresting (i.e. neither
1663 // explicitly expected nor explicitly unexpected) to the given
1665 void UntypedDescribeUninterestingCall(const void* untyped_args
,
1666 ::std::ostream
* os
) const override
1667 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1668 const ArgumentTuple
& args
=
1669 *static_cast<const ArgumentTuple
*>(untyped_args
);
1670 *os
<< "Uninteresting mock function call - ";
1671 DescribeDefaultActionTo(args
, os
);
1672 *os
<< " Function call: " << Name();
1673 UniversalPrint(args
, os
);
1676 // Returns the expectation that matches the given function arguments
1677 // (or NULL is there's no match); when a match is found,
1678 // untyped_action is set to point to the action that should be
1679 // performed (or NULL if the action is "do default"), and
1680 // is_excessive is modified to indicate whether the call exceeds the
1683 // Critical section: We must find the matching expectation and the
1684 // corresponding action that needs to be taken in an ATOMIC
1685 // transaction. Otherwise another thread may call this mock
1686 // method in the middle and mess up the state.
1688 // However, performing the action has to be left out of the critical
1689 // section. The reason is that we have no control on what the
1690 // action does (it can invoke an arbitrary user function or even a
1691 // mock function) and excessive locking could cause a dead lock.
1692 const ExpectationBase
* UntypedFindMatchingExpectation(
1693 const void* untyped_args
, const void** untyped_action
, bool* is_excessive
,
1694 ::std::ostream
* what
, ::std::ostream
* why
) override
1695 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1696 const ArgumentTuple
& args
=
1697 *static_cast<const ArgumentTuple
*>(untyped_args
);
1698 MutexLock
l(&g_gmock_mutex
);
1699 TypedExpectation
<F
>* exp
= this->FindMatchingExpectationLocked(args
);
1700 if (exp
== nullptr) { // A match wasn't found.
1701 this->FormatUnexpectedCallMessageLocked(args
, what
, why
);
1705 // This line must be done before calling GetActionForArguments(),
1706 // which will increment the call count for *exp and thus affect
1707 // its saturation status.
1708 *is_excessive
= exp
->IsSaturated();
1709 const Action
<F
>* action
= exp
->GetActionForArguments(this, args
, what
, why
);
1710 if (action
!= nullptr && action
->IsDoDefault())
1711 action
= nullptr; // Normalize "do default" to NULL.
1712 *untyped_action
= action
;
1716 // Prints the given function arguments to the ostream.
1717 void UntypedPrintArgs(const void* untyped_args
,
1718 ::std::ostream
* os
) const override
{
1719 const ArgumentTuple
& args
=
1720 *static_cast<const ArgumentTuple
*>(untyped_args
);
1721 UniversalPrint(args
, os
);
1724 // Returns the expectation that matches the arguments, or NULL if no
1725 // expectation matches them.
1726 TypedExpectation
<F
>* FindMatchingExpectationLocked(
1727 const ArgumentTuple
& args
) const
1728 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1729 g_gmock_mutex
.AssertHeld();
1730 // See the definition of untyped_expectations_ for why access to
1731 // it is unprotected here.
1732 for (typename
UntypedExpectations::const_reverse_iterator it
=
1733 untyped_expectations_
.rbegin();
1734 it
!= untyped_expectations_
.rend(); ++it
) {
1735 TypedExpectation
<F
>* const exp
=
1736 static_cast<TypedExpectation
<F
>*>(it
->get());
1737 if (exp
->ShouldHandleArguments(args
)) {
1744 // Returns a message that the arguments don't match any expectation.
1745 void FormatUnexpectedCallMessageLocked(
1746 const ArgumentTuple
& args
,
1748 ::std::ostream
* why
) const
1749 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1750 g_gmock_mutex
.AssertHeld();
1751 *os
<< "\nUnexpected mock function call - ";
1752 DescribeDefaultActionTo(args
, os
);
1753 PrintTriedExpectationsLocked(args
, why
);
1756 // Prints a list of expectations that have been tried against the
1757 // current mock function call.
1758 void PrintTriedExpectationsLocked(
1759 const ArgumentTuple
& args
,
1760 ::std::ostream
* why
) const
1761 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1762 g_gmock_mutex
.AssertHeld();
1763 const size_t count
= untyped_expectations_
.size();
1764 *why
<< "Google Mock tried the following " << count
<< " "
1765 << (count
== 1 ? "expectation, but it didn't match" :
1766 "expectations, but none matched")
1768 for (size_t i
= 0; i
< count
; i
++) {
1769 TypedExpectation
<F
>* const expectation
=
1770 static_cast<TypedExpectation
<F
>*>(untyped_expectations_
[i
].get());
1772 expectation
->DescribeLocationTo(why
);
1774 *why
<< "tried expectation #" << i
<< ": ";
1776 *why
<< expectation
->source_text() << "...\n";
1777 expectation
->ExplainMatchResultTo(args
, why
);
1778 expectation
->DescribeCallCountTo(why
);
1781 }; // class FunctionMocker
1783 // Reports an uninteresting call (whose description is in msg) in the
1784 // manner specified by 'reaction'.
1785 void ReportUninterestingCall(CallReaction reaction
, const std::string
& msg
);
1787 } // namespace internal
1789 // A MockFunction<F> class has one mock method whose type is F. It is
1790 // useful when you just want your test code to emit some messages and
1791 // have Google Mock verify the right messages are sent (and perhaps at
1792 // the right times). For example, if you are exercising code:
1798 // and want to verify that Foo(1) and Foo(3) both invoke
1799 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1801 // TEST(FooTest, InvokesBarCorrectly) {
1803 // MockFunction<void(string check_point_name)> check;
1807 // EXPECT_CALL(mock, Bar("a"));
1808 // EXPECT_CALL(check, Call("1"));
1809 // EXPECT_CALL(check, Call("2"));
1810 // EXPECT_CALL(mock, Bar("a"));
1819 // The expectation spec says that the first Bar("a") must happen
1820 // before check point "1", the second Bar("a") must happen after check
1821 // point "2", and nothing should happen between the two check
1822 // points. The explicit check points make it easy to tell which
1823 // Bar("a") is called by which call to Foo().
1825 // MockFunction<F> can also be used to exercise code that accepts
1826 // std::function<F> callbacks. To do so, use AsStdFunction() method
1827 // to create std::function proxy forwarding to original object's Call.
1830 // TEST(FooTest, RunsCallbackWithBarArgument) {
1831 // MockFunction<int(string)> callback;
1832 // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1833 // Foo(callback.AsStdFunction());
1835 template <typename F
>
1838 template <typename R
, typename
... Args
>
1839 class MockFunction
<R(Args
...)> {
1842 MockFunction(const MockFunction
&) = delete;
1843 MockFunction
& operator=(const MockFunction
&) = delete;
1845 std::function
<R(Args
...)> AsStdFunction() {
1846 return [this](Args
... args
) -> R
{
1847 return this->Call(std::forward
<Args
>(args
)...);
1851 // Implementation detail: the expansion of the MOCK_METHOD macro.
1852 R
Call(Args
... args
) {
1853 mock_
.SetOwnerAndName(this, "Call");
1854 return mock_
.Invoke(std::forward
<Args
>(args
)...);
1857 internal::MockSpec
<R(Args
...)> gmock_Call(Matcher
<Args
>... m
) {
1858 mock_
.RegisterOwner(this);
1859 return mock_
.With(std::move(m
)...);
1862 internal::MockSpec
<R(Args
...)> gmock_Call(const internal::WithoutMatchers
&,
1864 return this->gmock_Call(::testing::A
<Args
>()...);
1868 internal::FunctionMocker
<R(Args
...)> mock_
;
1871 // The style guide prohibits "using" statements in a namespace scope
1872 // inside a header file. However, the MockSpec class template is
1873 // meant to be defined in the ::testing namespace. The following line
1874 // is just a trick for working around a bug in MSVC 8.0, which cannot
1875 // handle it if we define MockSpec in ::testing.
1876 using internal::MockSpec
;
1878 // Const(x) is a convenient function for obtaining a const reference
1879 // to x. This is useful for setting expectations on an overloaded
1880 // const mock method, e.g.
1882 // class MockFoo : public FooInterface {
1884 // MOCK_METHOD0(Bar, int());
1885 // MOCK_CONST_METHOD0(Bar, int&());
1889 // // Expects a call to non-const MockFoo::Bar().
1890 // EXPECT_CALL(foo, Bar());
1891 // // Expects a call to const MockFoo::Bar().
1892 // EXPECT_CALL(Const(foo), Bar());
1893 template <typename T
>
1894 inline const T
& Const(const T
& x
) { return x
; }
1896 // Constructs an Expectation object that references and co-owns exp.
1897 inline Expectation::Expectation(internal::ExpectationBase
& exp
) // NOLINT
1898 : expectation_base_(exp
.GetHandle().expectation_base()) {}
1900 } // namespace testing
1902 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1904 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1905 // required to avoid compile errors when the name of the method used in call is
1906 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1907 // tests in internal/gmock-spec-builders_test.cc for more details.
1909 // This macro supports statements both with and without parameter matchers. If
1910 // the parameter list is omitted, gMock will accept any parameters, which allows
1911 // tests to be written that don't need to encode the number of method
1912 // parameter. This technique may only be used for non-overloaded methods.
1914 // // These are the same:
1915 // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1916 // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
1919 // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1920 // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
1922 // // Can also specify args if you want, of course:
1923 // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
1925 // // Overloads work as long as you specify parameters:
1926 // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1927 // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
1929 // // Oops! Which overload did you want?
1930 // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
1931 // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1933 // How this works: The mock class uses two overloads of the gmock_Method
1934 // expectation setter method plus an operator() overload on the MockSpec object.
1935 // In the matcher list form, the macro expands to:
1937 // // This statement:
1938 // ON_CALL(mock, TwoArgsMethod(_, 45))...
1940 // // ...expands to:
1941 // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
1942 // |-------------v---------------||------------v-------------|
1943 // invokes first overload swallowed by operator()
1945 // // ...which is essentially:
1946 // mock.gmock_TwoArgsMethod(_, 45)...
1948 // Whereas the form without a matcher list:
1950 // // This statement:
1951 // ON_CALL(mock, TwoArgsMethod)...
1953 // // ...expands to:
1954 // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
1955 // |-----------------------v--------------------------|
1956 // invokes second overload
1958 // // ...which is essentially:
1959 // mock.gmock_TwoArgsMethod(_, _)...
1961 // The WithoutMatchers() argument is used to disambiguate overloads and to
1962 // block the caller from accidentally invoking the second overload directly. The
1963 // second argument is an internal type derived from the method signature. The
1964 // failure to disambiguate two overloads of this method in the ON_CALL statement
1965 // is how we block callers from setting expectations on overloaded methods.
1966 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1967 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
1969 .Setter(__FILE__, __LINE__, #mock_expr, #call)
1971 #define ON_CALL(obj, call) \
1972 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1974 #define EXPECT_CALL(obj, call) \
1975 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
1977 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_