1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 // Author: wan@google.com (Zhanyong Wan)
32 // Google Mock - a framework for writing C++ mock classes.
34 // This file implements some commonly used actions.
36 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
37 #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
46 #include "gmock/internal/gmock-internal-utils.h"
47 #include "gmock/internal/gmock-port.h"
49 #if GTEST_LANG_CXX11 // Defined by gtest-port.h via gmock-port.h.
51 #include <type_traits>
52 #endif // GTEST_LANG_CXX11
56 // To implement an action Foo, define:
57 // 1. a class FooAction that implements the ActionInterface interface, and
58 // 2. a factory function that creates an Action object from a
61 // The two-level delegation design follows that of Matcher, providing
62 // consistency for extension developers. It also eases ownership
63 // management as Action objects can now be copied like plain values.
67 template <typename F1
, typename F2
>
70 // BuiltInDefaultValueGetter<T, true>::Get() returns a
71 // default-constructed T value. BuiltInDefaultValueGetter<T,
72 // false>::Get() crashes with an error.
74 // This primary template is used when kDefaultConstructible is true.
75 template <typename T
, bool kDefaultConstructible
>
76 struct BuiltInDefaultValueGetter
{
77 static T
Get() { return T(); }
80 struct BuiltInDefaultValueGetter
<T
, false> {
82 Assert(false, __FILE__
, __LINE__
,
83 "Default action undefined for the function return type.");
84 return internal::Invalid
<T
>();
85 // The above statement will never be reached, but is required in
86 // order for this function to compile.
90 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
91 // for type T, which is NULL when T is a raw pointer type, 0 when T is
92 // a numeric type, false when T is bool, or "" when T is string or
93 // std::string. In addition, in C++11 and above, it turns a
94 // default-constructed T value if T is default constructible. For any
95 // other type T, the built-in default T value is undefined, and the
96 // function will abort the process.
98 class BuiltInDefaultValue
{
101 // This function returns true iff type T has a built-in default value.
102 static bool Exists() {
103 return ::std::is_default_constructible
<T
>::value
;
107 return BuiltInDefaultValueGetter
<
108 T
, ::std::is_default_constructible
<T
>::value
>::Get();
111 #else // GTEST_LANG_CXX11
112 // This function returns true iff type T has a built-in default value.
113 static bool Exists() {
118 return BuiltInDefaultValueGetter
<T
, false>::Get();
121 #endif // GTEST_LANG_CXX11
124 // This partial specialization says that we use the same built-in
125 // default value for T and const T.
126 template <typename T
>
127 class BuiltInDefaultValue
<const T
> {
129 static bool Exists() { return BuiltInDefaultValue
<T
>::Exists(); }
130 static T
Get() { return BuiltInDefaultValue
<T
>::Get(); }
133 // This partial specialization defines the default values for pointer
135 template <typename T
>
136 class BuiltInDefaultValue
<T
*> {
138 static bool Exists() { return true; }
139 static T
* Get() { return NULL
; }
142 // The following specializations define the default values for
143 // specific types we care about.
144 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
146 class BuiltInDefaultValue<type> { \
148 static bool Exists() { return true; } \
149 static type Get() { return value; } \
152 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
153 #if GTEST_HAS_GLOBAL_STRING
154 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string
, "");
155 #endif // GTEST_HAS_GLOBAL_STRING
156 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string
, "");
157 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
158 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
159 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
160 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
162 // There's no need for a default action for signed wchar_t, as that
163 // type is the same as wchar_t for gcc, and invalid for MSVC.
165 // There's also no need for a default action for unsigned wchar_t, as
166 // that type is the same as unsigned int for gcc, and invalid for
168 #if GMOCK_WCHAR_T_IS_NATIVE_
169 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
172 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
173 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
174 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
175 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
176 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
177 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
178 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64
, 0);
179 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64
, 0);
180 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
181 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
183 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
185 } // namespace internal
187 // When an unexpected function call is encountered, Google Mock will
188 // let it return a default value if the user has specified one for its
189 // return type, or if the return type has a built-in default value;
190 // otherwise Google Mock won't know what value to return and will have
191 // to abort the process.
193 // The DefaultValue<T> class allows a user to specify the
194 // default value for a type T that is both copyable and publicly
195 // destructible (i.e. anything that can be used as a function return
196 // type). The usage is:
198 // // Sets the default value for type T to be foo.
199 // DefaultValue<T>::Set(foo);
200 template <typename T
>
203 // Sets the default value for type T; requires T to be
204 // copy-constructable and have a public destructor.
205 static void Set(T x
) {
207 producer_
= new FixedValueProducer(x
);
210 // Provides a factory function to be called to generate the default value.
211 // This method can be used even if T is only move-constructible, but it is not
212 // limited to that case.
213 typedef T (*FactoryFunction
)();
214 static void SetFactory(FactoryFunction factory
) {
216 producer_
= new FactoryValueProducer(factory
);
219 // Unsets the default value for type T.
220 static void Clear() {
225 // Returns true iff the user has set the default value for type T.
226 static bool IsSet() { return producer_
!= NULL
; }
228 // Returns true if T has a default return value set by the user or there
229 // exists a built-in default value.
230 static bool Exists() {
231 return IsSet() || internal::BuiltInDefaultValue
<T
>::Exists();
234 // Returns the default value for type T if the user has set one;
235 // otherwise returns the built-in default value. Requires that Exists()
236 // is true, which ensures that the return value is well-defined.
238 return producer_
== NULL
?
239 internal::BuiltInDefaultValue
<T
>::Get() : producer_
->Produce();
243 class ValueProducer
{
245 virtual ~ValueProducer() {}
246 virtual T
Produce() = 0;
249 class FixedValueProducer
: public ValueProducer
{
251 explicit FixedValueProducer(T value
) : value_(value
) {}
252 virtual T
Produce() { return value_
; }
256 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer
);
259 class FactoryValueProducer
: public ValueProducer
{
261 explicit FactoryValueProducer(FactoryFunction factory
)
262 : factory_(factory
) {}
263 virtual T
Produce() { return factory_(); }
266 const FactoryFunction factory_
;
267 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer
);
270 static ValueProducer
* producer_
;
273 // This partial specialization allows a user to set default values for
275 template <typename T
>
276 class DefaultValue
<T
&> {
278 // Sets the default value for type T&.
279 static void Set(T
& x
) { // NOLINT
283 // Unsets the default value for type T&.
284 static void Clear() {
288 // Returns true iff the user has set the default value for type T&.
289 static bool IsSet() { return address_
!= NULL
; }
291 // Returns true if T has a default return value set by the user or there
292 // exists a built-in default value.
293 static bool Exists() {
294 return IsSet() || internal::BuiltInDefaultValue
<T
&>::Exists();
297 // Returns the default value for type T& if the user has set one;
298 // otherwise returns the built-in default value if there is one;
299 // otherwise aborts the process.
301 return address_
== NULL
?
302 internal::BuiltInDefaultValue
<T
&>::Get() : *address_
;
309 // This specialization allows DefaultValue<void>::Get() to
312 class DefaultValue
<void> {
314 static bool Exists() { return true; }
318 // Points to the user-set default value for type T.
319 template <typename T
>
320 typename DefaultValue
<T
>::ValueProducer
* DefaultValue
<T
>::producer_
= NULL
;
322 // Points to the user-set default value for type T&.
323 template <typename T
>
324 T
* DefaultValue
<T
&>::address_
= NULL
;
326 // Implement this interface to define an action for function type F.
327 template <typename F
>
328 class ActionInterface
{
330 typedef typename
internal::Function
<F
>::Result Result
;
331 typedef typename
internal::Function
<F
>::ArgumentTuple ArgumentTuple
;
334 virtual ~ActionInterface() {}
336 // Performs the action. This method is not const, as in general an
337 // action can have side effects and be stateful. For example, a
338 // get-the-next-element-from-the-collection action will need to
339 // remember the current element.
340 virtual Result
Perform(const ArgumentTuple
& args
) = 0;
343 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface
);
346 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
347 // object that represents an action to be taken when a mock function
348 // of type F is called. The implementation of Action<T> is just a
349 // linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
350 // Don't inherit from Action!
352 // You can view an object implementing ActionInterface<F> as a
353 // concrete action (including its current state), and an Action<F>
354 // object as a handle to it.
355 template <typename F
>
358 typedef typename
internal::Function
<F
>::Result Result
;
359 typedef typename
internal::Function
<F
>::ArgumentTuple ArgumentTuple
;
361 // Constructs a null Action. Needed for storing Action objects in
366 // Construct an Action from a specified callable.
367 // This cannot take std::function directly, because then Action would not be
368 // directly constructible from lambda (it would require two conversions).
369 template <typename G
,
370 typename
= typename ::std::enable_if
<
371 ::std::is_constructible
<::std::function
<F
>, G
>::value
>::type
>
372 Action(G
&& fun
) : fun_(::std::forward
<G
>(fun
)) {} // NOLINT
375 // Constructs an Action from its implementation.
376 explicit Action(ActionInterface
<F
>* impl
) : impl_(impl
) {}
378 // This constructor allows us to turn an Action<Func> object into an
379 // Action<F>, as long as F's arguments can be implicitly converted
380 // to Func's and Func's return type can be implicitly converted to
382 template <typename Func
>
383 explicit Action(const Action
<Func
>& action
);
385 // Returns true iff this is the DoDefault() action.
386 bool IsDoDefault() const {
388 return impl_
== nullptr && fun_
== nullptr;
390 return impl_
== NULL
;
394 // Performs the action. Note that this method is const even though
395 // the corresponding method in ActionInterface is not. The reason
396 // is that a const Action<F> means that it cannot be re-bound to
397 // another concrete action, not that the concrete action it binds to
398 // cannot change state. (Think of the difference between a const
399 // pointer and a pointer to const.)
400 Result
Perform(ArgumentTuple args
) const {
402 internal::IllegalDoDefault(__FILE__
, __LINE__
);
405 if (fun_
!= nullptr) {
406 return internal::Apply(fun_
, ::std::move(args
));
409 return impl_
->Perform(args
);
413 template <typename F1
, typename F2
>
414 friend class internal::ActionAdaptor
;
416 template <typename G
>
419 // In C++11, Action can be implemented either as a generic functor (through
420 // std::function), or legacy ActionInterface. In C++98, only ActionInterface
421 // is available. The invariants are as follows:
422 // * in C++98, impl_ is null iff this is the default action
423 // * in C++11, at most one of fun_ & impl_ may be nonnull; both are null iff
424 // this is the default action
426 ::std::function
<F
> fun_
;
428 internal::linked_ptr
<ActionInterface
<F
> > impl_
;
431 // The PolymorphicAction class template makes it easy to implement a
432 // polymorphic action (i.e. an action that can be used in mock
433 // functions of than one type, e.g. Return()).
435 // To define a polymorphic action, a user first provides a COPYABLE
436 // implementation class that has a Perform() method template:
440 // template <typename Result, typename ArgumentTuple>
441 // Result Perform(const ArgumentTuple& args) const {
442 // // Processes the arguments and returns a result, using
443 // // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
448 // Then the user creates the polymorphic action using
449 // MakePolymorphicAction(object) where object has type FooAction. See
450 // the definition of Return(void) and SetArgumentPointee<N>(value) for
451 // complete examples.
452 template <typename Impl
>
453 class PolymorphicAction
{
455 explicit PolymorphicAction(const Impl
& impl
) : impl_(impl
) {}
457 template <typename F
>
458 operator Action
<F
>() const {
459 return Action
<F
>(new MonomorphicImpl
<F
>(impl_
));
463 template <typename F
>
464 class MonomorphicImpl
: public ActionInterface
<F
> {
466 typedef typename
internal::Function
<F
>::Result Result
;
467 typedef typename
internal::Function
<F
>::ArgumentTuple ArgumentTuple
;
469 explicit MonomorphicImpl(const Impl
& impl
) : impl_(impl
) {}
471 virtual Result
Perform(const ArgumentTuple
& args
) {
472 return impl_
.template Perform
<Result
>(args
);
478 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl
);
483 GTEST_DISALLOW_ASSIGN_(PolymorphicAction
);
486 // Creates an Action from its implementation and returns it. The
487 // created Action object owns the implementation.
488 template <typename F
>
489 Action
<F
> MakeAction(ActionInterface
<F
>* impl
) {
490 return Action
<F
>(impl
);
493 // Creates a polymorphic action from its implementation. This is
494 // easier to use than the PolymorphicAction<Impl> constructor as it
495 // doesn't require you to explicitly write the template argument, e.g.
497 // MakePolymorphicAction(foo);
499 // PolymorphicAction<TypeOfFoo>(foo);
500 template <typename Impl
>
501 inline PolymorphicAction
<Impl
> MakePolymorphicAction(const Impl
& impl
) {
502 return PolymorphicAction
<Impl
>(impl
);
507 // Allows an Action<F2> object to pose as an Action<F1>, as long as F2
508 // and F1 are compatible.
509 template <typename F1
, typename F2
>
510 class ActionAdaptor
: public ActionInterface
<F1
> {
512 typedef typename
internal::Function
<F1
>::Result Result
;
513 typedef typename
internal::Function
<F1
>::ArgumentTuple ArgumentTuple
;
515 explicit ActionAdaptor(const Action
<F2
>& from
) : impl_(from
.impl_
) {}
517 virtual Result
Perform(const ArgumentTuple
& args
) {
518 return impl_
->Perform(args
);
522 const internal::linked_ptr
<ActionInterface
<F2
> > impl_
;
524 GTEST_DISALLOW_ASSIGN_(ActionAdaptor
);
527 // Helper struct to specialize ReturnAction to execute a move instead of a copy
528 // on return. Useful for move-only types, but could be used on any type.
529 template <typename T
>
530 struct ByMoveWrapper
{
531 explicit ByMoveWrapper(T value
) : payload(internal::move(value
)) {}
535 // Implements the polymorphic Return(x) action, which can be used in
536 // any function that returns the type of x, regardless of the argument
539 // Note: The value passed into Return must be converted into
540 // Function<F>::Result when this action is cast to Action<F> rather than
541 // when that action is performed. This is important in scenarios like
543 // MOCK_METHOD1(Method, T(U));
548 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
551 // In the example above the variable x holds reference to foo which leaves
552 // scope and gets destroyed. If copying X just copies a reference to foo,
553 // that copy will be left with a hanging reference. If conversion to T
554 // makes a copy of foo, the above code is safe. To support that scenario, we
555 // need to make sure that the type conversion happens inside the EXPECT_CALL
556 // statement, and conversion of the result of Return to Action<T(U)> is a
557 // good place for that.
559 // The real life example of the above scenario happens when an invocation
560 // of gtl::Container() is passed into Return.
562 template <typename R
>
565 // Constructs a ReturnAction object from the value to be returned.
566 // 'value' is passed by value instead of by const reference in order
567 // to allow Return("string literal") to compile.
568 explicit ReturnAction(R value
) : value_(new R(internal::move(value
))) {}
570 // This template type conversion operator allows Return(x) to be
571 // used in ANY function that returns x's type.
572 template <typename F
>
573 operator Action
<F
>() const {
574 // Assert statement belongs here because this is the best place to verify
575 // conditions on F. It produces the clearest error messages
576 // in most compilers.
577 // Impl really belongs in this scope as a local class but can't
578 // because MSVC produces duplicate symbols in different translation units
579 // in this case. Until MS fixes that bug we put Impl into the class scope
580 // and put the typedef both here (for use in assert statement) and
581 // in the Impl class. But both definitions must be the same.
582 typedef typename Function
<F
>::Result Result
;
583 GTEST_COMPILE_ASSERT_(
584 !is_reference
<Result
>::value
,
585 use_ReturnRef_instead_of_Return_to_return_a_reference
);
586 return Action
<F
>(new Impl
<R
, F
>(value_
));
590 // Implements the Return(x) action for a particular function type F.
591 template <typename R_
, typename F
>
592 class Impl
: public ActionInterface
<F
> {
594 typedef typename Function
<F
>::Result Result
;
595 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
597 // The implicit cast is necessary when Result has more than one
598 // single-argument constructor (e.g. Result is std::vector<int>) and R
599 // has a type conversion operator template. In that case, value_(value)
600 // won't compile as the compiler doesn't known which constructor of
601 // Result to call. ImplicitCast_ forces the compiler to convert R to
602 // Result without considering explicit constructors, thus resolving the
603 // ambiguity. value_ is then initialized using its copy constructor.
604 explicit Impl(const linked_ptr
<R
>& value
)
605 : value_before_cast_(*value
),
606 value_(ImplicitCast_
<Result
>(value_before_cast_
)) {}
608 virtual Result
Perform(const ArgumentTuple
&) { return value_
; }
611 GTEST_COMPILE_ASSERT_(!is_reference
<Result
>::value
,
612 Result_cannot_be_a_reference_type
);
613 // We save the value before casting just in case it is being cast to a
615 R value_before_cast_
;
618 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl
);
621 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
622 // move its contents instead.
623 template <typename R_
, typename F
>
624 class Impl
<ByMoveWrapper
<R_
>, F
> : public ActionInterface
<F
> {
626 typedef typename Function
<F
>::Result Result
;
627 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
629 explicit Impl(const linked_ptr
<R
>& wrapper
)
630 : performed_(false), wrapper_(wrapper
) {}
632 virtual Result
Perform(const ArgumentTuple
&) {
633 GTEST_CHECK_(!performed_
)
634 << "A ByMove() action should only be performed once.";
636 return internal::move(wrapper_
->payload
);
641 const linked_ptr
<R
> wrapper_
;
643 GTEST_DISALLOW_ASSIGN_(Impl
);
646 const linked_ptr
<R
> value_
;
648 GTEST_DISALLOW_ASSIGN_(ReturnAction
);
651 // Implements the ReturnNull() action.
652 class ReturnNullAction
{
654 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
655 // this is enforced by returning nullptr, and in non-C++11 by asserting a
656 // pointer type on compile time.
657 template <typename Result
, typename ArgumentTuple
>
658 static Result
Perform(const ArgumentTuple
&) {
662 GTEST_COMPILE_ASSERT_(internal::is_pointer
<Result
>::value
,
663 ReturnNull_can_be_used_to_return_a_pointer_only
);
665 #endif // GTEST_LANG_CXX11
669 // Implements the Return() action.
670 class ReturnVoidAction
{
672 // Allows Return() to be used in any void-returning function.
673 template <typename Result
, typename ArgumentTuple
>
674 static void Perform(const ArgumentTuple
&) {
675 CompileAssertTypesEqual
<void, Result
>();
679 // Implements the polymorphic ReturnRef(x) action, which can be used
680 // in any function that returns a reference to the type of x,
681 // regardless of the argument types.
682 template <typename T
>
683 class ReturnRefAction
{
685 // Constructs a ReturnRefAction object from the reference to be returned.
686 explicit ReturnRefAction(T
& ref
) : ref_(ref
) {} // NOLINT
688 // This template type conversion operator allows ReturnRef(x) to be
689 // used in ANY function that returns a reference to x's type.
690 template <typename F
>
691 operator Action
<F
>() const {
692 typedef typename Function
<F
>::Result Result
;
693 // Asserts that the function return type is a reference. This
694 // catches the user error of using ReturnRef(x) when Return(x)
695 // should be used, and generates some helpful error message.
696 GTEST_COMPILE_ASSERT_(internal::is_reference
<Result
>::value
,
697 use_Return_instead_of_ReturnRef_to_return_a_value
);
698 return Action
<F
>(new Impl
<F
>(ref_
));
702 // Implements the ReturnRef(x) action for a particular function type F.
703 template <typename F
>
704 class Impl
: public ActionInterface
<F
> {
706 typedef typename Function
<F
>::Result Result
;
707 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
709 explicit Impl(T
& ref
) : ref_(ref
) {} // NOLINT
711 virtual Result
Perform(const ArgumentTuple
&) {
718 GTEST_DISALLOW_ASSIGN_(Impl
);
723 GTEST_DISALLOW_ASSIGN_(ReturnRefAction
);
726 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
727 // used in any function that returns a reference to the type of x,
728 // regardless of the argument types.
729 template <typename T
>
730 class ReturnRefOfCopyAction
{
732 // Constructs a ReturnRefOfCopyAction object from the reference to
734 explicit ReturnRefOfCopyAction(const T
& value
) : value_(value
) {} // NOLINT
736 // This template type conversion operator allows ReturnRefOfCopy(x) to be
737 // used in ANY function that returns a reference to x's type.
738 template <typename F
>
739 operator Action
<F
>() const {
740 typedef typename Function
<F
>::Result Result
;
741 // Asserts that the function return type is a reference. This
742 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
743 // should be used, and generates some helpful error message.
744 GTEST_COMPILE_ASSERT_(
745 internal::is_reference
<Result
>::value
,
746 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value
);
747 return Action
<F
>(new Impl
<F
>(value_
));
751 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
752 template <typename F
>
753 class Impl
: public ActionInterface
<F
> {
755 typedef typename Function
<F
>::Result Result
;
756 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
758 explicit Impl(const T
& value
) : value_(value
) {} // NOLINT
760 virtual Result
Perform(const ArgumentTuple
&) {
767 GTEST_DISALLOW_ASSIGN_(Impl
);
772 GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction
);
775 // Implements the polymorphic DoDefault() action.
776 class DoDefaultAction
{
778 // This template type conversion operator allows DoDefault() to be
779 // used in any function.
780 template <typename F
>
781 operator Action
<F
>() const { return Action
<F
>(); } // NOLINT
784 // Implements the Assign action to set a given pointer referent to a
786 template <typename T1
, typename T2
>
789 AssignAction(T1
* ptr
, T2 value
) : ptr_(ptr
), value_(value
) {}
791 template <typename Result
, typename ArgumentTuple
>
792 void Perform(const ArgumentTuple
& /* args */) const {
800 GTEST_DISALLOW_ASSIGN_(AssignAction
);
803 #if !GTEST_OS_WINDOWS_MOBILE
805 // Implements the SetErrnoAndReturn action to simulate return from
806 // various system calls and libc functions.
807 template <typename T
>
808 class SetErrnoAndReturnAction
{
810 SetErrnoAndReturnAction(int errno_value
, T result
)
811 : errno_(errno_value
),
813 template <typename Result
, typename ArgumentTuple
>
814 Result
Perform(const ArgumentTuple
& /* args */) const {
823 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction
);
826 #endif // !GTEST_OS_WINDOWS_MOBILE
828 // Implements the SetArgumentPointee<N>(x) action for any function
829 // whose N-th argument (0-based) is a pointer to x's type. The
830 // template parameter kIsProto is true iff type A is ProtocolMessage,
831 // proto2::Message, or a sub-class of those.
832 template <size_t N
, typename A
, bool kIsProto
>
833 class SetArgumentPointeeAction
{
835 // Constructs an action that sets the variable pointed to by the
836 // N-th function argument to 'value'.
837 explicit SetArgumentPointeeAction(const A
& value
) : value_(value
) {}
839 template <typename Result
, typename ArgumentTuple
>
840 void Perform(const ArgumentTuple
& args
) const {
841 CompileAssertTypesEqual
<void, Result
>();
842 *::testing::get
<N
>(args
) = value_
;
848 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction
);
851 template <size_t N
, typename Proto
>
852 class SetArgumentPointeeAction
<N
, Proto
, true> {
854 // Constructs an action that sets the variable pointed to by the
855 // N-th function argument to 'proto'. Both ProtocolMessage and
856 // proto2::Message have the CopyFrom() method, so the same
857 // implementation works for both.
858 explicit SetArgumentPointeeAction(const Proto
& proto
) : proto_(new Proto
) {
859 proto_
->CopyFrom(proto
);
862 template <typename Result
, typename ArgumentTuple
>
863 void Perform(const ArgumentTuple
& args
) const {
864 CompileAssertTypesEqual
<void, Result
>();
865 ::testing::get
<N
>(args
)->CopyFrom(*proto_
);
869 const internal::linked_ptr
<Proto
> proto_
;
871 GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction
);
874 // Implements the InvokeWithoutArgs(f) action. The template argument
875 // FunctionImpl is the implementation type of f, which can be either a
876 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
877 // Action<F> as long as f's type is compatible with F (i.e. f can be
878 // assigned to a tr1::function<F>).
879 template <typename FunctionImpl
>
880 class InvokeWithoutArgsAction
{
882 // The c'tor makes a copy of function_impl (either a function
883 // pointer or a functor).
884 explicit InvokeWithoutArgsAction(FunctionImpl function_impl
)
885 : function_impl_(function_impl
) {}
887 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
888 // compatible with f.
889 template <typename Result
, typename ArgumentTuple
>
890 Result
Perform(const ArgumentTuple
&) { return function_impl_(); }
893 FunctionImpl function_impl_
;
895 GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction
);
898 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
899 template <class Class
, typename MethodPtr
>
900 class InvokeMethodWithoutArgsAction
{
902 InvokeMethodWithoutArgsAction(Class
* obj_ptr
, MethodPtr method_ptr
)
903 : obj_ptr_(obj_ptr
), method_ptr_(method_ptr
) {}
905 template <typename Result
, typename ArgumentTuple
>
906 Result
Perform(const ArgumentTuple
&) const {
907 return (obj_ptr_
->*method_ptr_
)();
911 Class
* const obj_ptr_
;
912 const MethodPtr method_ptr_
;
914 GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction
);
917 // Implements the InvokeWithoutArgs(callback) action.
918 template <typename CallbackType
>
919 class InvokeCallbackWithoutArgsAction
{
921 // The c'tor takes ownership of the callback.
922 explicit InvokeCallbackWithoutArgsAction(CallbackType
* callback
)
923 : callback_(callback
) {
924 callback
->CheckIsRepeatable(); // Makes sure the callback is permanent.
927 // This type conversion operator template allows Invoke(callback) to
928 // be used wherever the callback's return type can be implicitly
929 // converted to that of the mock function.
930 template <typename Result
, typename ArgumentTuple
>
931 Result
Perform(const ArgumentTuple
&) const { return callback_
->Run(); }
934 const internal::linked_ptr
<CallbackType
> callback_
;
936 GTEST_DISALLOW_ASSIGN_(InvokeCallbackWithoutArgsAction
);
939 // Implements the IgnoreResult(action) action.
940 template <typename A
>
941 class IgnoreResultAction
{
943 explicit IgnoreResultAction(const A
& action
) : action_(action
) {}
945 template <typename F
>
946 operator Action
<F
>() const {
947 // Assert statement belongs here because this is the best place to verify
948 // conditions on F. It produces the clearest error messages
949 // in most compilers.
950 // Impl really belongs in this scope as a local class but can't
951 // because MSVC produces duplicate symbols in different translation units
952 // in this case. Until MS fixes that bug we put Impl into the class scope
953 // and put the typedef both here (for use in assert statement) and
954 // in the Impl class. But both definitions must be the same.
955 typedef typename
internal::Function
<F
>::Result Result
;
957 // Asserts at compile time that F returns void.
958 CompileAssertTypesEqual
<void, Result
>();
960 return Action
<F
>(new Impl
<F
>(action_
));
964 template <typename F
>
965 class Impl
: public ActionInterface
<F
> {
967 typedef typename
internal::Function
<F
>::Result Result
;
968 typedef typename
internal::Function
<F
>::ArgumentTuple ArgumentTuple
;
970 explicit Impl(const A
& action
) : action_(action
) {}
972 virtual void Perform(const ArgumentTuple
& args
) {
973 // Performs the action and ignores its result.
974 action_
.Perform(args
);
978 // Type OriginalFunction is the same as F except that its return
979 // type is IgnoredValue.
980 typedef typename
internal::Function
<F
>::MakeResultIgnoredValue
983 const Action
<OriginalFunction
> action_
;
985 GTEST_DISALLOW_ASSIGN_(Impl
);
990 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction
);
993 // A ReferenceWrapper<T> object represents a reference to type T,
994 // which can be either const or not. It can be explicitly converted
995 // from, and implicitly converted to, a T&. Unlike a reference,
996 // ReferenceWrapper<T> can be copied and can survive template type
997 // inference. This is used to support by-reference arguments in the
998 // InvokeArgument<N>(...) action. The idea was from "reference
999 // wrappers" in tr1, which we don't have in our source tree yet.
1000 template <typename T
>
1001 class ReferenceWrapper
{
1003 // Constructs a ReferenceWrapper<T> object from a T&.
1004 explicit ReferenceWrapper(T
& l_value
) : pointer_(&l_value
) {} // NOLINT
1006 // Allows a ReferenceWrapper<T> object to be implicitly converted to
1008 operator T
&() const { return *pointer_
; }
1013 // Allows the expression ByRef(x) to be printed as a reference to x.
1014 template <typename T
>
1015 void PrintTo(const ReferenceWrapper
<T
>& ref
, ::std::ostream
* os
) {
1017 UniversalPrinter
<T
&>::Print(value
, os
);
1020 // Does two actions sequentially. Used for implementing the DoAll(a1,
1022 template <typename Action1
, typename Action2
>
1023 class DoBothAction
{
1025 DoBothAction(Action1 action1
, Action2 action2
)
1026 : action1_(action1
), action2_(action2
) {}
1028 // This template type conversion operator allows DoAll(a1, ..., a_n)
1029 // to be used in ANY function of compatible type.
1030 template <typename F
>
1031 operator Action
<F
>() const {
1032 return Action
<F
>(new Impl
<F
>(action1_
, action2_
));
1036 // Implements the DoAll(...) action for a particular function type F.
1037 template <typename F
>
1038 class Impl
: public ActionInterface
<F
> {
1040 typedef typename Function
<F
>::Result Result
;
1041 typedef typename Function
<F
>::ArgumentTuple ArgumentTuple
;
1042 typedef typename Function
<F
>::MakeResultVoid VoidResult
;
1044 Impl(const Action
<VoidResult
>& action1
, const Action
<F
>& action2
)
1045 : action1_(action1
), action2_(action2
) {}
1047 virtual Result
Perform(const ArgumentTuple
& args
) {
1048 action1_
.Perform(args
);
1049 return action2_
.Perform(args
);
1053 const Action
<VoidResult
> action1_
;
1054 const Action
<F
> action2_
;
1056 GTEST_DISALLOW_ASSIGN_(Impl
);
1062 GTEST_DISALLOW_ASSIGN_(DoBothAction
);
1065 } // namespace internal
1067 // An Unused object can be implicitly constructed from ANY value.
1068 // This is handy when defining actions that ignore some or all of the
1069 // mock function arguments. For example, given
1071 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1072 // MOCK_METHOD3(Bar, double(int index, double x, double y));
1076 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
1077 // return sqrt(x*x + y*y);
1079 // double DistanceToOriginWithIndex(int index, double x, double y) {
1080 // return sqrt(x*x + y*y);
1083 // EXPECT_CALL(mock, Foo("abc", _, _))
1084 // .WillOnce(Invoke(DistanceToOriginWithLabel));
1085 // EXPECT_CALL(mock, Bar(5, _, _))
1086 // .WillOnce(Invoke(DistanceToOriginWithIndex));
1090 // // We can declare any uninteresting argument as Unused.
1091 // double DistanceToOrigin(Unused, double x, double y) {
1092 // return sqrt(x*x + y*y);
1095 // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
1096 // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
1097 typedef internal::IgnoredValue Unused
;
1099 // This constructor allows us to turn an Action<From> object into an
1100 // Action<To>, as long as To's arguments can be implicitly converted
1101 // to From's and From's return type cann be implicitly converted to
1103 template <typename To
>
1104 template <typename From
>
1105 Action
<To
>::Action(const Action
<From
>& from
)
1107 #if GTEST_LANG_CXX11
1110 impl_(from
.impl_
== NULL
? NULL
1111 : new internal::ActionAdaptor
<To
, From
>(from
)) {
1114 // Creates an action that returns 'value'. 'value' is passed by value
1115 // instead of const reference - otherwise Return("string literal")
1116 // will trigger a compiler error about using array as initializer.
1117 template <typename R
>
1118 internal::ReturnAction
<R
> Return(R value
) {
1119 return internal::ReturnAction
<R
>(internal::move(value
));
1122 // Creates an action that returns NULL.
1123 inline PolymorphicAction
<internal::ReturnNullAction
> ReturnNull() {
1124 return MakePolymorphicAction(internal::ReturnNullAction());
1127 // Creates an action that returns from a void function.
1128 inline PolymorphicAction
<internal::ReturnVoidAction
> Return() {
1129 return MakePolymorphicAction(internal::ReturnVoidAction());
1132 // Creates an action that returns the reference to a variable.
1133 template <typename R
>
1134 inline internal::ReturnRefAction
<R
> ReturnRef(R
& x
) { // NOLINT
1135 return internal::ReturnRefAction
<R
>(x
);
1138 // Creates an action that returns the reference to a copy of the
1139 // argument. The copy is created when the action is constructed and
1140 // lives as long as the action.
1141 template <typename R
>
1142 inline internal::ReturnRefOfCopyAction
<R
> ReturnRefOfCopy(const R
& x
) {
1143 return internal::ReturnRefOfCopyAction
<R
>(x
);
1146 // Modifies the parent action (a Return() action) to perform a move of the
1147 // argument instead of a copy.
1148 // Return(ByMove()) actions can only be executed once and will assert this
1150 template <typename R
>
1151 internal::ByMoveWrapper
<R
> ByMove(R x
) {
1152 return internal::ByMoveWrapper
<R
>(internal::move(x
));
1155 // Creates an action that does the default action for the give mock function.
1156 inline internal::DoDefaultAction
DoDefault() {
1157 return internal::DoDefaultAction();
1160 // Creates an action that sets the variable pointed by the N-th
1161 // (0-based) function argument to 'value'.
1162 template <size_t N
, typename T
>
1164 internal::SetArgumentPointeeAction
<
1165 N
, T
, internal::IsAProtocolMessage
<T
>::value
> >
1166 SetArgPointee(const T
& x
) {
1167 return MakePolymorphicAction(internal::SetArgumentPointeeAction
<
1168 N
, T
, internal::IsAProtocolMessage
<T
>::value
>(x
));
1171 #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
1172 // This overload allows SetArgPointee() to accept a string literal.
1173 // GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish
1174 // this overload from the templated version and emit a compile error.
1177 internal::SetArgumentPointeeAction
<N
, const char*, false> >
1178 SetArgPointee(const char* p
) {
1179 return MakePolymorphicAction(internal::SetArgumentPointeeAction
<
1180 N
, const char*, false>(p
));
1185 internal::SetArgumentPointeeAction
<N
, const wchar_t*, false> >
1186 SetArgPointee(const wchar_t* p
) {
1187 return MakePolymorphicAction(internal::SetArgumentPointeeAction
<
1188 N
, const wchar_t*, false>(p
));
1192 // The following version is DEPRECATED.
1193 template <size_t N
, typename T
>
1195 internal::SetArgumentPointeeAction
<
1196 N
, T
, internal::IsAProtocolMessage
<T
>::value
> >
1197 SetArgumentPointee(const T
& x
) {
1198 return MakePolymorphicAction(internal::SetArgumentPointeeAction
<
1199 N
, T
, internal::IsAProtocolMessage
<T
>::value
>(x
));
1202 // Creates an action that sets a pointer referent to a given value.
1203 template <typename T1
, typename T2
>
1204 PolymorphicAction
<internal::AssignAction
<T1
, T2
> > Assign(T1
* ptr
, T2 val
) {
1205 return MakePolymorphicAction(internal::AssignAction
<T1
, T2
>(ptr
, val
));
1208 #if !GTEST_OS_WINDOWS_MOBILE
1210 // Creates an action that sets errno and returns the appropriate error.
1211 template <typename T
>
1212 PolymorphicAction
<internal::SetErrnoAndReturnAction
<T
> >
1213 SetErrnoAndReturn(int errval
, T result
) {
1214 return MakePolymorphicAction(
1215 internal::SetErrnoAndReturnAction
<T
>(errval
, result
));
1218 #endif // !GTEST_OS_WINDOWS_MOBILE
1220 // Various overloads for InvokeWithoutArgs().
1222 // Creates an action that invokes 'function_impl' with no argument.
1223 template <typename FunctionImpl
>
1224 PolymorphicAction
<internal::InvokeWithoutArgsAction
<FunctionImpl
> >
1225 InvokeWithoutArgs(FunctionImpl function_impl
) {
1226 return MakePolymorphicAction(
1227 internal::InvokeWithoutArgsAction
<FunctionImpl
>(function_impl
));
1230 // Creates an action that invokes the given method on the given object
1231 // with no argument.
1232 template <class Class
, typename MethodPtr
>
1233 PolymorphicAction
<internal::InvokeMethodWithoutArgsAction
<Class
, MethodPtr
> >
1234 InvokeWithoutArgs(Class
* obj_ptr
, MethodPtr method_ptr
) {
1235 return MakePolymorphicAction(
1236 internal::InvokeMethodWithoutArgsAction
<Class
, MethodPtr
>(
1237 obj_ptr
, method_ptr
));
1240 // Creates an action that performs an_action and throws away its
1241 // result. In other words, it changes the return type of an_action to
1242 // void. an_action MUST NOT return void, or the code won't compile.
1243 template <typename A
>
1244 inline internal::IgnoreResultAction
<A
> IgnoreResult(const A
& an_action
) {
1245 return internal::IgnoreResultAction
<A
>(an_action
);
1248 // Creates a reference wrapper for the given L-value. If necessary,
1249 // you can explicitly specify the type of the reference. For example,
1250 // suppose 'derived' is an object of type Derived, ByRef(derived)
1251 // would wrap a Derived&. If you want to wrap a const Base& instead,
1252 // where Base is a base class of Derived, just write:
1254 // ByRef<const Base>(derived)
1255 template <typename T
>
1256 inline internal::ReferenceWrapper
<T
> ByRef(T
& l_value
) { // NOLINT
1257 return internal::ReferenceWrapper
<T
>(l_value
);
1260 } // namespace testing
1262 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_