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 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 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 rhs references the same expectation as this object does.
520 bool operator==(const Expectation
& rhs
) const {
521 return expectation_base_
== rhs
.expectation_base_
;
524 bool operator!=(const Expectation
& rhs
) const { return !(*this == rhs
); }
527 friend class ExpectationSet
;
528 friend class Sequence
;
529 friend class ::testing::internal::ExpectationBase
;
530 friend class ::testing::internal::UntypedFunctionMockerBase
;
532 template <typename F
>
533 friend class ::testing::internal::FunctionMocker
;
535 template <typename F
>
536 friend class ::testing::internal::TypedExpectation
;
538 // This comparator is needed for putting Expectation objects into a set.
541 bool operator()(const Expectation
& lhs
, const Expectation
& rhs
) const {
542 return lhs
.expectation_base_
.get() < rhs
.expectation_base_
.get();
546 typedef ::std::set
<Expectation
, Less
> Set
;
549 const std::shared_ptr
<internal::ExpectationBase
>& expectation_base
);
551 // Returns the expectation this object references.
552 const std::shared_ptr
<internal::ExpectationBase
>& expectation_base() const {
553 return expectation_base_
;
556 // A shared_ptr that co-owns the expectation this handle references.
557 std::shared_ptr
<internal::ExpectationBase
> expectation_base_
;
560 // A set of expectation handles. Useful in the .After() clause of
561 // EXPECT_CALL() for setting the (partial) order of expectations. The
564 // ExpectationSet es;
565 // es += EXPECT_CALL(...)...;
566 // es += EXPECT_CALL(...)...;
567 // EXPECT_CALL(...).After(es)...;
569 // sets three expectations where the last one can only be matched
570 // after the first two have both been satisfied.
572 // This class is copyable and has value semantics.
573 class ExpectationSet
{
575 // A bidirectional iterator that can read a const element in the set.
576 typedef Expectation::Set::const_iterator const_iterator
;
578 // An object stored in the set. This is an alias of Expectation.
579 typedef Expectation::Set::value_type value_type
;
581 // Constructs an empty set.
584 // This single-argument ctor must not be explicit, in order to support the
585 // ExpectationSet es = EXPECT_CALL(...);
587 ExpectationSet(internal::ExpectationBase
& exp
) { // NOLINT
588 *this += Expectation(exp
);
591 // This single-argument ctor implements implicit conversion from
592 // Expectation and thus must not be explicit. This allows either an
593 // Expectation or an ExpectationSet to be used in .After().
594 ExpectationSet(const Expectation
& e
) { // NOLINT
598 // The compiler-generator ctor and operator= works exactly as
599 // intended, so we don't need to define our own.
601 // Returns true if rhs contains the same set of Expectation objects
603 bool operator==(const ExpectationSet
& rhs
) const {
604 return expectations_
== rhs
.expectations_
;
607 bool operator!=(const ExpectationSet
& rhs
) const { return !(*this == rhs
); }
609 // Implements the syntax
610 // expectation_set += EXPECT_CALL(...);
611 ExpectationSet
& operator+=(const Expectation
& e
) {
612 expectations_
.insert(e
);
616 int size() const { return static_cast<int>(expectations_
.size()); }
618 const_iterator
begin() const { return expectations_
.begin(); }
619 const_iterator
end() const { return expectations_
.end(); }
622 Expectation::Set expectations_
;
626 // Sequence objects are used by a user to specify the relative order
627 // in which the expectations should match. They are copyable (we rely
628 // on the compiler-defined copy constructor and assignment operator).
629 class GTEST_API_ Sequence
{
631 // Constructs an empty sequence.
632 Sequence() : last_expectation_(new Expectation
) {}
634 // Adds an expectation to this sequence. The caller must ensure
635 // that no other thread is accessing this Sequence object.
636 void AddExpectation(const Expectation
& expectation
) const;
639 // The last expectation in this sequence.
640 std::shared_ptr
<Expectation
> last_expectation_
;
643 // An object of this type causes all EXPECT_CALL() statements
644 // encountered in its scope to be put in an anonymous sequence. The
645 // work is done in the constructor and destructor. You should only
646 // create an InSequence object on the stack.
648 // The sole purpose for this class is to support easy definition of
649 // sequential expectations, e.g.
652 // InSequence dummy; // The name of the object doesn't matter.
654 // // The following expectations must match in the order they appear.
655 // EXPECT_CALL(a, Bar())...;
656 // EXPECT_CALL(a, Baz())...;
658 // EXPECT_CALL(b, Xyz())...;
661 // You can create InSequence objects in multiple threads, as long as
662 // they are used to affect different mock objects. The idea is that
663 // each thread can create and set up its own mocks as if it's the only
664 // thread. However, for clarity of your tests we recommend you to set
665 // up mocks in the main thread unless you have a good reason not to do
667 class GTEST_API_ InSequence
{
672 bool sequence_created_
;
674 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence
); // NOLINT
675 } GTEST_ATTRIBUTE_UNUSED_
;
679 // Points to the implicit sequence introduced by a living InSequence
680 // object (if any) in the current thread or NULL.
681 GTEST_API_
extern ThreadLocal
<Sequence
*> g_gmock_implicit_sequence
;
683 // Base class for implementing expectations.
685 // There are two reasons for having a type-agnostic base class for
688 // 1. We need to store collections of expectations of different
689 // types (e.g. all pre-requisites of a particular expectation, all
690 // expectations in a sequence). Therefore these expectation objects
691 // must share a common base class.
693 // 2. We can avoid binary code bloat by moving methods not depending
694 // on the template argument of Expectation to the base class.
696 // This class is internal and mustn't be used by user code directly.
697 class GTEST_API_ ExpectationBase
{
699 // source_text is the EXPECT_CALL(...) source that created this Expectation.
700 ExpectationBase(const char* file
, int line
, const std::string
& source_text
);
702 virtual ~ExpectationBase();
704 // Where in the source file was the expectation spec defined?
705 const char* file() const { return file_
; }
706 int line() const { return line_
; }
707 const char* source_text() const { return source_text_
.c_str(); }
708 // Returns the cardinality specified in the expectation spec.
709 const Cardinality
& cardinality() const { return cardinality_
; }
711 // Describes the source file location of this expectation.
712 void DescribeLocationTo(::std::ostream
* os
) const {
713 *os
<< FormatFileLocation(file(), line()) << " ";
716 // Describes how many times a function call matching this
717 // expectation has occurred.
718 void DescribeCallCountTo(::std::ostream
* os
) const
719 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
721 // If this mock method has an extra matcher (i.e. .With(matcher)),
722 // describes it to the ostream.
723 virtual void MaybeDescribeExtraMatcherTo(::std::ostream
* os
) = 0;
726 friend class ::testing::Expectation
;
727 friend class UntypedFunctionMockerBase
;
730 // Don't change the order of the enum members!
741 typedef std::vector
<const void*> UntypedActions
;
743 // Returns an Expectation object that references and co-owns this
745 virtual Expectation
GetHandle() = 0;
747 // Asserts that the EXPECT_CALL() statement has the given property.
748 void AssertSpecProperty(bool property
,
749 const std::string
& failure_message
) const {
750 Assert(property
, file_
, line_
, failure_message
);
753 // Expects that the EXPECT_CALL() statement has the given property.
754 void ExpectSpecProperty(bool property
,
755 const std::string
& failure_message
) const {
756 Expect(property
, file_
, line_
, failure_message
);
759 // Explicitly specifies the cardinality of this expectation. Used
760 // by the subclasses to implement the .Times() clause.
761 void SpecifyCardinality(const Cardinality
& cardinality
);
763 // Returns true if the user specified the cardinality explicitly
765 bool cardinality_specified() const { return cardinality_specified_
; }
767 // Sets the cardinality of this expectation spec.
768 void set_cardinality(const Cardinality
& a_cardinality
) {
769 cardinality_
= a_cardinality
;
772 // The following group of methods should only be called after the
773 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
774 // the current thread.
776 // Retires all pre-requisites of this expectation.
777 void RetireAllPreRequisites()
778 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
780 // Returns true if this expectation is retired.
781 bool is_retired() const
782 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
783 g_gmock_mutex
.AssertHeld();
787 // Retires this expectation.
789 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
790 g_gmock_mutex
.AssertHeld();
794 // Returns true if this expectation is satisfied.
795 bool IsSatisfied() const
796 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
797 g_gmock_mutex
.AssertHeld();
798 return cardinality().IsSatisfiedByCallCount(call_count_
);
801 // Returns true if this expectation is saturated.
802 bool IsSaturated() const
803 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
804 g_gmock_mutex
.AssertHeld();
805 return cardinality().IsSaturatedByCallCount(call_count_
);
808 // Returns true if this expectation is over-saturated.
809 bool IsOverSaturated() const
810 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
811 g_gmock_mutex
.AssertHeld();
812 return cardinality().IsOverSaturatedByCallCount(call_count_
);
815 // Returns true if all pre-requisites of this expectation are satisfied.
816 bool AllPrerequisitesAreSatisfied() const
817 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
819 // Adds unsatisfied pre-requisites of this expectation to 'result'.
820 void FindUnsatisfiedPrerequisites(ExpectationSet
* result
) const
821 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
);
823 // Returns the number this expectation has been invoked.
824 int call_count() const
825 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
826 g_gmock_mutex
.AssertHeld();
830 // Increments the number this expectation has been invoked.
831 void IncrementCallCount()
832 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
833 g_gmock_mutex
.AssertHeld();
837 // Checks the action count (i.e. the number of WillOnce() and
838 // WillRepeatedly() clauses) against the cardinality if this hasn't
839 // been done before. Prints a warning if there are too many or too
841 void CheckActionCountIfNotDone() const
842 GTEST_LOCK_EXCLUDED_(mutex_
);
844 friend class ::testing::Sequence
;
845 friend class ::testing::internal::ExpectationTester
;
847 template <typename Function
>
848 friend class TypedExpectation
;
850 // Implements the .Times() clause.
851 void UntypedTimes(const Cardinality
& a_cardinality
);
853 // This group of fields are part of the spec and won't change after
854 // an EXPECT_CALL() statement finishes.
855 const char* file_
; // The file that contains the expectation.
856 int line_
; // The line number of the expectation.
857 const std::string source_text_
; // The EXPECT_CALL(...) source text.
858 // True if the cardinality is specified explicitly.
859 bool cardinality_specified_
;
860 Cardinality cardinality_
; // The cardinality of the expectation.
861 // The immediate pre-requisites (i.e. expectations that must be
862 // satisfied before this expectation can be matched) of this
863 // expectation. We use std::shared_ptr in the set because we want an
864 // Expectation object to be co-owned by its FunctionMocker and its
865 // successors. This allows multiple mock objects to be deleted at
867 ExpectationSet immediate_prerequisites_
;
869 // This group of fields are the current state of the expectation,
870 // and can change as the mock function is called.
871 int call_count_
; // How many times this expectation has been invoked.
872 bool retired_
; // True if this expectation has retired.
873 UntypedActions untyped_actions_
;
874 bool extra_matcher_specified_
;
875 bool repeated_action_specified_
; // True if a WillRepeatedly() was specified.
876 bool retires_on_saturation_
;
878 mutable bool action_count_checked_
; // Under mutex_.
879 mutable Mutex mutex_
; // Protects action_count_checked_.
881 GTEST_DISALLOW_ASSIGN_(ExpectationBase
);
882 }; // class ExpectationBase
884 // Impements an expectation for the given function type.
885 template <typename F
>
886 class TypedExpectation
: public ExpectationBase
{
888 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
889 typedef typename Function
<F
>::ArgumentMatcherTuple ArgumentMatcherTuple
;
890 typedef typename Function
<F
>::Result Result
;
892 TypedExpectation(FunctionMocker
<F
>* owner
, const char* a_file
, int a_line
,
893 const std::string
& a_source_text
,
894 const ArgumentMatcherTuple
& m
)
895 : ExpectationBase(a_file
, a_line
, a_source_text
),
898 // By default, extra_matcher_ should match anything. However,
899 // we cannot initialize it with _ as that causes ambiguity between
900 // Matcher's copy and move constructor for some argument types.
901 extra_matcher_(A
<const ArgumentTuple
&>()),
902 repeated_action_(DoDefault()) {}
904 ~TypedExpectation() override
{
905 // Check the validity of the action count if it hasn't been done
906 // yet (for example, if the expectation was never used).
907 CheckActionCountIfNotDone();
908 for (UntypedActions::const_iterator it
= untyped_actions_
.begin();
909 it
!= untyped_actions_
.end(); ++it
) {
910 delete static_cast<const Action
<F
>*>(*it
);
914 // Implements the .With() clause.
915 TypedExpectation
& With(const Matcher
<const ArgumentTuple
&>& m
) {
916 if (last_clause_
== kWith
) {
917 ExpectSpecProperty(false,
918 ".With() cannot appear "
919 "more than once in an EXPECT_CALL().");
921 ExpectSpecProperty(last_clause_
< kWith
,
922 ".With() must be the first "
923 "clause in an EXPECT_CALL().");
925 last_clause_
= kWith
;
928 extra_matcher_specified_
= true;
932 // Implements the .Times() clause.
933 TypedExpectation
& Times(const Cardinality
& a_cardinality
) {
934 ExpectationBase::UntypedTimes(a_cardinality
);
938 // Implements the .Times() clause.
939 TypedExpectation
& Times(int n
) {
940 return Times(Exactly(n
));
943 // Implements the .InSequence() clause.
944 TypedExpectation
& InSequence(const Sequence
& s
) {
945 ExpectSpecProperty(last_clause_
<= kInSequence
,
946 ".InSequence() cannot appear after .After(),"
947 " .WillOnce(), .WillRepeatedly(), or "
948 ".RetiresOnSaturation().");
949 last_clause_
= kInSequence
;
951 s
.AddExpectation(GetHandle());
954 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
) {
955 return InSequence(s1
).InSequence(s2
);
957 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
958 const Sequence
& s3
) {
959 return InSequence(s1
, s2
).InSequence(s3
);
961 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
962 const Sequence
& s3
, const Sequence
& s4
) {
963 return InSequence(s1
, s2
, s3
).InSequence(s4
);
965 TypedExpectation
& InSequence(const Sequence
& s1
, const Sequence
& s2
,
966 const Sequence
& s3
, const Sequence
& s4
,
967 const Sequence
& s5
) {
968 return InSequence(s1
, s2
, s3
, s4
).InSequence(s5
);
971 // Implements that .After() clause.
972 TypedExpectation
& After(const ExpectationSet
& s
) {
973 ExpectSpecProperty(last_clause_
<= kAfter
,
974 ".After() cannot appear after .WillOnce(),"
975 " .WillRepeatedly(), or "
976 ".RetiresOnSaturation().");
977 last_clause_
= kAfter
;
979 for (ExpectationSet::const_iterator it
= s
.begin(); it
!= s
.end(); ++it
) {
980 immediate_prerequisites_
+= *it
;
984 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
) {
985 return After(s1
).After(s2
);
987 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
988 const ExpectationSet
& s3
) {
989 return After(s1
, s2
).After(s3
);
991 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
992 const ExpectationSet
& s3
, const ExpectationSet
& s4
) {
993 return After(s1
, s2
, s3
).After(s4
);
995 TypedExpectation
& After(const ExpectationSet
& s1
, const ExpectationSet
& s2
,
996 const ExpectationSet
& s3
, const ExpectationSet
& s4
,
997 const ExpectationSet
& s5
) {
998 return After(s1
, s2
, s3
, s4
).After(s5
);
1001 // Implements the .WillOnce() clause.
1002 TypedExpectation
& WillOnce(const Action
<F
>& action
) {
1003 ExpectSpecProperty(last_clause_
<= kWillOnce
,
1004 ".WillOnce() cannot appear after "
1005 ".WillRepeatedly() or .RetiresOnSaturation().");
1006 last_clause_
= kWillOnce
;
1008 untyped_actions_
.push_back(new Action
<F
>(action
));
1009 if (!cardinality_specified()) {
1010 set_cardinality(Exactly(static_cast<int>(untyped_actions_
.size())));
1015 // Implements the .WillRepeatedly() clause.
1016 TypedExpectation
& WillRepeatedly(const Action
<F
>& action
) {
1017 if (last_clause_
== kWillRepeatedly
) {
1018 ExpectSpecProperty(false,
1019 ".WillRepeatedly() cannot appear "
1020 "more than once in an EXPECT_CALL().");
1022 ExpectSpecProperty(last_clause_
< kWillRepeatedly
,
1023 ".WillRepeatedly() cannot appear "
1024 "after .RetiresOnSaturation().");
1026 last_clause_
= kWillRepeatedly
;
1027 repeated_action_specified_
= true;
1029 repeated_action_
= action
;
1030 if (!cardinality_specified()) {
1031 set_cardinality(AtLeast(static_cast<int>(untyped_actions_
.size())));
1034 // Now that no more action clauses can be specified, we check
1035 // whether their count makes sense.
1036 CheckActionCountIfNotDone();
1040 // Implements the .RetiresOnSaturation() clause.
1041 TypedExpectation
& RetiresOnSaturation() {
1042 ExpectSpecProperty(last_clause_
< kRetiresOnSaturation
,
1043 ".RetiresOnSaturation() cannot appear "
1045 last_clause_
= kRetiresOnSaturation
;
1046 retires_on_saturation_
= true;
1048 // Now that no more action clauses can be specified, we check
1049 // whether their count makes sense.
1050 CheckActionCountIfNotDone();
1054 // Returns the matchers for the arguments as specified inside the
1055 // EXPECT_CALL() macro.
1056 const ArgumentMatcherTuple
& matchers() const {
1060 // Returns the matcher specified by the .With() clause.
1061 const Matcher
<const ArgumentTuple
&>& extra_matcher() const {
1062 return extra_matcher_
;
1065 // Returns the action specified by the .WillRepeatedly() clause.
1066 const Action
<F
>& repeated_action() const { return repeated_action_
; }
1068 // If this mock method has an extra matcher (i.e. .With(matcher)),
1069 // describes it to the ostream.
1070 void MaybeDescribeExtraMatcherTo(::std::ostream
* os
) override
{
1071 if (extra_matcher_specified_
) {
1072 *os
<< " Expected args: ";
1073 extra_matcher_
.DescribeTo(os
);
1079 template <typename Function
>
1080 friend class FunctionMocker
;
1082 // Returns an Expectation object that references and co-owns this
1084 Expectation
GetHandle() override
{ return owner_
->GetHandleOf(this); }
1086 // The following methods will be called only after the EXPECT_CALL()
1087 // statement finishes and when the current thread holds
1090 // Returns true if this expectation matches the given arguments.
1091 bool Matches(const ArgumentTuple
& args
) const
1092 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1093 g_gmock_mutex
.AssertHeld();
1094 return TupleMatches(matchers_
, args
) && extra_matcher_
.Matches(args
);
1097 // Returns true if this expectation should handle the given arguments.
1098 bool ShouldHandleArguments(const ArgumentTuple
& args
) const
1099 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1100 g_gmock_mutex
.AssertHeld();
1102 // In case the action count wasn't checked when the expectation
1103 // was defined (e.g. if this expectation has no WillRepeatedly()
1104 // or RetiresOnSaturation() clause), we check it when the
1105 // expectation is used for the first time.
1106 CheckActionCountIfNotDone();
1107 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args
);
1110 // Describes the result of matching the arguments against this
1111 // expectation to the given ostream.
1112 void ExplainMatchResultTo(
1113 const ArgumentTuple
& args
,
1114 ::std::ostream
* os
) const
1115 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1116 g_gmock_mutex
.AssertHeld();
1119 *os
<< " Expected: the expectation is active\n"
1120 << " Actual: it is retired\n";
1121 } else if (!Matches(args
)) {
1122 if (!TupleMatches(matchers_
, args
)) {
1123 ExplainMatchFailureTupleTo(matchers_
, args
, os
);
1125 StringMatchResultListener listener
;
1126 if (!extra_matcher_
.MatchAndExplain(args
, &listener
)) {
1127 *os
<< " Expected args: ";
1128 extra_matcher_
.DescribeTo(os
);
1129 *os
<< "\n Actual: don't match";
1131 internal::PrintIfNotEmpty(listener
.str(), os
);
1134 } else if (!AllPrerequisitesAreSatisfied()) {
1135 *os
<< " Expected: all pre-requisites are satisfied\n"
1136 << " Actual: the following immediate pre-requisites "
1137 << "are not satisfied:\n";
1138 ExpectationSet unsatisfied_prereqs
;
1139 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs
);
1141 for (ExpectationSet::const_iterator it
= unsatisfied_prereqs
.begin();
1142 it
!= unsatisfied_prereqs
.end(); ++it
) {
1143 it
->expectation_base()->DescribeLocationTo(os
);
1144 *os
<< "pre-requisite #" << i
++ << "\n";
1146 *os
<< " (end of pre-requisites)\n";
1148 // This line is here just for completeness' sake. It will never
1149 // be executed as currently the ExplainMatchResultTo() function
1150 // is called only when the mock function call does NOT match the
1152 *os
<< "The call matches the expectation.\n";
1156 // Returns the action that should be taken for the current invocation.
1157 const Action
<F
>& GetCurrentAction(const FunctionMocker
<F
>* mocker
,
1158 const ArgumentTuple
& args
) const
1159 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1160 g_gmock_mutex
.AssertHeld();
1161 const int count
= call_count();
1162 Assert(count
>= 1, __FILE__
, __LINE__
,
1163 "call_count() is <= 0 when GetCurrentAction() is "
1164 "called - this should never happen.");
1166 const int action_count
= static_cast<int>(untyped_actions_
.size());
1167 if (action_count
> 0 && !repeated_action_specified_
&&
1168 count
> action_count
) {
1169 // If there is at least one WillOnce() and no WillRepeatedly(),
1170 // we warn the user when the WillOnce() clauses ran out.
1171 ::std::stringstream ss
;
1172 DescribeLocationTo(&ss
);
1173 ss
<< "Actions ran out in " << source_text() << "...\n"
1174 << "Called " << count
<< " times, but only "
1175 << action_count
<< " WillOnce()"
1176 << (action_count
== 1 ? " is" : "s are") << " specified - ";
1177 mocker
->DescribeDefaultActionTo(args
, &ss
);
1178 Log(kWarning
, ss
.str(), 1);
1181 return count
<= action_count
1182 ? *static_cast<const Action
<F
>*>(
1183 untyped_actions_
[static_cast<size_t>(count
- 1)])
1184 : repeated_action();
1187 // Given the arguments of a mock function call, if the call will
1188 // over-saturate this expectation, returns the default action;
1189 // otherwise, returns the next action in this expectation. Also
1190 // describes *what* happened to 'what', and explains *why* Google
1191 // Mock does it to 'why'. This method is not const as it calls
1192 // IncrementCallCount(). A return value of NULL means the default
1194 const Action
<F
>* GetActionForArguments(const FunctionMocker
<F
>* mocker
,
1195 const ArgumentTuple
& args
,
1196 ::std::ostream
* what
,
1197 ::std::ostream
* why
)
1198 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1199 g_gmock_mutex
.AssertHeld();
1200 if (IsSaturated()) {
1201 // We have an excessive call.
1202 IncrementCallCount();
1203 *what
<< "Mock function called more times than expected - ";
1204 mocker
->DescribeDefaultActionTo(args
, what
);
1205 DescribeCallCountTo(why
);
1210 IncrementCallCount();
1211 RetireAllPreRequisites();
1213 if (retires_on_saturation_
&& IsSaturated()) {
1217 // Must be done after IncrementCount()!
1218 *what
<< "Mock function call matches " << source_text() <<"...\n";
1219 return &(GetCurrentAction(mocker
, args
));
1222 // All the fields below won't change once the EXPECT_CALL()
1223 // statement finishes.
1224 FunctionMocker
<F
>* const owner_
;
1225 ArgumentMatcherTuple matchers_
;
1226 Matcher
<const ArgumentTuple
&> extra_matcher_
;
1227 Action
<F
> repeated_action_
;
1229 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation
);
1230 }; // class TypedExpectation
1232 // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1233 // specifying the default behavior of, or expectation on, a mock
1236 // Note: class MockSpec really belongs to the ::testing namespace.
1237 // However if we define it in ::testing, MSVC will complain when
1238 // classes in ::testing::internal declare it as a friend class
1239 // template. To workaround this compiler bug, we define MockSpec in
1240 // ::testing::internal and import it into ::testing.
1242 // Logs a message including file and line number information.
1243 GTEST_API_
void LogWithLocation(testing::internal::LogSeverity severity
,
1244 const char* file
, int line
,
1245 const std::string
& message
);
1247 template <typename F
>
1250 typedef typename
internal::Function
<F
>::ArgumentTuple ArgumentTuple
;
1251 typedef typename
internal::Function
<F
>::ArgumentMatcherTuple
1252 ArgumentMatcherTuple
;
1254 // Constructs a MockSpec object, given the function mocker object
1255 // that the spec is associated with.
1256 MockSpec(internal::FunctionMocker
<F
>* function_mocker
,
1257 const ArgumentMatcherTuple
& matchers
)
1258 : function_mocker_(function_mocker
), matchers_(matchers
) {}
1260 // Adds a new default action spec to the function mocker and returns
1261 // the newly created spec.
1262 internal::OnCallSpec
<F
>& InternalDefaultActionSetAt(
1263 const char* file
, int line
, const char* obj
, const char* call
) {
1264 LogWithLocation(internal::kInfo
, file
, line
,
1265 std::string("ON_CALL(") + obj
+ ", " + call
+ ") invoked");
1266 return function_mocker_
->AddNewOnCallSpec(file
, line
, matchers_
);
1269 // Adds a new expectation spec to the function mocker and returns
1270 // the newly created spec.
1271 internal::TypedExpectation
<F
>& InternalExpectedAt(
1272 const char* file
, int line
, const char* obj
, const char* call
) {
1273 const std::string
source_text(std::string("EXPECT_CALL(") + obj
+ ", " +
1275 LogWithLocation(internal::kInfo
, file
, line
, source_text
+ " invoked");
1276 return function_mocker_
->AddNewExpectation(
1277 file
, line
, source_text
, matchers_
);
1280 // This operator overload is used to swallow the superfluous parameter list
1281 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1283 MockSpec
<F
>& operator()(const internal::WithoutMatchers
&, void* const) {
1288 template <typename Function
>
1289 friend class internal::FunctionMocker
;
1291 // The function mocker that owns this spec.
1292 internal::FunctionMocker
<F
>* const function_mocker_
;
1293 // The argument matchers specified in the spec.
1294 ArgumentMatcherTuple matchers_
;
1296 GTEST_DISALLOW_ASSIGN_(MockSpec
);
1297 }; // class MockSpec
1299 // Wrapper type for generically holding an ordinary value or lvalue reference.
1300 // If T is not a reference type, it must be copyable or movable.
1301 // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1302 // T is a move-only value type (which means that it will always be copyable
1303 // if the current platform does not support move semantics).
1305 // The primary template defines handling for values, but function header
1306 // comments describe the contract for the whole template (including
1307 // specializations).
1308 template <typename T
>
1309 class ReferenceOrValueWrapper
{
1311 // Constructs a wrapper from the given value/reference.
1312 explicit ReferenceOrValueWrapper(T value
)
1313 : value_(std::move(value
)) {
1316 // Unwraps and returns the underlying value/reference, exactly as
1317 // originally passed. The behavior of calling this more than once on
1318 // the same object is unspecified.
1319 T
Unwrap() { return std::move(value_
); }
1321 // Provides nondestructive access to the underlying value/reference.
1322 // Always returns a const reference (more precisely,
1323 // const RemoveReference<T>&). The behavior of calling this after
1324 // calling Unwrap on the same object is unspecified.
1325 const T
& Peek() const {
1333 // Specialization for lvalue reference types. See primary template
1334 // for documentation.
1335 template <typename T
>
1336 class ReferenceOrValueWrapper
<T
&> {
1338 // Workaround for debatable pass-by-reference lint warning (c-library-team
1339 // policy precludes NOLINT in this context)
1340 typedef T
& reference
;
1341 explicit ReferenceOrValueWrapper(reference ref
)
1342 : value_ptr_(&ref
) {}
1343 T
& Unwrap() { return *value_ptr_
; }
1344 const T
& Peek() const { return *value_ptr_
; }
1350 // MSVC warns about using 'this' in base member initializer list, so
1351 // we need to temporarily disable the warning. We have to do it for
1352 // the entire class to suppress the warning, even though it's about
1353 // the constructor only.
1354 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
1356 // C++ treats the void type specially. For example, you cannot define
1357 // a void-typed variable or pass a void value to a function.
1358 // ActionResultHolder<T> holds a value of type T, where T must be a
1359 // copyable type or void (T doesn't need to be default-constructable).
1360 // It hides the syntactic difference between void and other types, and
1361 // is used to unify the code for invoking both void-returning and
1362 // non-void-returning mock functions.
1364 // Untyped base class for ActionResultHolder<T>.
1365 class UntypedActionResultHolderBase
{
1367 virtual ~UntypedActionResultHolderBase() {}
1369 // Prints the held value as an action's result to os.
1370 virtual void PrintAsActionResult(::std::ostream
* os
) const = 0;
1373 // This generic definition is used when T is not void.
1374 template <typename T
>
1375 class ActionResultHolder
: public UntypedActionResultHolderBase
{
1377 // Returns the held value. Must not be called more than once.
1379 return result_
.Unwrap();
1382 // Prints the held value as an action's result to os.
1383 void PrintAsActionResult(::std::ostream
* os
) const override
{
1384 *os
<< "\n Returns: ";
1385 // T may be a reference type, so we don't use UniversalPrint().
1386 UniversalPrinter
<T
>::Print(result_
.Peek(), os
);
1389 // Performs the given mock function's default action and returns the
1390 // result in a new-ed ActionResultHolder.
1391 template <typename F
>
1392 static ActionResultHolder
* PerformDefaultAction(
1393 const FunctionMocker
<F
>* func_mocker
,
1394 typename Function
<F
>::ArgumentTuple
&& args
,
1395 const std::string
& call_description
) {
1396 return new ActionResultHolder(Wrapper(func_mocker
->PerformDefaultAction(
1397 std::move(args
), call_description
)));
1400 // Performs the given action and returns the result in a new-ed
1401 // ActionResultHolder.
1402 template <typename F
>
1403 static ActionResultHolder
* PerformAction(
1404 const Action
<F
>& action
, typename Function
<F
>::ArgumentTuple
&& args
) {
1405 return new ActionResultHolder(
1406 Wrapper(action
.Perform(std::move(args
))));
1410 typedef ReferenceOrValueWrapper
<T
> Wrapper
;
1412 explicit ActionResultHolder(Wrapper result
)
1413 : result_(std::move(result
)) {
1418 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder
);
1421 // Specialization for T = void.
1423 class ActionResultHolder
<void> : public UntypedActionResultHolderBase
{
1427 void PrintAsActionResult(::std::ostream
* /* os */) const override
{}
1429 // Performs the given mock function's default action and returns ownership
1430 // of an empty ActionResultHolder*.
1431 template <typename F
>
1432 static ActionResultHolder
* PerformDefaultAction(
1433 const FunctionMocker
<F
>* func_mocker
,
1434 typename Function
<F
>::ArgumentTuple
&& args
,
1435 const std::string
& call_description
) {
1436 func_mocker
->PerformDefaultAction(std::move(args
), call_description
);
1437 return new ActionResultHolder
;
1440 // Performs the given action and returns ownership of an empty
1441 // ActionResultHolder*.
1442 template <typename F
>
1443 static ActionResultHolder
* PerformAction(
1444 const Action
<F
>& action
, typename Function
<F
>::ArgumentTuple
&& args
) {
1445 action
.Perform(std::move(args
));
1446 return new ActionResultHolder
;
1450 ActionResultHolder() {}
1451 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder
);
1454 template <typename F
>
1455 class FunctionMocker
;
1457 template <typename R
, typename
... Args
>
1458 class FunctionMocker
<R(Args
...)> final
: public UntypedFunctionMockerBase
{
1459 using F
= R(Args
...);
1463 using ArgumentTuple
= std::tuple
<Args
...>;
1464 using ArgumentMatcherTuple
= std::tuple
<Matcher
<Args
>...>;
1468 // There is no generally useful and implementable semantics of
1469 // copying a mock object, so copying a mock is usually a user error.
1470 // Thus we disallow copying function mockers. If the user really
1471 // wants to copy a mock object, they should implement their own copy
1472 // operation, for example:
1474 // class MockFoo : public Foo {
1476 // // Defines a copy constructor explicitly.
1477 // MockFoo(const MockFoo& src) {}
1480 FunctionMocker(const FunctionMocker
&) = delete;
1481 FunctionMocker
& operator=(const FunctionMocker
&) = delete;
1483 // The destructor verifies that all expectations on this mock
1484 // function have been satisfied. If not, it will report Google Test
1485 // non-fatal failures for the violations.
1486 ~FunctionMocker() override
GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1487 MutexLock
l(&g_gmock_mutex
);
1488 VerifyAndClearExpectationsLocked();
1489 Mock::UnregisterLocked(this);
1490 ClearDefaultActionsLocked();
1493 // Returns the ON_CALL spec that matches this mock function with the
1494 // given arguments; returns NULL if no matching ON_CALL is found.
1496 const OnCallSpec
<F
>* FindOnCallSpec(
1497 const ArgumentTuple
& args
) const {
1498 for (UntypedOnCallSpecs::const_reverse_iterator it
1499 = untyped_on_call_specs_
.rbegin();
1500 it
!= untyped_on_call_specs_
.rend(); ++it
) {
1501 const OnCallSpec
<F
>* spec
= static_cast<const OnCallSpec
<F
>*>(*it
);
1502 if (spec
->Matches(args
))
1509 // Performs the default action of this mock function on the given
1510 // arguments and returns the result. Asserts (or throws if
1511 // exceptions are enabled) with a helpful call descrption if there
1512 // is no valid return value. This method doesn't depend on the
1513 // mutable state of this object, and thus can be called concurrently
1516 Result
PerformDefaultAction(ArgumentTuple
&& args
,
1517 const std::string
& call_description
) const {
1518 const OnCallSpec
<F
>* const spec
=
1519 this->FindOnCallSpec(args
);
1520 if (spec
!= nullptr) {
1521 return spec
->GetAction().Perform(std::move(args
));
1523 const std::string message
=
1525 "\n The mock function has no default action "
1526 "set, and its return type has no default value set.";
1527 #if GTEST_HAS_EXCEPTIONS
1528 if (!DefaultValue
<Result
>::Exists()) {
1529 throw std::runtime_error(message
);
1532 Assert(DefaultValue
<Result
>::Exists(), "", -1, message
);
1534 return DefaultValue
<Result
>::Get();
1537 // Performs the default action with the given arguments and returns
1538 // the action's result. The call description string will be used in
1539 // the error message to describe the call in the case the default
1540 // action fails. The caller is responsible for deleting the result.
1542 UntypedActionResultHolderBase
* UntypedPerformDefaultAction(
1543 void* untyped_args
, // must point to an ArgumentTuple
1544 const std::string
& call_description
) const override
{
1545 ArgumentTuple
* args
= static_cast<ArgumentTuple
*>(untyped_args
);
1546 return ResultHolder::PerformDefaultAction(this, std::move(*args
),
1550 // Performs the given action with the given arguments and returns
1551 // the action's result. The caller is responsible for deleting the
1554 UntypedActionResultHolderBase
* UntypedPerformAction(
1555 const void* untyped_action
, void* untyped_args
) const override
{
1556 // Make a copy of the action before performing it, in case the
1557 // action deletes the mock object (and thus deletes itself).
1558 const Action
<F
> action
= *static_cast<const Action
<F
>*>(untyped_action
);
1559 ArgumentTuple
* args
= static_cast<ArgumentTuple
*>(untyped_args
);
1560 return ResultHolder::PerformAction(action
, std::move(*args
));
1563 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1564 // clears the ON_CALL()s set on this mock function.
1565 void ClearDefaultActionsLocked() override
1566 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1567 g_gmock_mutex
.AssertHeld();
1569 // Deleting our default actions may trigger other mock objects to be
1570 // deleted, for example if an action contains a reference counted smart
1571 // pointer to that mock object, and that is the last reference. So if we
1572 // delete our actions within the context of the global mutex we may deadlock
1573 // when this method is called again. Instead, make a copy of the set of
1574 // actions to delete, clear our set within the mutex, and then delete the
1575 // actions outside of the mutex.
1576 UntypedOnCallSpecs specs_to_delete
;
1577 untyped_on_call_specs_
.swap(specs_to_delete
);
1579 g_gmock_mutex
.Unlock();
1580 for (UntypedOnCallSpecs::const_iterator it
=
1581 specs_to_delete
.begin();
1582 it
!= specs_to_delete
.end(); ++it
) {
1583 delete static_cast<const OnCallSpec
<F
>*>(*it
);
1586 // Lock the mutex again, since the caller expects it to be locked when we
1588 g_gmock_mutex
.Lock();
1591 // Returns the result of invoking this mock function with the given
1592 // arguments. This function can be safely called from multiple
1593 // threads concurrently.
1594 Result
Invoke(Args
... args
) GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1595 ArgumentTuple
tuple(std::forward
<Args
>(args
)...);
1596 std::unique_ptr
<ResultHolder
> holder(DownCast_
<ResultHolder
*>(
1597 this->UntypedInvokeWith(static_cast<void*>(&tuple
))));
1598 return holder
->Unwrap();
1601 MockSpec
<F
> With(Matcher
<Args
>... m
) {
1602 return MockSpec
<F
>(this, ::std::make_tuple(std::move(m
)...));
1606 template <typename Function
>
1607 friend class MockSpec
;
1609 typedef ActionResultHolder
<Result
> ResultHolder
;
1611 // Adds and returns a default action spec for this mock function.
1612 OnCallSpec
<F
>& AddNewOnCallSpec(
1613 const char* file
, int line
,
1614 const ArgumentMatcherTuple
& m
)
1615 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1616 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file
, line
);
1617 OnCallSpec
<F
>* const on_call_spec
= new OnCallSpec
<F
>(file
, line
, m
);
1618 untyped_on_call_specs_
.push_back(on_call_spec
);
1619 return *on_call_spec
;
1622 // Adds and returns an expectation spec for this mock function.
1623 TypedExpectation
<F
>& AddNewExpectation(const char* file
, int line
,
1624 const std::string
& source_text
,
1625 const ArgumentMatcherTuple
& m
)
1626 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1627 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file
, line
);
1628 TypedExpectation
<F
>* const expectation
=
1629 new TypedExpectation
<F
>(this, file
, line
, source_text
, m
);
1630 const std::shared_ptr
<ExpectationBase
> untyped_expectation(expectation
);
1631 // See the definition of untyped_expectations_ for why access to
1632 // it is unprotected here.
1633 untyped_expectations_
.push_back(untyped_expectation
);
1635 // Adds this expectation into the implicit sequence if there is one.
1636 Sequence
* const implicit_sequence
= g_gmock_implicit_sequence
.get();
1637 if (implicit_sequence
!= nullptr) {
1638 implicit_sequence
->AddExpectation(Expectation(untyped_expectation
));
1641 return *expectation
;
1645 template <typename Func
> friend class TypedExpectation
;
1647 // Some utilities needed for implementing UntypedInvokeWith().
1649 // Describes what default action will be performed for the given
1652 void DescribeDefaultActionTo(const ArgumentTuple
& args
,
1653 ::std::ostream
* os
) const {
1654 const OnCallSpec
<F
>* const spec
= FindOnCallSpec(args
);
1656 if (spec
== nullptr) {
1657 *os
<< (std::is_void
<Result
>::value
? "returning directly.\n"
1658 : "returning default value.\n");
1660 *os
<< "taking default action specified at:\n"
1661 << FormatFileLocation(spec
->file(), spec
->line()) << "\n";
1665 // Writes a message that the call is uninteresting (i.e. neither
1666 // explicitly expected nor explicitly unexpected) to the given
1668 void UntypedDescribeUninterestingCall(const void* untyped_args
,
1669 ::std::ostream
* os
) const override
1670 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1671 const ArgumentTuple
& args
=
1672 *static_cast<const ArgumentTuple
*>(untyped_args
);
1673 *os
<< "Uninteresting mock function call - ";
1674 DescribeDefaultActionTo(args
, os
);
1675 *os
<< " Function call: " << Name();
1676 UniversalPrint(args
, os
);
1679 // Returns the expectation that matches the given function arguments
1680 // (or NULL is there's no match); when a match is found,
1681 // untyped_action is set to point to the action that should be
1682 // performed (or NULL if the action is "do default"), and
1683 // is_excessive is modified to indicate whether the call exceeds the
1686 // Critical section: We must find the matching expectation and the
1687 // corresponding action that needs to be taken in an ATOMIC
1688 // transaction. Otherwise another thread may call this mock
1689 // method in the middle and mess up the state.
1691 // However, performing the action has to be left out of the critical
1692 // section. The reason is that we have no control on what the
1693 // action does (it can invoke an arbitrary user function or even a
1694 // mock function) and excessive locking could cause a dead lock.
1695 const ExpectationBase
* UntypedFindMatchingExpectation(
1696 const void* untyped_args
, const void** untyped_action
, bool* is_excessive
,
1697 ::std::ostream
* what
, ::std::ostream
* why
) override
1698 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
1699 const ArgumentTuple
& args
=
1700 *static_cast<const ArgumentTuple
*>(untyped_args
);
1701 MutexLock
l(&g_gmock_mutex
);
1702 TypedExpectation
<F
>* exp
= this->FindMatchingExpectationLocked(args
);
1703 if (exp
== nullptr) { // A match wasn't found.
1704 this->FormatUnexpectedCallMessageLocked(args
, what
, why
);
1708 // This line must be done before calling GetActionForArguments(),
1709 // which will increment the call count for *exp and thus affect
1710 // its saturation status.
1711 *is_excessive
= exp
->IsSaturated();
1712 const Action
<F
>* action
= exp
->GetActionForArguments(this, args
, what
, why
);
1713 if (action
!= nullptr && action
->IsDoDefault())
1714 action
= nullptr; // Normalize "do default" to NULL.
1715 *untyped_action
= action
;
1719 // Prints the given function arguments to the ostream.
1720 void UntypedPrintArgs(const void* untyped_args
,
1721 ::std::ostream
* os
) const override
{
1722 const ArgumentTuple
& args
=
1723 *static_cast<const ArgumentTuple
*>(untyped_args
);
1724 UniversalPrint(args
, os
);
1727 // Returns the expectation that matches the arguments, or NULL if no
1728 // expectation matches them.
1729 TypedExpectation
<F
>* FindMatchingExpectationLocked(
1730 const ArgumentTuple
& args
) const
1731 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1732 g_gmock_mutex
.AssertHeld();
1733 // See the definition of untyped_expectations_ for why access to
1734 // it is unprotected here.
1735 for (typename
UntypedExpectations::const_reverse_iterator it
=
1736 untyped_expectations_
.rbegin();
1737 it
!= untyped_expectations_
.rend(); ++it
) {
1738 TypedExpectation
<F
>* const exp
=
1739 static_cast<TypedExpectation
<F
>*>(it
->get());
1740 if (exp
->ShouldHandleArguments(args
)) {
1747 // Returns a message that the arguments don't match any expectation.
1748 void FormatUnexpectedCallMessageLocked(
1749 const ArgumentTuple
& args
,
1751 ::std::ostream
* why
) const
1752 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1753 g_gmock_mutex
.AssertHeld();
1754 *os
<< "\nUnexpected mock function call - ";
1755 DescribeDefaultActionTo(args
, os
);
1756 PrintTriedExpectationsLocked(args
, why
);
1759 // Prints a list of expectations that have been tried against the
1760 // current mock function call.
1761 void PrintTriedExpectationsLocked(
1762 const ArgumentTuple
& args
,
1763 ::std::ostream
* why
) const
1764 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
1765 g_gmock_mutex
.AssertHeld();
1766 const size_t count
= untyped_expectations_
.size();
1767 *why
<< "Google Mock tried the following " << count
<< " "
1768 << (count
== 1 ? "expectation, but it didn't match" :
1769 "expectations, but none matched")
1771 for (size_t i
= 0; i
< count
; i
++) {
1772 TypedExpectation
<F
>* const expectation
=
1773 static_cast<TypedExpectation
<F
>*>(untyped_expectations_
[i
].get());
1775 expectation
->DescribeLocationTo(why
);
1777 *why
<< "tried expectation #" << i
<< ": ";
1779 *why
<< expectation
->source_text() << "...\n";
1780 expectation
->ExplainMatchResultTo(args
, why
);
1781 expectation
->DescribeCallCountTo(why
);
1784 }; // class FunctionMocker
1786 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
1788 // Reports an uninteresting call (whose description is in msg) in the
1789 // manner specified by 'reaction'.
1790 void ReportUninterestingCall(CallReaction reaction
, const std::string
& msg
);
1792 } // namespace internal
1794 // A MockFunction<F> class has one mock method whose type is F. It is
1795 // useful when you just want your test code to emit some messages and
1796 // have Google Mock verify the right messages are sent (and perhaps at
1797 // the right times). For example, if you are exercising code:
1803 // and want to verify that Foo(1) and Foo(3) both invoke
1804 // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1806 // TEST(FooTest, InvokesBarCorrectly) {
1808 // MockFunction<void(string check_point_name)> check;
1812 // EXPECT_CALL(mock, Bar("a"));
1813 // EXPECT_CALL(check, Call("1"));
1814 // EXPECT_CALL(check, Call("2"));
1815 // EXPECT_CALL(mock, Bar("a"));
1824 // The expectation spec says that the first Bar("a") must happen
1825 // before check point "1", the second Bar("a") must happen after check
1826 // point "2", and nothing should happen between the two check
1827 // points. The explicit check points make it easy to tell which
1828 // Bar("a") is called by which call to Foo().
1830 // MockFunction<F> can also be used to exercise code that accepts
1831 // std::function<F> callbacks. To do so, use AsStdFunction() method
1832 // to create std::function proxy forwarding to original object's Call.
1835 // TEST(FooTest, RunsCallbackWithBarArgument) {
1836 // MockFunction<int(string)> callback;
1837 // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1838 // Foo(callback.AsStdFunction());
1840 template <typename F
>
1843 template <typename R
, typename
... Args
>
1844 class MockFunction
<R(Args
...)> {
1847 MockFunction(const MockFunction
&) = delete;
1848 MockFunction
& operator=(const MockFunction
&) = delete;
1850 std::function
<R(Args
...)> AsStdFunction() {
1851 return [this](Args
... args
) -> R
{
1852 return this->Call(std::forward
<Args
>(args
)...);
1856 // Implementation detail: the expansion of the MOCK_METHOD macro.
1857 R
Call(Args
... args
) {
1858 mock_
.SetOwnerAndName(this, "Call");
1859 return mock_
.Invoke(std::forward
<Args
>(args
)...);
1862 internal::MockSpec
<R(Args
...)> gmock_Call(Matcher
<Args
>... m
) {
1863 mock_
.RegisterOwner(this);
1864 return mock_
.With(std::move(m
)...);
1867 internal::MockSpec
<R(Args
...)> gmock_Call(const internal::WithoutMatchers
&,
1869 return this->gmock_Call(::testing::A
<Args
>()...);
1873 internal::FunctionMocker
<R(Args
...)> mock_
;
1876 // The style guide prohibits "using" statements in a namespace scope
1877 // inside a header file. However, the MockSpec class template is
1878 // meant to be defined in the ::testing namespace. The following line
1879 // is just a trick for working around a bug in MSVC 8.0, which cannot
1880 // handle it if we define MockSpec in ::testing.
1881 using internal::MockSpec
;
1883 // Const(x) is a convenient function for obtaining a const reference
1884 // to x. This is useful for setting expectations on an overloaded
1885 // const mock method, e.g.
1887 // class MockFoo : public FooInterface {
1889 // MOCK_METHOD0(Bar, int());
1890 // MOCK_CONST_METHOD0(Bar, int&());
1894 // // Expects a call to non-const MockFoo::Bar().
1895 // EXPECT_CALL(foo, Bar());
1896 // // Expects a call to const MockFoo::Bar().
1897 // EXPECT_CALL(Const(foo), Bar());
1898 template <typename T
>
1899 inline const T
& Const(const T
& x
) { return x
; }
1901 // Constructs an Expectation object that references and co-owns exp.
1902 inline Expectation::Expectation(internal::ExpectationBase
& exp
) // NOLINT
1903 : expectation_base_(exp
.GetHandle().expectation_base()) {}
1905 } // namespace testing
1907 GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1909 // Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1910 // required to avoid compile errors when the name of the method used in call is
1911 // a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1912 // tests in internal/gmock-spec-builders_test.cc for more details.
1914 // This macro supports statements both with and without parameter matchers. If
1915 // the parameter list is omitted, gMock will accept any parameters, which allows
1916 // tests to be written that don't need to encode the number of method
1917 // parameter. This technique may only be used for non-overloaded methods.
1919 // // These are the same:
1920 // ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1921 // ON_CALL(mock, NoArgsMethod).WillByDefault(...);
1924 // ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1925 // ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
1927 // // Can also specify args if you want, of course:
1928 // ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
1930 // // Overloads work as long as you specify parameters:
1931 // ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1932 // ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
1934 // // Oops! Which overload did you want?
1935 // ON_CALL(mock, OverloadedMethod).WillByDefault(...);
1936 // => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1938 // How this works: The mock class uses two overloads of the gmock_Method
1939 // expectation setter method plus an operator() overload on the MockSpec object.
1940 // In the matcher list form, the macro expands to:
1942 // // This statement:
1943 // ON_CALL(mock, TwoArgsMethod(_, 45))...
1945 // // ...expands to:
1946 // mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
1947 // |-------------v---------------||------------v-------------|
1948 // invokes first overload swallowed by operator()
1950 // // ...which is essentially:
1951 // mock.gmock_TwoArgsMethod(_, 45)...
1953 // Whereas the form without a matcher list:
1955 // // This statement:
1956 // ON_CALL(mock, TwoArgsMethod)...
1958 // // ...expands to:
1959 // mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
1960 // |-----------------------v--------------------------|
1961 // invokes second overload
1963 // // ...which is essentially:
1964 // mock.gmock_TwoArgsMethod(_, _)...
1966 // The WithoutMatchers() argument is used to disambiguate overloads and to
1967 // block the caller from accidentally invoking the second overload directly. The
1968 // second argument is an internal type derived from the method signature. The
1969 // failure to disambiguate two overloads of this method in the ON_CALL statement
1970 // is how we block callers from setting expectations on overloaded methods.
1971 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1972 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
1974 .Setter(__FILE__, __LINE__, #mock_expr, #call)
1976 #define ON_CALL(obj, call) \
1977 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1979 #define EXPECT_CALL(obj, call) \
1980 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
1982 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_