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>
51 // To implement an action Foo, define:
52 // 1. a class FooAction that implements the ActionInterface interface, and
53 // 2. a factory function that creates an Action object from a
56 // The two-level delegation design follows that of Matcher, providing
57 // consistency for extension developers. It also eases ownership
58 // management as Action objects can now be copied like plain values.
63 class MonomorphicDoDefaultActionImpl;
65 template <typename F1, typename F2>
68 // BuiltInDefaultValue<T>::Get() returns the "built-in" default
69 // value for type T, which is NULL when T is a pointer type, 0 when T
70 // is a numeric type, false when T is bool, or "" when T is string or
71 // std::string. For any other type T, this value is undefined and the
72 // function will abort the process.
74 class BuiltInDefaultValue {
76 // This function returns true iff type T has a built-in default value.
77 static bool Exists() { return false; }
79 Assert(false, __FILE__, __LINE__,
80 "Default action undefined for the function return type.");
81 return internal::Invalid<T>();
82 // The above statement will never be reached, but is required in
83 // order for this function to compile.
87 // This partial specialization says that we use the same built-in
88 // default value for T and const T.
90 class BuiltInDefaultValue<const T> {
92 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
93 static T Get() { return BuiltInDefaultValue<T>::Get(); }
96 // This partial specialization defines the default values for pointer
99 class BuiltInDefaultValue<T*> {
101 static bool Exists() { return true; }
102 static T* Get() { return NULL; }
105 // The following specializations define the default values for
106 // specific types we care about.
107 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
109 class BuiltInDefaultValue<type> { \
111 static bool Exists() { return true; } \
112 static type Get() { return value; } \
115 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
116 #if GTEST_HAS_GLOBAL_STRING
117 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, "");
118 #endif // GTEST_HAS_GLOBAL_STRING
119 #if GTEST_HAS_STD_STRING
120 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
121 #endif // GTEST_HAS_STD_STRING
122 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
123 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
124 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
125 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
127 // signed wchar_t and unsigned wchar_t are NOT in the C++ standard.
128 // Using them is a bad practice and not portable. So don't use them.
130 // Still, Google Mock is designed to work even if the user uses signed
131 // wchar_t or unsigned wchar_t (obviously, assuming the compiler
136 // wchar_t == signed wchar_t != unsigned wchar_t == unsigned int
138 // MSVC does not recognize signed wchar_t or unsigned wchar_t. It
139 // treats wchar_t as a native type usually, but treats it as the same
140 // as unsigned short when the compiler option /Zc:wchar_t- is
143 // Therefore we provide a default action for wchar_t when compiled
144 // with gcc or _NATIVE_WCHAR_T_DEFINED is defined.
146 // There's no need for a default action for signed wchar_t, as that
147 // type is the same as wchar_t for gcc, and invalid for MSVC.
149 // There's also no need for a default action for unsigned wchar_t, as
150 // that type is the same as unsigned int for gcc, and invalid for
152 #if defined(__GNUC__) || defined(_NATIVE_WCHAR_T_DEFINED)
153 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
156 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
157 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
158 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
159 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
160 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
161 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
162 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
163 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
164 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
165 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
167 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
169 } // namespace internal
171 // When an unexpected function call is encountered, Google Mock will
172 // let it return a default value if the user has specified one for its
173 // return type, or if the return type has a built-in default value;
174 // otherwise Google Mock won't know what value to return and will have
175 // to abort the process.
177 // The DefaultValue<T> class allows a user to specify the
178 // default value for a type T that is both copyable and publicly
179 // destructible (i.e. anything that can be used as a function return
180 // type). The usage is:
182 // // Sets the default value for type T to be foo.
183 // DefaultValue<T>::Set(foo);
184 template <typename T>
187 // Sets the default value for type T; requires T to be
188 // copy-constructable and have a public destructor.
189 static void Set(T x) {
194 // Unsets the default value for type T.
195 static void Clear() {
200 // Returns true iff the user has set the default value for type T.
201 static bool IsSet() { return value_ != NULL; }
203 // Returns true if T has a default return value set by the user or there
204 // exists a built-in default value.
205 static bool Exists() {
206 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
209 // Returns the default value for type T if the user has set one;
210 // otherwise returns the built-in default value if there is one;
211 // otherwise aborts the process.
213 return value_ == NULL ?
214 internal::BuiltInDefaultValue<T>::Get() : *value_;
217 static const T* value_;
220 // This partial specialization allows a user to set default values for
222 template <typename T>
223 class DefaultValue<T&> {
225 // Sets the default value for type T&.
226 static void Set(T& x) { // NOLINT
230 // Unsets the default value for type T&.
231 static void Clear() {
235 // Returns true iff the user has set the default value for type T&.
236 static bool IsSet() { return address_ != NULL; }
238 // Returns true if T has a default return value set by the user or there
239 // exists a built-in default value.
240 static bool Exists() {
241 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
244 // Returns the default value for type T& if the user has set one;
245 // otherwise returns the built-in default value if there is one;
246 // otherwise aborts the process.
248 return address_ == NULL ?
249 internal::BuiltInDefaultValue<T&>::Get() : *address_;
255 // This specialization allows DefaultValue<void>::Get() to
258 class DefaultValue<void> {
260 static bool Exists() { return true; }
264 // Points to the user-set default value for type T.
265 template <typename T>
266 const T* DefaultValue<T>::value_ = NULL;
268 // Points to the user-set default value for type T&.
269 template <typename T>
270 T* DefaultValue<T&>::address_ = NULL;
272 // Implement this interface to define an action for function type F.
273 template <typename F>
274 class ActionInterface {
276 typedef typename internal::Function<F>::Result Result;
277 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
279 ActionInterface() : is_do_default_(false) {}
281 virtual ~ActionInterface() {}
283 // Performs the action. This method is not const, as in general an
284 // action can have side effects and be stateful. For example, a
285 // get-the-next-element-from-the-collection action will need to
286 // remember the current element.
287 virtual Result Perform(const ArgumentTuple& args) = 0;
289 // Returns true iff this is the DoDefault() action.
290 bool IsDoDefault() const { return is_do_default_; }
292 template <typename Function>
293 friend class internal::MonomorphicDoDefaultActionImpl;
295 // This private constructor is reserved for implementing
296 // DoDefault(), the default action for a given mock function.
297 explicit ActionInterface(bool is_do_default)
298 : is_do_default_(is_do_default) {}
300 // True iff this action is DoDefault().
301 const bool is_do_default_;
304 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
305 // object that represents an action to be taken when a mock function
306 // of type F is called. The implementation of Action<T> is just a
307 // linked_ptr to const ActionInterface<T>, so copying is fairly cheap.
308 // Don't inherit from Action!
310 // You can view an object implementing ActionInterface<F> as a
311 // concrete action (including its current state), and an Action<F>
312 // object as a handle to it.
313 template <typename F>
316 typedef typename internal::Function<F>::Result Result;
317 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
319 // Constructs a null Action. Needed for storing Action objects in
321 Action() : impl_(NULL) {}
323 // Constructs an Action from its implementation.
324 explicit Action(ActionInterface<F>* impl) : impl_(impl) {}
327 Action(const Action& action) : impl_(action.impl_) {}
329 // This constructor allows us to turn an Action<Func> object into an
330 // Action<F>, as long as F's arguments can be implicitly converted
331 // to Func's and Func's return type cann be implicitly converted to
333 template <typename Func>
334 explicit Action(const Action<Func>& action);
336 // Returns true iff this is the DoDefault() action.
337 bool IsDoDefault() const { return impl_->IsDoDefault(); }
339 // Performs the action. Note that this method is const even though
340 // the corresponding method in ActionInterface is not. The reason
341 // is that a const Action<F> means that it cannot be re-bound to
342 // another concrete action, not that the concrete action it binds to
343 // cannot change state. (Think of the difference between a const
344 // pointer and a pointer to const.)
345 Result Perform(const ArgumentTuple& args) const {
346 return impl_->Perform(args);
349 template <typename F1, typename F2>
350 friend class internal::ActionAdaptor;
352 internal::linked_ptr<ActionInterface<F> > impl_;
355 // The PolymorphicAction class template makes it easy to implement a
356 // polymorphic action (i.e. an action that can be used in mock
357 // functions of than one type, e.g. Return()).
359 // To define a polymorphic action, a user first provides a COPYABLE
360 // implementation class that has a Perform() method template:
364 // template <typename Result, typename ArgumentTuple>
365 // Result Perform(const ArgumentTuple& args) const {
366 // // Processes the arguments and returns a result, using
367 // // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple.
372 // Then the user creates the polymorphic action using
373 // MakePolymorphicAction(object) where object has type FooAction. See
374 // the definition of Return(void) and SetArgumentPointee<N>(value) for
375 // complete examples.
376 template <typename Impl>
377 class PolymorphicAction {
379 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
381 template <typename F>
382 operator Action<F>() const {
383 return Action<F>(new MonomorphicImpl<F>(impl_));
386 template <typename F>
387 class MonomorphicImpl : public ActionInterface<F> {
389 typedef typename internal::Function<F>::Result Result;
390 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
392 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
394 virtual Result Perform(const ArgumentTuple& args) {
395 return impl_.template Perform<Result>(args);
405 // Creates an Action from its implementation and returns it. The
406 // created Action object owns the implementation.
407 template <typename F>
408 Action<F> MakeAction(ActionInterface<F>* impl) {
409 return Action<F>(impl);
412 // Creates a polymorphic action from its implementation. This is
413 // easier to use than the PolymorphicAction<Impl> constructor as it
414 // doesn't require you to explicitly write the template argument, e.g.
416 // MakePolymorphicAction(foo);
418 // PolymorphicAction<TypeOfFoo>(foo);
419 template <typename Impl>
420 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
421 return PolymorphicAction<Impl>(impl);
426 // Allows an Action<F2> object to pose as an Action<F1>, as long as F2
427 // and F1 are compatible.
428 template <typename F1, typename F2>
429 class ActionAdaptor : public ActionInterface<F1> {
431 typedef typename internal::Function<F1>::Result Result;
432 typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple;
434 explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {}
436 virtual Result Perform(const ArgumentTuple& args) {
437 return impl_->Perform(args);
440 const internal::linked_ptr<ActionInterface<F2> > impl_;
443 // Implements the polymorphic Return(x) action, which can be used in
444 // any function that returns the type of x, regardless of the argument
446 template <typename R>
449 // Constructs a ReturnAction object from the value to be returned.
450 // 'value' is passed by value instead of by const reference in order
451 // to allow Return("string literal") to compile.
452 explicit ReturnAction(R value) : value_(value) {}
454 // This template type conversion operator allows Return(x) to be
455 // used in ANY function that returns x's type.
456 template <typename F>
457 operator Action<F>() const {
458 // Assert statement belongs here because this is the best place to verify
459 // conditions on F. It produces the clearest error messages
460 // in most compilers.
461 // Impl really belongs in this scope as a local class but can't
462 // because MSVC produces duplicate symbols in different translation units
463 // in this case. Until MS fixes that bug we put Impl into the class scope
464 // and put the typedef both here (for use in assert statement) and
465 // in the Impl class. But both definitions must be the same.
466 typedef typename Function<F>::Result Result;
467 GMOCK_COMPILE_ASSERT_(
468 !internal::is_reference<Result>::value,
469 use_ReturnRef_instead_of_Return_to_return_a_reference);
470 return Action<F>(new Impl<F>(value_));
473 // Implements the Return(x) action for a particular function type F.
474 template <typename F>
475 class Impl : public ActionInterface<F> {
477 typedef typename Function<F>::Result Result;
478 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
480 explicit Impl(R value) : value_(value) {}
482 virtual Result Perform(const ArgumentTuple&) { return value_; }
491 // Implements the ReturnNull() action.
492 class ReturnNullAction {
494 // Allows ReturnNull() to be used in any pointer-returning function.
495 template <typename Result, typename ArgumentTuple>
496 static Result Perform(const ArgumentTuple&) {
497 GMOCK_COMPILE_ASSERT_(internal::is_pointer<Result>::value,
498 ReturnNull_can_be_used_to_return_a_pointer_only);
503 // Implements the Return() action.
504 class ReturnVoidAction {
506 // Allows Return() to be used in any void-returning function.
507 template <typename Result, typename ArgumentTuple>
508 static void Perform(const ArgumentTuple&) {
509 CompileAssertTypesEqual<void, Result>();
513 // Implements the polymorphic ReturnRef(x) action, which can be used
514 // in any function that returns a reference to the type of x,
515 // regardless of the argument types.
516 template <typename T>
517 class ReturnRefAction {
519 // Constructs a ReturnRefAction object from the reference to be returned.
520 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
522 // This template type conversion operator allows ReturnRef(x) to be
523 // used in ANY function that returns a reference to x's type.
524 template <typename F>
525 operator Action<F>() const {
526 typedef typename Function<F>::Result Result;
527 // Asserts that the function return type is a reference. This
528 // catches the user error of using ReturnRef(x) when Return(x)
529 // should be used, and generates some helpful error message.
530 GMOCK_COMPILE_ASSERT_(internal::is_reference<Result>::value,
531 use_Return_instead_of_ReturnRef_to_return_a_value);
532 return Action<F>(new Impl<F>(ref_));
535 // Implements the ReturnRef(x) action for a particular function type F.
536 template <typename F>
537 class Impl : public ActionInterface<F> {
539 typedef typename Function<F>::Result Result;
540 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
542 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
544 virtual Result Perform(const ArgumentTuple&) {
554 // Implements the DoDefault() action for a particular function type F.
555 template <typename F>
556 class MonomorphicDoDefaultActionImpl : public ActionInterface<F> {
558 typedef typename Function<F>::Result Result;
559 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
561 MonomorphicDoDefaultActionImpl() : ActionInterface<F>(true) {}
563 // For technical reasons, DoDefault() cannot be used inside a
564 // composite action (e.g. DoAll(...)). It can only be used at the
565 // top level in an EXPECT_CALL(). If this function is called, the
566 // user must be using DoDefault() inside a composite action, and we
567 // have to generate a run-time error.
568 virtual Result Perform(const ArgumentTuple&) {
569 Assert(false, __FILE__, __LINE__,
570 "You are using DoDefault() inside a composite action like "
571 "DoAll() or WithArgs(). This is not supported for technical "
572 "reasons. Please instead spell out the default action, or "
573 "assign the default action to an Action variable and use "
574 "the variable in various places.");
575 return internal::Invalid<Result>();
576 // The above statement will never be reached, but is required in
577 // order for this function to compile.
581 // Implements the polymorphic DoDefault() action.
582 class DoDefaultAction {
584 // This template type conversion operator allows DoDefault() to be
585 // used in any function.
586 template <typename F>
587 operator Action<F>() const {
588 return Action<F>(new MonomorphicDoDefaultActionImpl<F>);
592 // Implements the Assign action to set a given pointer referent to a
594 template <typename T1, typename T2>
597 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
599 template <typename Result, typename ArgumentTuple>
600 void Perform(const ArgumentTuple& /* args */) const {
610 // Implements the SetErrnoAndReturn action to simulate return from
611 // various system calls and libc functions.
612 template <typename T>
613 class SetErrnoAndReturnAction {
615 SetErrnoAndReturnAction(int errno_value, T result)
616 : errno_(errno_value),
618 template <typename Result, typename ArgumentTuple>
619 Result Perform(const ArgumentTuple& /* args */) const {
630 // Implements the SetArgumentPointee<N>(x) action for any function
631 // whose N-th argument (0-based) is a pointer to x's type. The
632 // template parameter kIsProto is true iff type A is ProtocolMessage,
633 // proto2::Message, or a sub-class of those.
634 template <size_t N, typename A, bool kIsProto>
635 class SetArgumentPointeeAction {
637 // Constructs an action that sets the variable pointed to by the
638 // N-th function argument to 'value'.
639 explicit SetArgumentPointeeAction(const A& value) : value_(value) {}
641 template <typename Result, typename ArgumentTuple>
642 void Perform(const ArgumentTuple& args) const {
643 CompileAssertTypesEqual<void, Result>();
644 *::std::tr1::get<N>(args) = value_;
651 template <size_t N, typename Proto>
652 class SetArgumentPointeeAction<N, Proto, true> {
654 // Constructs an action that sets the variable pointed to by the
655 // N-th function argument to 'proto'. Both ProtocolMessage and
656 // proto2::Message have the CopyFrom() method, so the same
657 // implementation works for both.
658 explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) {
659 proto_->CopyFrom(proto);
662 template <typename Result, typename ArgumentTuple>
663 void Perform(const ArgumentTuple& args) const {
664 CompileAssertTypesEqual<void, Result>();
665 ::std::tr1::get<N>(args)->CopyFrom(*proto_);
668 const internal::linked_ptr<Proto> proto_;
671 // Implements the SetArrayArgument<N>(first, last) action for any function
672 // whose N-th argument (0-based) is a pointer or iterator to a type that can be
673 // implicitly converted from *first.
674 template <size_t N, typename InputIterator>
675 class SetArrayArgumentAction {
677 // Constructs an action that sets the variable pointed to by the
678 // N-th function argument to 'value'.
679 explicit SetArrayArgumentAction(InputIterator first, InputIterator last)
680 : first_(first), last_(last) {
683 template <typename Result, typename ArgumentTuple>
684 void Perform(const ArgumentTuple& args) const {
685 CompileAssertTypesEqual<void, Result>();
687 // Microsoft compiler deprecates ::std::copy, so we want to suppress warning
688 // 4996 (Function call with parameters that may be unsafe) there.
690 #pragma warning(push) // Saves the current warning state.
691 #pragma warning(disable:4996) // Temporarily disables warning 4996.
692 #endif // GTEST_OS_WINDOWS
693 ::std::copy(first_, last_, ::std::tr1::get<N>(args));
695 #pragma warning(pop) // Restores the warning state.
696 #endif // GTEST_OS_WINDOWS
700 const InputIterator first_;
701 const InputIterator last_;
704 // Implements the InvokeWithoutArgs(f) action. The template argument
705 // FunctionImpl is the implementation type of f, which can be either a
706 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
707 // Action<F> as long as f's type is compatible with F (i.e. f can be
708 // assigned to a tr1::function<F>).
709 template <typename FunctionImpl>
710 class InvokeWithoutArgsAction {
712 // The c'tor makes a copy of function_impl (either a function
713 // pointer or a functor).
714 explicit InvokeWithoutArgsAction(FunctionImpl function_impl)
715 : function_impl_(function_impl) {}
717 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
718 // compatible with f.
719 template <typename Result, typename ArgumentTuple>
720 Result Perform(const ArgumentTuple&) { return function_impl_(); }
722 FunctionImpl function_impl_;
725 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
726 template <class Class, typename MethodPtr>
727 class InvokeMethodWithoutArgsAction {
729 InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr)
730 : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {}
732 template <typename Result, typename ArgumentTuple>
733 Result Perform(const ArgumentTuple&) const {
734 return (obj_ptr_->*method_ptr_)();
737 Class* const obj_ptr_;
738 const MethodPtr method_ptr_;
741 // Implements the IgnoreResult(action) action.
742 template <typename A>
743 class IgnoreResultAction {
745 explicit IgnoreResultAction(const A& action) : action_(action) {}
747 template <typename F>
748 operator Action<F>() const {
749 // Assert statement belongs here because this is the best place to verify
750 // conditions on F. It produces the clearest error messages
751 // in most compilers.
752 // Impl really belongs in this scope as a local class but can't
753 // because MSVC produces duplicate symbols in different translation units
754 // in this case. Until MS fixes that bug we put Impl into the class scope
755 // and put the typedef both here (for use in assert statement) and
756 // in the Impl class. But both definitions must be the same.
757 typedef typename internal::Function<F>::Result Result;
759 // Asserts at compile time that F returns void.
760 CompileAssertTypesEqual<void, Result>();
762 return Action<F>(new Impl<F>(action_));
765 template <typename F>
766 class Impl : public ActionInterface<F> {
768 typedef typename internal::Function<F>::Result Result;
769 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
771 explicit Impl(const A& action) : action_(action) {}
773 virtual void Perform(const ArgumentTuple& args) {
774 // Performs the action and ignores its result.
775 action_.Perform(args);
779 // Type OriginalFunction is the same as F except that its return
780 // type is IgnoredValue.
781 typedef typename internal::Function<F>::MakeResultIgnoredValue
784 const Action<OriginalFunction> action_;
790 } // namespace internal
792 // An Unused object can be implicitly constructed from ANY value.
793 // This is handy when defining actions that ignore some or all of the
794 // mock function arguments. For example, given
796 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
797 // MOCK_METHOD3(Bar, double(int index, double x, double y));
801 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
802 // return sqrt(x*x + y*y);
804 // double DistanceToOriginWithIndex(int index, double x, double y) {
805 // return sqrt(x*x + y*y);
808 // EXEPCT_CALL(mock, Foo("abc", _, _))
809 // .WillOnce(Invoke(DistanceToOriginWithLabel));
810 // EXEPCT_CALL(mock, Bar(5, _, _))
811 // .WillOnce(Invoke(DistanceToOriginWithIndex));
815 // // We can declare any uninteresting argument as Unused.
816 // double DistanceToOrigin(Unused, double x, double y) {
817 // return sqrt(x*x + y*y);
820 // EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
821 // EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
822 typedef internal::IgnoredValue Unused;
824 // This constructor allows us to turn an Action<From> object into an
825 // Action<To>, as long as To's arguments can be implicitly converted
826 // to From's and From's return type cann be implicitly converted to
828 template <typename To>
829 template <typename From>
830 Action<To>::Action(const Action<From>& from)
831 : impl_(new internal::ActionAdaptor<To, From>(from)) {}
833 // Creates an action that returns 'value'. 'value' is passed by value
834 // instead of const reference - otherwise Return("string literal")
835 // will trigger a compiler error about using array as initializer.
836 template <typename R>
837 internal::ReturnAction<R> Return(R value) {
838 return internal::ReturnAction<R>(value);
841 // Creates an action that returns NULL.
842 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
843 return MakePolymorphicAction(internal::ReturnNullAction());
846 // Creates an action that returns from a void function.
847 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
848 return MakePolymorphicAction(internal::ReturnVoidAction());
851 // Creates an action that returns the reference to a variable.
852 template <typename R>
853 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
854 return internal::ReturnRefAction<R>(x);
857 // Creates an action that does the default action for the give mock function.
858 inline internal::DoDefaultAction DoDefault() {
859 return internal::DoDefaultAction();
862 // Creates an action that sets the variable pointed by the N-th
863 // (0-based) function argument to 'value'.
864 template <size_t N, typename T>
866 internal::SetArgumentPointeeAction<
867 N, T, internal::IsAProtocolMessage<T>::value> >
868 SetArgumentPointee(const T& x) {
869 return MakePolymorphicAction(internal::SetArgumentPointeeAction<
870 N, T, internal::IsAProtocolMessage<T>::value>(x));
873 // Creates an action that sets the elements of the array pointed to by the N-th
874 // (0-based) function argument, which can be either a pointer or an iterator,
875 // to the values of the elements in the source range [first, last).
876 template <size_t N, typename InputIterator>
877 PolymorphicAction<internal::SetArrayArgumentAction<N, InputIterator> >
878 SetArrayArgument(InputIterator first, InputIterator last) {
879 return MakePolymorphicAction(internal::SetArrayArgumentAction<
880 N, InputIterator>(first, last));
883 // Creates an action that sets a pointer referent to a given value.
884 template <typename T1, typename T2>
885 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
886 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
891 // Creates an action that sets errno and returns the appropriate error.
892 template <typename T>
893 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
894 SetErrnoAndReturn(int errval, T result) {
895 return MakePolymorphicAction(
896 internal::SetErrnoAndReturnAction<T>(errval, result));
901 // Various overloads for InvokeWithoutArgs().
903 // Creates an action that invokes 'function_impl' with no argument.
904 template <typename FunctionImpl>
905 PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> >
906 InvokeWithoutArgs(FunctionImpl function_impl) {
907 return MakePolymorphicAction(
908 internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl));
911 // Creates an action that invokes the given method on the given object
913 template <class Class, typename MethodPtr>
914 PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> >
915 InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) {
916 return MakePolymorphicAction(
917 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>(
918 obj_ptr, method_ptr));
921 // Creates an action that performs an_action and throws away its
922 // result. In other words, it changes the return type of an_action to
923 // void. an_action MUST NOT return void, or the code won't compile.
924 template <typename A>
925 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
926 return internal::IgnoreResultAction<A>(an_action);
929 } // namespace testing
931 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_