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 some commonly used actions.
35 // GOOGLETEST_CM0002 DO NOT DELETE
37 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
38 #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
48 #include <type_traits>
51 #include "gmock/internal/gmock-internal-utils.h"
52 #include "gmock/internal/gmock-port.h"
55 # pragma warning(push)
56 # pragma warning(disable:4100)
61 // To implement an action Foo, define:
62 // 1. a class FooAction that implements the ActionInterface interface, and
63 // 2. a factory function that creates an Action object from a
66 // The two-level delegation design follows that of Matcher, providing
67 // consistency for extension developers. It also eases ownership
68 // management as Action objects can now be copied like plain values.
72 // BuiltInDefaultValueGetter<T, true>::Get() returns a
73 // default-constructed T value. BuiltInDefaultValueGetter<T,
74 // false>::Get() crashes with an error.
76 // This primary template is used when kDefaultConstructible is true.
77 template <typename T, bool kDefaultConstructible>
78 struct BuiltInDefaultValueGetter {
79 static T Get() { return T(); }
82 struct BuiltInDefaultValueGetter<T, false> {
84 Assert(false, __FILE__, __LINE__,
85 "Default action undefined for the function return type.");
86 return internal::Invalid<T>();
87 // The above statement will never be reached, but is required in
88 // order for this function to compile.
92 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
93 // for type T, which is NULL when T is a raw pointer type, 0 when T is
94 // a numeric type, false when T is bool, or "" when T is string or
95 // std::string. In addition, in C++11 and above, it turns a
96 // default-constructed T value if T is default constructible. For any
97 // other type T, the built-in default T value is undefined, and the
98 // function will abort the process.
100 class BuiltInDefaultValue {
102 // This function returns true if and only if type T has a built-in default
104 static bool Exists() {
105 return ::std::is_default_constructible<T>::value;
109 return BuiltInDefaultValueGetter<
110 T, ::std::is_default_constructible<T>::value>::Get();
114 // This partial specialization says that we use the same built-in
115 // default value for T and const T.
116 template <typename T>
117 class BuiltInDefaultValue<const T> {
119 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
120 static T Get() { return BuiltInDefaultValue<T>::Get(); }
123 // This partial specialization defines the default values for pointer
125 template <typename T>
126 class BuiltInDefaultValue<T*> {
128 static bool Exists() { return true; }
129 static T* Get() { return nullptr; }
132 // The following specializations define the default values for
133 // specific types we care about.
134 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
136 class BuiltInDefaultValue<type> { \
138 static bool Exists() { return true; } \
139 static type Get() { return value; } \
142 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
143 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
144 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
145 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
146 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
147 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
149 // There's no need for a default action for signed wchar_t, as that
150 // type is the same as wchar_t for gcc, and invalid for MSVC.
152 // There's also no need for a default action for unsigned wchar_t, as
153 // that type is the same as unsigned int for gcc, and invalid for
155 #if GMOCK_WCHAR_T_IS_NATIVE_
156 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
159 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
160 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
161 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
162 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
163 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
164 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
165 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0);
166 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0);
167 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
168 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
170 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
172 } // namespace internal
174 // When an unexpected function call is encountered, Google Mock will
175 // let it return a default value if the user has specified one for its
176 // return type, or if the return type has a built-in default value;
177 // otherwise Google Mock won't know what value to return and will have
178 // to abort the process.
180 // The DefaultValue<T> class allows a user to specify the
181 // default value for a type T that is both copyable and publicly
182 // destructible (i.e. anything that can be used as a function return
183 // type). The usage is:
185 // // Sets the default value for type T to be foo.
186 // DefaultValue<T>::Set(foo);
187 template <typename T>
190 // Sets the default value for type T; requires T to be
191 // copy-constructable and have a public destructor.
192 static void Set(T x) {
194 producer_ = new FixedValueProducer(x);
197 // Provides a factory function to be called to generate the default value.
198 // This method can be used even if T is only move-constructible, but it is not
199 // limited to that case.
200 typedef T (*FactoryFunction)();
201 static void SetFactory(FactoryFunction factory) {
203 producer_ = new FactoryValueProducer(factory);
206 // Unsets the default value for type T.
207 static void Clear() {
212 // Returns true if and only if the user has set the default value for type T.
213 static bool IsSet() { return producer_ != nullptr; }
215 // Returns true if T has a default return value set by the user or there
216 // exists a built-in default value.
217 static bool Exists() {
218 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
221 // Returns the default value for type T if the user has set one;
222 // otherwise returns the built-in default value. Requires that Exists()
223 // is true, which ensures that the return value is well-defined.
225 return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
226 : producer_->Produce();
230 class ValueProducer {
232 virtual ~ValueProducer() {}
233 virtual T Produce() = 0;
236 class FixedValueProducer : public ValueProducer {
238 explicit FixedValueProducer(T value) : value_(value) {}
239 T Produce() override { return value_; }
243 GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer);
246 class FactoryValueProducer : public ValueProducer {
248 explicit FactoryValueProducer(FactoryFunction factory)
249 : factory_(factory) {}
250 T Produce() override { return factory_(); }
253 const FactoryFunction factory_;
254 GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer);
257 static ValueProducer* producer_;
260 // This partial specialization allows a user to set default values for
262 template <typename T>
263 class DefaultValue<T&> {
265 // Sets the default value for type T&.
266 static void Set(T& x) { // NOLINT
270 // Unsets the default value for type T&.
271 static void Clear() { address_ = nullptr; }
273 // Returns true if and only if the user has set the default value for type T&.
274 static bool IsSet() { return address_ != nullptr; }
276 // Returns true if T has a default return value set by the user or there
277 // exists a built-in default value.
278 static bool Exists() {
279 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
282 // Returns the default value for type T& if the user has set one;
283 // otherwise returns the built-in default value if there is one;
284 // otherwise aborts the process.
286 return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
294 // This specialization allows DefaultValue<void>::Get() to
297 class DefaultValue<void> {
299 static bool Exists() { return true; }
303 // Points to the user-set default value for type T.
304 template <typename T>
305 typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
307 // Points to the user-set default value for type T&.
308 template <typename T>
309 T* DefaultValue<T&>::address_ = nullptr;
311 // Implement this interface to define an action for function type F.
312 template <typename F>
313 class ActionInterface {
315 typedef typename internal::Function<F>::Result Result;
316 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
319 virtual ~ActionInterface() {}
321 // Performs the action. This method is not const, as in general an
322 // action can have side effects and be stateful. For example, a
323 // get-the-next-element-from-the-collection action will need to
324 // remember the current element.
325 virtual Result Perform(const ArgumentTuple& args) = 0;
328 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface);
331 // An Action<F> is a copyable and IMMUTABLE (except by assignment)
332 // object that represents an action to be taken when a mock function
333 // of type F is called. The implementation of Action<T> is just a
334 // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action!
335 // You can view an object implementing ActionInterface<F> as a
336 // concrete action (including its current state), and an Action<F>
337 // object as a handle to it.
338 template <typename F>
340 // Adapter class to allow constructing Action from a legacy ActionInterface.
341 // New code should create Actions from functors instead.
342 struct ActionAdapter {
343 // Adapter must be copyable to satisfy std::function requirements.
344 ::std::shared_ptr<ActionInterface<F>> impl_;
346 template <typename... Args>
347 typename internal::Function<F>::Result operator()(Args&&... args) {
348 return impl_->Perform(
349 ::std::forward_as_tuple(::std::forward<Args>(args)...));
354 typedef typename internal::Function<F>::Result Result;
355 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
357 // Constructs a null Action. Needed for storing Action objects in
361 // Construct an Action from a specified callable.
362 // This cannot take std::function directly, because then Action would not be
363 // directly constructible from lambda (it would require two conversions).
364 template <typename G,
365 typename = typename ::std::enable_if<
366 ::std::is_constructible<::std::function<F>, G>::value>::type>
367 Action(G&& fun) : fun_(::std::forward<G>(fun)) {} // NOLINT
369 // Constructs an Action from its implementation.
370 explicit Action(ActionInterface<F>* impl)
371 : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
373 // This constructor allows us to turn an Action<Func> object into an
374 // Action<F>, as long as F's arguments can be implicitly converted
375 // to Func's and Func's return type can be implicitly converted to F's.
376 template <typename Func>
377 explicit Action(const Action<Func>& action) : fun_(action.fun_) {}
379 // Returns true if and only if this is the DoDefault() action.
380 bool IsDoDefault() const { return fun_ == nullptr; }
382 // Performs the action. Note that this method is const even though
383 // the corresponding method in ActionInterface is not. The reason
384 // is that a const Action<F> means that it cannot be re-bound to
385 // another concrete action, not that the concrete action it binds to
386 // cannot change state. (Think of the difference between a const
387 // pointer and a pointer to const.)
388 Result Perform(ArgumentTuple args) const {
390 internal::IllegalDoDefault(__FILE__, __LINE__);
392 return internal::Apply(fun_, ::std::move(args));
396 template <typename G>
399 // fun_ is an empty function if and only if this is the DoDefault() action.
400 ::std::function<F> fun_;
403 // The PolymorphicAction class template makes it easy to implement a
404 // polymorphic action (i.e. an action that can be used in mock
405 // functions of than one type, e.g. Return()).
407 // To define a polymorphic action, a user first provides a COPYABLE
408 // implementation class that has a Perform() method template:
412 // template <typename Result, typename ArgumentTuple>
413 // Result Perform(const ArgumentTuple& args) const {
414 // // Processes the arguments and returns a result, using
415 // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
420 // Then the user creates the polymorphic action using
421 // MakePolymorphicAction(object) where object has type FooAction. See
422 // the definition of Return(void) and SetArgumentPointee<N>(value) for
423 // complete examples.
424 template <typename Impl>
425 class PolymorphicAction {
427 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
429 template <typename F>
430 operator Action<F>() const {
431 return Action<F>(new MonomorphicImpl<F>(impl_));
435 template <typename F>
436 class MonomorphicImpl : public ActionInterface<F> {
438 typedef typename internal::Function<F>::Result Result;
439 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
441 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
443 Result Perform(const ArgumentTuple& args) override {
444 return impl_.template Perform<Result>(args);
450 GTEST_DISALLOW_ASSIGN_(MonomorphicImpl);
455 GTEST_DISALLOW_ASSIGN_(PolymorphicAction);
458 // Creates an Action from its implementation and returns it. The
459 // created Action object owns the implementation.
460 template <typename F>
461 Action<F> MakeAction(ActionInterface<F>* impl) {
462 return Action<F>(impl);
465 // Creates a polymorphic action from its implementation. This is
466 // easier to use than the PolymorphicAction<Impl> constructor as it
467 // doesn't require you to explicitly write the template argument, e.g.
469 // MakePolymorphicAction(foo);
471 // PolymorphicAction<TypeOfFoo>(foo);
472 template <typename Impl>
473 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
474 return PolymorphicAction<Impl>(impl);
479 // Helper struct to specialize ReturnAction to execute a move instead of a copy
480 // on return. Useful for move-only types, but could be used on any type.
481 template <typename T>
482 struct ByMoveWrapper {
483 explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
487 // Implements the polymorphic Return(x) action, which can be used in
488 // any function that returns the type of x, regardless of the argument
491 // Note: The value passed into Return must be converted into
492 // Function<F>::Result when this action is cast to Action<F> rather than
493 // when that action is performed. This is important in scenarios like
495 // MOCK_METHOD1(Method, T(U));
500 // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x));
503 // In the example above the variable x holds reference to foo which leaves
504 // scope and gets destroyed. If copying X just copies a reference to foo,
505 // that copy will be left with a hanging reference. If conversion to T
506 // makes a copy of foo, the above code is safe. To support that scenario, we
507 // need to make sure that the type conversion happens inside the EXPECT_CALL
508 // statement, and conversion of the result of Return to Action<T(U)> is a
509 // good place for that.
511 // The real life example of the above scenario happens when an invocation
512 // of gtl::Container() is passed into Return.
514 template <typename R>
517 // Constructs a ReturnAction object from the value to be returned.
518 // 'value' is passed by value instead of by const reference in order
519 // to allow Return("string literal") to compile.
520 explicit ReturnAction(R value) : value_(new R(std::move(value))) {}
522 // This template type conversion operator allows Return(x) to be
523 // used in ANY function that returns x's type.
524 template <typename F>
525 operator Action<F>() const { // NOLINT
526 // Assert statement belongs here because this is the best place to verify
527 // conditions on F. It produces the clearest error messages
528 // in most compilers.
529 // Impl really belongs in this scope as a local class but can't
530 // because MSVC produces duplicate symbols in different translation units
531 // in this case. Until MS fixes that bug we put Impl into the class scope
532 // and put the typedef both here (for use in assert statement) and
533 // in the Impl class. But both definitions must be the same.
534 typedef typename Function<F>::Result Result;
535 GTEST_COMPILE_ASSERT_(
536 !std::is_reference<Result>::value,
537 use_ReturnRef_instead_of_Return_to_return_a_reference);
538 static_assert(!std::is_void<Result>::value,
539 "Can't use Return() on an action expected to return `void`.");
540 return Action<F>(new Impl<R, F>(value_));
544 // Implements the Return(x) action for a particular function type F.
545 template <typename R_, typename F>
546 class Impl : public ActionInterface<F> {
548 typedef typename Function<F>::Result Result;
549 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
551 // The implicit cast is necessary when Result has more than one
552 // single-argument constructor (e.g. Result is std::vector<int>) and R
553 // has a type conversion operator template. In that case, value_(value)
554 // won't compile as the compiler doesn't known which constructor of
555 // Result to call. ImplicitCast_ forces the compiler to convert R to
556 // Result without considering explicit constructors, thus resolving the
557 // ambiguity. value_ is then initialized using its copy constructor.
558 explicit Impl(const std::shared_ptr<R>& value)
559 : value_before_cast_(*value),
560 value_(ImplicitCast_<Result>(value_before_cast_)) {}
562 Result Perform(const ArgumentTuple&) override { return value_; }
565 GTEST_COMPILE_ASSERT_(!std::is_reference<Result>::value,
566 Result_cannot_be_a_reference_type);
567 // We save the value before casting just in case it is being cast to a
569 R value_before_cast_;
572 GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl);
575 // Partially specialize for ByMoveWrapper. This version of ReturnAction will
576 // move its contents instead.
577 template <typename R_, typename F>
578 class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> {
580 typedef typename Function<F>::Result Result;
581 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
583 explicit Impl(const std::shared_ptr<R>& wrapper)
584 : performed_(false), wrapper_(wrapper) {}
586 Result Perform(const ArgumentTuple&) override {
587 GTEST_CHECK_(!performed_)
588 << "A ByMove() action should only be performed once.";
590 return std::move(wrapper_->payload);
595 const std::shared_ptr<R> wrapper_;
597 GTEST_DISALLOW_ASSIGN_(Impl);
600 const std::shared_ptr<R> value_;
602 GTEST_DISALLOW_ASSIGN_(ReturnAction);
605 // Implements the ReturnNull() action.
606 class ReturnNullAction {
608 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
609 // this is enforced by returning nullptr, and in non-C++11 by asserting a
610 // pointer type on compile time.
611 template <typename Result, typename ArgumentTuple>
612 static Result Perform(const ArgumentTuple&) {
617 // Implements the Return() action.
618 class ReturnVoidAction {
620 // Allows Return() to be used in any void-returning function.
621 template <typename Result, typename ArgumentTuple>
622 static void Perform(const ArgumentTuple&) {
623 static_assert(std::is_void<Result>::value, "Result should be void.");
627 // Implements the polymorphic ReturnRef(x) action, which can be used
628 // in any function that returns a reference to the type of x,
629 // regardless of the argument types.
630 template <typename T>
631 class ReturnRefAction {
633 // Constructs a ReturnRefAction object from the reference to be returned.
634 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
636 // This template type conversion operator allows ReturnRef(x) to be
637 // used in ANY function that returns a reference to x's type.
638 template <typename F>
639 operator Action<F>() const {
640 typedef typename Function<F>::Result Result;
641 // Asserts that the function return type is a reference. This
642 // catches the user error of using ReturnRef(x) when Return(x)
643 // should be used, and generates some helpful error message.
644 GTEST_COMPILE_ASSERT_(std::is_reference<Result>::value,
645 use_Return_instead_of_ReturnRef_to_return_a_value);
646 return Action<F>(new Impl<F>(ref_));
650 // Implements the ReturnRef(x) action for a particular function type F.
651 template <typename F>
652 class Impl : public ActionInterface<F> {
654 typedef typename Function<F>::Result Result;
655 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
657 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
659 Result Perform(const ArgumentTuple&) override { return ref_; }
664 GTEST_DISALLOW_ASSIGN_(Impl);
669 GTEST_DISALLOW_ASSIGN_(ReturnRefAction);
672 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
673 // used in any function that returns a reference to the type of x,
674 // regardless of the argument types.
675 template <typename T>
676 class ReturnRefOfCopyAction {
678 // Constructs a ReturnRefOfCopyAction object from the reference to
680 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
682 // This template type conversion operator allows ReturnRefOfCopy(x) to be
683 // used in ANY function that returns a reference to x's type.
684 template <typename F>
685 operator Action<F>() const {
686 typedef typename Function<F>::Result Result;
687 // Asserts that the function return type is a reference. This
688 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
689 // should be used, and generates some helpful error message.
690 GTEST_COMPILE_ASSERT_(
691 std::is_reference<Result>::value,
692 use_Return_instead_of_ReturnRefOfCopy_to_return_a_value);
693 return Action<F>(new Impl<F>(value_));
697 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
698 template <typename F>
699 class Impl : public ActionInterface<F> {
701 typedef typename Function<F>::Result Result;
702 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
704 explicit Impl(const T& value) : value_(value) {} // NOLINT
706 Result Perform(const ArgumentTuple&) override { return value_; }
711 GTEST_DISALLOW_ASSIGN_(Impl);
716 GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction);
719 // Implements the polymorphic DoDefault() action.
720 class DoDefaultAction {
722 // This template type conversion operator allows DoDefault() to be
723 // used in any function.
724 template <typename F>
725 operator Action<F>() const { return Action<F>(); } // NOLINT
728 // Implements the Assign action to set a given pointer referent to a
730 template <typename T1, typename T2>
733 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
735 template <typename Result, typename ArgumentTuple>
736 void Perform(const ArgumentTuple& /* args */) const {
744 GTEST_DISALLOW_ASSIGN_(AssignAction);
747 #if !GTEST_OS_WINDOWS_MOBILE
749 // Implements the SetErrnoAndReturn action to simulate return from
750 // various system calls and libc functions.
751 template <typename T>
752 class SetErrnoAndReturnAction {
754 SetErrnoAndReturnAction(int errno_value, T result)
755 : errno_(errno_value),
757 template <typename Result, typename ArgumentTuple>
758 Result Perform(const ArgumentTuple& /* args */) const {
767 GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction);
770 #endif // !GTEST_OS_WINDOWS_MOBILE
772 // Implements the SetArgumentPointee<N>(x) action for any function
773 // whose N-th argument (0-based) is a pointer to x's type.
774 template <size_t N, typename A, typename = void>
775 struct SetArgumentPointeeAction {
778 template <typename... Args>
779 void operator()(const Args&... args) const {
780 *::std::get<N>(std::tie(args...)) = value;
784 // Implements the Invoke(object_ptr, &Class::Method) action.
785 template <class Class, typename MethodPtr>
786 struct InvokeMethodAction {
787 Class* const obj_ptr;
788 const MethodPtr method_ptr;
790 template <typename... Args>
791 auto operator()(Args&&... args) const
792 -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
793 return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
797 // Implements the InvokeWithoutArgs(f) action. The template argument
798 // FunctionImpl is the implementation type of f, which can be either a
799 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
800 // Action<F> as long as f's type is compatible with F.
801 template <typename FunctionImpl>
802 struct InvokeWithoutArgsAction {
803 FunctionImpl function_impl;
805 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
806 // compatible with f.
807 template <typename... Args>
808 auto operator()(const Args&...) -> decltype(function_impl()) {
809 return function_impl();
813 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
814 template <class Class, typename MethodPtr>
815 struct InvokeMethodWithoutArgsAction {
816 Class* const obj_ptr;
817 const MethodPtr method_ptr;
819 using ReturnType = typename std::result_of<MethodPtr(Class*)>::type;
821 template <typename... Args>
822 ReturnType operator()(const Args&...) const {
823 return (obj_ptr->*method_ptr)();
827 // Implements the IgnoreResult(action) action.
828 template <typename A>
829 class IgnoreResultAction {
831 explicit IgnoreResultAction(const A& action) : action_(action) {}
833 template <typename F>
834 operator Action<F>() const {
835 // Assert statement belongs here because this is the best place to verify
836 // conditions on F. It produces the clearest error messages
837 // in most compilers.
838 // Impl really belongs in this scope as a local class but can't
839 // because MSVC produces duplicate symbols in different translation units
840 // in this case. Until MS fixes that bug we put Impl into the class scope
841 // and put the typedef both here (for use in assert statement) and
842 // in the Impl class. But both definitions must be the same.
843 typedef typename internal::Function<F>::Result Result;
845 // Asserts at compile time that F returns void.
846 static_assert(std::is_void<Result>::value, "Result type should be void.");
848 return Action<F>(new Impl<F>(action_));
852 template <typename F>
853 class Impl : public ActionInterface<F> {
855 typedef typename internal::Function<F>::Result Result;
856 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
858 explicit Impl(const A& action) : action_(action) {}
860 void Perform(const ArgumentTuple& args) override {
861 // Performs the action and ignores its result.
862 action_.Perform(args);
866 // Type OriginalFunction is the same as F except that its return
867 // type is IgnoredValue.
868 typedef typename internal::Function<F>::MakeResultIgnoredValue
871 const Action<OriginalFunction> action_;
873 GTEST_DISALLOW_ASSIGN_(Impl);
878 GTEST_DISALLOW_ASSIGN_(IgnoreResultAction);
881 template <typename InnerAction, size_t... I>
882 struct WithArgsAction {
885 // The inner action could be anything convertible to Action<X>.
886 // We use the conversion operator to detect the signature of the inner Action.
887 template <typename R, typename... Args>
888 operator Action<R(Args...)>() const { // NOLINT
889 Action<R(typename std::tuple_element<I, std::tuple<Args...>>::type...)>
892 return [converted](Args... args) -> R {
893 return converted.Perform(std::forward_as_tuple(
894 std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
899 template <typename... Actions>
902 template <typename... Args, size_t... I>
903 std::vector<Action<void(Args...)>> Convert(IndexSequence<I...>) const {
904 return {std::get<I>(actions)...};
908 std::tuple<Actions...> actions;
910 template <typename R, typename... Args>
911 operator Action<R(Args...)>() const { // NOLINT
913 std::vector<Action<void(Args...)>> converted;
914 Action<R(Args...)> last;
915 R operator()(Args... args) const {
916 auto tuple_args = std::forward_as_tuple(std::forward<Args>(args)...);
917 for (auto& a : converted) {
918 a.Perform(tuple_args);
920 return last.Perform(tuple_args);
923 return Op{Convert<Args...>(MakeIndexSequence<sizeof...(Actions) - 1>()),
924 std::get<sizeof...(Actions) - 1>(actions)};
928 } // namespace internal
930 // An Unused object can be implicitly constructed from ANY value.
931 // This is handy when defining actions that ignore some or all of the
932 // mock function arguments. For example, given
934 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
935 // MOCK_METHOD3(Bar, double(int index, double x, double y));
939 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
940 // return sqrt(x*x + y*y);
942 // double DistanceToOriginWithIndex(int index, double x, double y) {
943 // return sqrt(x*x + y*y);
946 // EXPECT_CALL(mock, Foo("abc", _, _))
947 // .WillOnce(Invoke(DistanceToOriginWithLabel));
948 // EXPECT_CALL(mock, Bar(5, _, _))
949 // .WillOnce(Invoke(DistanceToOriginWithIndex));
953 // // We can declare any uninteresting argument as Unused.
954 // double DistanceToOrigin(Unused, double x, double y) {
955 // return sqrt(x*x + y*y);
958 // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
959 // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
960 typedef internal::IgnoredValue Unused;
962 // Creates an action that does actions a1, a2, ..., sequentially in
964 template <typename... Action>
965 internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
966 Action&&... action) {
967 return {std::forward_as_tuple(std::forward<Action>(action)...)};
970 // WithArg<k>(an_action) creates an action that passes the k-th
971 // (0-based) argument of the mock function to an_action and performs
972 // it. It adapts an action accepting one argument to one that accepts
973 // multiple arguments. For convenience, we also provide
974 // WithArgs<k>(an_action) (defined below) as a synonym.
975 template <size_t k, typename InnerAction>
976 internal::WithArgsAction<typename std::decay<InnerAction>::type, k>
977 WithArg(InnerAction&& action) {
978 return {std::forward<InnerAction>(action)};
981 // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
982 // the selected arguments of the mock function to an_action and
983 // performs it. It serves as an adaptor between actions with
984 // different argument lists.
985 template <size_t k, size_t... ks, typename InnerAction>
986 internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
987 WithArgs(InnerAction&& action) {
988 return {std::forward<InnerAction>(action)};
991 // WithoutArgs(inner_action) can be used in a mock function with a
992 // non-empty argument list to perform inner_action, which takes no
993 // argument. In other words, it adapts an action accepting no
994 // argument to one that accepts (and ignores) arguments.
995 template <typename InnerAction>
996 internal::WithArgsAction<typename std::decay<InnerAction>::type>
997 WithoutArgs(InnerAction&& action) {
998 return {std::forward<InnerAction>(action)};
1001 // Creates an action that returns 'value'. 'value' is passed by value
1002 // instead of const reference - otherwise Return("string literal")
1003 // will trigger a compiler error about using array as initializer.
1004 template <typename R>
1005 internal::ReturnAction<R> Return(R value) {
1006 return internal::ReturnAction<R>(std::move(value));
1009 // Creates an action that returns NULL.
1010 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1011 return MakePolymorphicAction(internal::ReturnNullAction());
1014 // Creates an action that returns from a void function.
1015 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1016 return MakePolymorphicAction(internal::ReturnVoidAction());
1019 // Creates an action that returns the reference to a variable.
1020 template <typename R>
1021 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
1022 return internal::ReturnRefAction<R>(x);
1025 // Creates an action that returns the reference to a copy of the
1026 // argument. The copy is created when the action is constructed and
1027 // lives as long as the action.
1028 template <typename R>
1029 inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1030 return internal::ReturnRefOfCopyAction<R>(x);
1033 // Modifies the parent action (a Return() action) to perform a move of the
1034 // argument instead of a copy.
1035 // Return(ByMove()) actions can only be executed once and will assert this
1037 template <typename R>
1038 internal::ByMoveWrapper<R> ByMove(R x) {
1039 return internal::ByMoveWrapper<R>(std::move(x));
1042 // Creates an action that does the default action for the give mock function.
1043 inline internal::DoDefaultAction DoDefault() {
1044 return internal::DoDefaultAction();
1047 // Creates an action that sets the variable pointed by the N-th
1048 // (0-based) function argument to 'value'.
1049 template <size_t N, typename T>
1050 internal::SetArgumentPointeeAction<N, T> SetArgPointee(T x) {
1051 return {std::move(x)};
1054 // The following version is DEPRECATED.
1055 template <size_t N, typename T>
1056 internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T x) {
1057 return {std::move(x)};
1060 // Creates an action that sets a pointer referent to a given value.
1061 template <typename T1, typename T2>
1062 PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) {
1063 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1066 #if !GTEST_OS_WINDOWS_MOBILE
1068 // Creates an action that sets errno and returns the appropriate error.
1069 template <typename T>
1070 PolymorphicAction<internal::SetErrnoAndReturnAction<T> >
1071 SetErrnoAndReturn(int errval, T result) {
1072 return MakePolymorphicAction(
1073 internal::SetErrnoAndReturnAction<T>(errval, result));
1076 #endif // !GTEST_OS_WINDOWS_MOBILE
1078 // Various overloads for Invoke().
1081 // Actions can now be implicitly constructed from callables. No need to create
1083 // This function exists for backwards compatibility.
1084 template <typename FunctionImpl>
1085 typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
1086 return std::forward<FunctionImpl>(function_impl);
1089 // Creates an action that invokes the given method on the given object
1090 // with the mock function's arguments.
1091 template <class Class, typename MethodPtr>
1092 internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
1093 MethodPtr method_ptr) {
1094 return {obj_ptr, method_ptr};
1097 // Creates an action that invokes 'function_impl' with no argument.
1098 template <typename FunctionImpl>
1099 internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
1100 InvokeWithoutArgs(FunctionImpl function_impl) {
1101 return {std::move(function_impl)};
1104 // Creates an action that invokes the given method on the given object
1105 // with no argument.
1106 template <class Class, typename MethodPtr>
1107 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
1108 Class* obj_ptr, MethodPtr method_ptr) {
1109 return {obj_ptr, method_ptr};
1112 // Creates an action that performs an_action and throws away its
1113 // result. In other words, it changes the return type of an_action to
1114 // void. an_action MUST NOT return void, or the code won't compile.
1115 template <typename A>
1116 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1117 return internal::IgnoreResultAction<A>(an_action);
1120 // Creates a reference wrapper for the given L-value. If necessary,
1121 // you can explicitly specify the type of the reference. For example,
1122 // suppose 'derived' is an object of type Derived, ByRef(derived)
1123 // would wrap a Derived&. If you want to wrap a const Base& instead,
1124 // where Base is a base class of Derived, just write:
1126 // ByRef<const Base>(derived)
1128 // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
1129 // However, it may still be used for consistency with ByMove().
1130 template <typename T>
1131 inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
1132 return ::std::reference_wrapper<T>(l_value);
1135 } // namespace testing
1138 # pragma warning(pop)
1142 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_