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 // Google Mock - a framework for writing C++ mock classes.
32 // The ACTION* family of macros can be used in a namespace scope to
33 // define custom actions easily. The syntax:
35 // ACTION(name) { statements; }
37 // will define an action with the given name that executes the
38 // statements. The value returned by the statements will be used as
39 // the return value of the action. Inside the statements, you can
40 // refer to the K-th (0-based) argument of the mock function by
41 // 'argK', and refer to its type by 'argK_type'. For example:
43 // ACTION(IncrementArg1) {
44 // arg1_type temp = arg1;
48 // allows you to write
50 // ...WillOnce(IncrementArg1());
52 // You can also refer to the entire argument tuple and its type by
53 // 'args' and 'args_type', and refer to the mock function type and its
54 // return type by 'function_type' and 'return_type'.
56 // Note that you don't need to specify the types of the mock function
57 // arguments. However rest assured that your code is still type-safe:
58 // you'll get a compiler error if *arg1 doesn't support the ++
59 // operator, or if the type of ++(*arg1) isn't compatible with the
60 // mock function's return type, for example.
62 // Sometimes you'll want to parameterize the action. For that you can use
65 // ACTION_P(name, param_name) { statements; }
69 // ACTION_P(Add, n) { return arg0 + n; }
71 // will allow you to write:
73 // ...WillOnce(Add(5));
75 // Note that you don't need to provide the type of the parameter
76 // either. If you need to reference the type of a parameter named
77 // 'foo', you can write 'foo_type'. For example, in the body of
78 // ACTION_P(Add, n) above, you can write 'n_type' to refer to the type
81 // We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support
82 // multi-parameter actions.
84 // For the purpose of typing, you can view
86 // ACTION_Pk(Foo, p1, ..., pk) { ... }
90 // template <typename p1_type, ..., typename pk_type>
91 // FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }
93 // In particular, you can provide the template type arguments
94 // explicitly when invoking Foo(), as in Foo<long, bool>(5, false);
95 // although usually you can rely on the compiler to infer the types
96 // for you automatically. You can assign the result of expression
97 // Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,
98 // pk_type>. This can be useful when composing actions.
100 // You can also overload actions with different numbers of parameters:
102 // ACTION_P(Plus, a) { ... }
103 // ACTION_P2(Plus, a, b) { ... }
105 // While it's tempting to always use the ACTION* macros when defining
106 // a new action, you should also consider implementing ActionInterface
107 // or using MakePolymorphicAction() instead, especially if you need to
108 // use the action a lot. While these approaches require more work,
109 // they give you more control on the types of the mock function
110 // arguments and the action parameters, which in general leads to
111 // better compiler error messages that pay off in the long run. They
112 // also allow overloading actions based on parameter types (as opposed
113 // to just based on the number of parameters).
117 // ACTION*() can only be used in a namespace scope as templates cannot be
118 // declared inside of a local class.
119 // Users can, however, define any local functors (e.g. a lambda) that
120 // can be used as actions.
124 // To learn more about using these macros, please search for 'ACTION' on
125 // https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md
127 // IWYU pragma: private, include "gmock/gmock.h"
128 // IWYU pragma: friend gmock/.*
130 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
131 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
138 #include <functional>
142 #include <type_traits>
145 #include "gmock/internal/gmock-internal-utils.h"
146 #include "gmock/internal/gmock-port.h"
147 #include "gmock/internal/gmock-pp.h"
150 #pragma warning(push)
151 #pragma warning(disable : 4100)
156 // To implement an action Foo, define:
157 // 1. a class FooAction that implements the ActionInterface interface, and
158 // 2. a factory function that creates an Action object from a
161 // The two-level delegation design follows that of Matcher, providing
162 // consistency for extension developers. It also eases ownership
163 // management as Action objects can now be copied like plain values.
167 // BuiltInDefaultValueGetter<T, true>::Get() returns a
168 // default-constructed T value. BuiltInDefaultValueGetter<T,
169 // false>::Get() crashes with an error.
171 // This primary template is used when kDefaultConstructible is true.
172 template <typename T, bool kDefaultConstructible>
173 struct BuiltInDefaultValueGetter {
174 static T Get() { return T(); }
176 template <typename T>
177 struct BuiltInDefaultValueGetter<T, false> {
179 Assert(false, __FILE__, __LINE__,
180 "Default action undefined for the function return type.");
181 return internal::Invalid<T>();
182 // The above statement will never be reached, but is required in
183 // order for this function to compile.
187 // BuiltInDefaultValue<T>::Get() returns the "built-in" default value
188 // for type T, which is NULL when T is a raw pointer type, 0 when T is
189 // a numeric type, false when T is bool, or "" when T is string or
190 // std::string. In addition, in C++11 and above, it turns a
191 // default-constructed T value if T is default constructible. For any
192 // other type T, the built-in default T value is undefined, and the
193 // function will abort the process.
194 template <typename T>
195 class BuiltInDefaultValue {
197 // This function returns true if and only if type T has a built-in default
199 static bool Exists() { return ::std::is_default_constructible<T>::value; }
202 return BuiltInDefaultValueGetter<
203 T, ::std::is_default_constructible<T>::value>::Get();
207 // This partial specialization says that we use the same built-in
208 // default value for T and const T.
209 template <typename T>
210 class BuiltInDefaultValue<const T> {
212 static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }
213 static T Get() { return BuiltInDefaultValue<T>::Get(); }
216 // This partial specialization defines the default values for pointer
218 template <typename T>
219 class BuiltInDefaultValue<T*> {
221 static bool Exists() { return true; }
222 static T* Get() { return nullptr; }
225 // The following specializations define the default values for
226 // specific types we care about.
227 #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \
229 class BuiltInDefaultValue<type> { \
231 static bool Exists() { return true; } \
232 static type Get() { return value; } \
235 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT
236 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, "");
237 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);
238 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0');
239 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0');
240 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0');
242 // There's no need for a default action for signed wchar_t, as that
243 // type is the same as wchar_t for gcc, and invalid for MSVC.
245 // There's also no need for a default action for unsigned wchar_t, as
246 // that type is the same as unsigned int for gcc, and invalid for
248 #if GMOCK_WCHAR_T_IS_NATIVE_
249 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT
252 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT
253 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT
254 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);
255 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);
256 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT
257 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT
258 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0); // NOLINT
259 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0); // NOLINT
260 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);
261 GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);
263 #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_
265 // Partial implementations of metaprogramming types from the standard library
266 // not available in C++11.
268 template <typename P>
271 : std::integral_constant<bool, bool(!P::value)> {};
273 // Base case: with zero predicates the answer is always true.
274 template <typename...>
275 struct conjunction : std::true_type {};
277 // With a single predicate, the answer is that predicate.
278 template <typename P1>
279 struct conjunction<P1> : P1 {};
281 // With multiple predicates the answer is the first predicate if that is false,
282 // and we recurse otherwise.
283 template <typename P1, typename... Ps>
284 struct conjunction<P1, Ps...>
285 : std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {};
287 template <typename...>
288 struct disjunction : std::false_type {};
290 template <typename P1>
291 struct disjunction<P1> : P1 {};
293 template <typename P1, typename... Ps>
294 struct disjunction<P1, Ps...>
296 : std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {};
298 template <typename...>
301 // Detects whether an expression of type `From` can be implicitly converted to
302 // `To` according to [conv]. In C++17, [conv]/3 defines this as follows:
304 // An expression e can be implicitly converted to a type T if and only if
305 // the declaration T t=e; is well-formed, for some invented temporary
306 // variable t ([dcl.init]).
308 // [conv]/2 implies we can use function argument passing to detect whether this
309 // initialization is valid.
311 // Note that this is distinct from is_convertible, which requires this be valid:
314 // return declval<From>();
317 // In particular, is_convertible doesn't give the correct answer when `To` and
318 // `From` are the same non-moveable type since `declval<From>` will be an rvalue
319 // reference, defeating the guaranteed copy elision that would otherwise make
320 // this function work.
322 // REQUIRES: `From` is not cv void.
323 template <typename From, typename To>
324 struct is_implicitly_convertible {
326 // A function that accepts a parameter of type T. This can be called with type
327 // U successfully only if U is implicitly convertible to T.
328 template <typename T>
329 static void Accept(T);
331 // A function that creates a value of type T.
332 template <typename T>
335 // An overload be selected when implicit conversion from T to To is possible.
336 template <typename T, typename = decltype(Accept<To>(Make<T>()))>
337 static std::true_type TestImplicitConversion(int);
339 // A fallback overload selected in all other cases.
340 template <typename T>
341 static std::false_type TestImplicitConversion(...);
344 using type = decltype(TestImplicitConversion<From>(0));
345 static constexpr bool value = type::value;
348 // Like std::invoke_result_t from C++17, but works only for objects with call
349 // operators (not e.g. member function pointers, which we don't need specific
350 // support for in OnceAction because std::function deals with them).
351 template <typename F, typename... Args>
352 using call_result_t = decltype(std::declval<F>()(std::declval<Args>()...));
354 template <typename Void, typename R, typename F, typename... Args>
355 struct is_callable_r_impl : std::false_type {};
357 // Specialize the struct for those template arguments where call_result_t is
358 // well-formed. When it's not, the generic template above is chosen, resulting
359 // in std::false_type.
360 template <typename R, typename F, typename... Args>
361 struct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...>
363 std::is_void<R>::value, //
365 is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {};
367 // Like std::is_invocable_r from C++17, but works only for objects with call
368 // operators. See the note on call_result_t.
369 template <typename R, typename F, typename... Args>
370 using is_callable_r = is_callable_r_impl<void, R, F, Args...>;
372 // Like std::as_const from C++17.
373 template <typename T>
374 typename std::add_const<T>::type& as_const(T& t) {
378 } // namespace internal
380 // Specialized for function types below.
381 template <typename F>
384 // An action that can only be used once.
386 // This is accepted by WillOnce, which doesn't require the underlying action to
387 // be copy-constructible (only move-constructible), and promises to invoke it as
388 // an rvalue reference. This allows the action to work with move-only types like
389 // std::move_only_function in a type-safe manner.
393 // // Assume we have some API that needs to accept a unique pointer to some
394 // // non-copyable object Foo.
395 // void AcceptUniquePointer(std::unique_ptr<Foo> foo);
397 // // We can define an action that provides a Foo to that API. Because It
398 // // has to give away its unique pointer, it must not be called more than
399 // // once, so its call operator is &&-qualified.
400 // struct ProvideFoo {
401 // std::unique_ptr<Foo> foo;
403 // void operator()() && {
404 // AcceptUniquePointer(std::move(Foo));
408 // // This action can be used with WillOnce.
409 // EXPECT_CALL(mock, Call)
410 // .WillOnce(ProvideFoo{std::make_unique<Foo>(...)});
412 // // But a call to WillRepeatedly will fail to compile. This is correct,
413 // // since the action cannot correctly be used repeatedly.
414 // EXPECT_CALL(mock, Call)
415 // .WillRepeatedly(ProvideFoo{std::make_unique<Foo>(...)});
417 // A less-contrived example would be an action that returns an arbitrary type,
418 // whose &&-qualified call operator is capable of dealing with move-only types.
419 template <typename Result, typename... Args>
420 class OnceAction<Result(Args...)> final {
422 // True iff we can use the given callable type (or lvalue reference) directly
423 // via StdFunctionAdaptor.
424 template <typename Callable>
425 using IsDirectlyCompatible = internal::conjunction<
426 // It must be possible to capture the callable in StdFunctionAdaptor.
427 std::is_constructible<typename std::decay<Callable>::type, Callable>,
428 // The callable must be compatible with our signature.
429 internal::is_callable_r<Result, typename std::decay<Callable>::type,
432 // True iff we can use the given callable type via StdFunctionAdaptor once we
433 // ignore incoming arguments.
434 template <typename Callable>
435 using IsCompatibleAfterIgnoringArguments = internal::conjunction<
436 // It must be possible to capture the callable in a lambda.
437 std::is_constructible<typename std::decay<Callable>::type, Callable>,
438 // The callable must be invocable with zero arguments, returning something
439 // convertible to Result.
440 internal::is_callable_r<Result, typename std::decay<Callable>::type>>;
443 // Construct from a callable that is directly compatible with our mocked
444 // signature: it accepts our function type's arguments and returns something
445 // convertible to our result type.
446 template <typename Callable,
447 typename std::enable_if<
448 internal::conjunction<
449 // Teach clang on macOS that we're not talking about a
450 // copy/move constructor here. Otherwise it gets confused
451 // when checking the is_constructible requirement of our
453 internal::negation<std::is_same<
454 OnceAction, typename std::decay<Callable>::type>>,
455 IsDirectlyCompatible<Callable>> //
458 OnceAction(Callable&& callable) // NOLINT
459 : function_(StdFunctionAdaptor<typename std::decay<Callable>::type>(
460 {}, std::forward<Callable>(callable))) {}
462 // As above, but for a callable that ignores the mocked function's arguments.
463 template <typename Callable,
464 typename std::enable_if<
465 internal::conjunction<
466 // Teach clang on macOS that we're not talking about a
467 // copy/move constructor here. Otherwise it gets confused
468 // when checking the is_constructible requirement of our
470 internal::negation<std::is_same<
471 OnceAction, typename std::decay<Callable>::type>>,
472 // Exclude callables for which the overload above works.
473 // We'd rather provide the arguments if possible.
474 internal::negation<IsDirectlyCompatible<Callable>>,
475 IsCompatibleAfterIgnoringArguments<Callable>>::value,
477 OnceAction(Callable&& callable) // NOLINT
478 // Call the constructor above with a callable
479 // that ignores the input arguments.
480 : OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{
481 std::forward<Callable>(callable)}) {}
483 // We are naturally copyable because we store only an std::function, but
484 // semantically we should not be copyable.
485 OnceAction(const OnceAction&) = delete;
486 OnceAction& operator=(const OnceAction&) = delete;
487 OnceAction(OnceAction&&) = default;
489 // Invoke the underlying action callable with which we were constructed,
490 // handing it the supplied arguments.
491 Result Call(Args... args) && {
492 return function_(std::forward<Args>(args)...);
496 // An adaptor that wraps a callable that is compatible with our signature and
497 // being invoked as an rvalue reference so that it can be used as an
498 // StdFunctionAdaptor. This throws away type safety, but that's fine because
499 // this is only used by WillOnce, which we know calls at most once.
501 // Once we have something like std::move_only_function from C++23, we can do
503 template <typename Callable>
504 class StdFunctionAdaptor final {
506 // A tag indicating that the (otherwise universal) constructor is accepting
507 // the callable itself, instead of e.g. stealing calls for the move
509 struct CallableTag final {};
511 template <typename F>
512 explicit StdFunctionAdaptor(CallableTag, F&& callable)
513 : callable_(std::make_shared<Callable>(std::forward<F>(callable))) {}
515 // Rather than explicitly returning Result, we return whatever the wrapped
516 // callable returns. This allows for compatibility with existing uses like
517 // the following, when the mocked function returns void:
519 // EXPECT_CALL(mock_fn_, Call)
525 // Such a callable can be turned into std::function<void()>. If we use an
526 // explicit return type of Result here then it *doesn't* work with
527 // std::function, because we'll get a "void function should not return a
530 // We need not worry about incompatible result types because the SFINAE on
531 // OnceAction already checks this for us. std::is_invocable_r_v itself makes
532 // the same allowance for void result types.
533 template <typename... ArgRefs>
534 internal::call_result_t<Callable, ArgRefs...> operator()(
535 ArgRefs&&... args) const {
536 return std::move(*callable_)(std::forward<ArgRefs>(args)...);
540 // We must put the callable on the heap so that we are copyable, which
541 // std::function needs.
542 std::shared_ptr<Callable> callable_;
545 // An adaptor that makes a callable that accepts zero arguments callable with
546 // our mocked arguments.
547 template <typename Callable>
548 struct IgnoreIncomingArguments {
549 internal::call_result_t<Callable> operator()(Args&&...) {
550 return std::move(callable)();
556 std::function<Result(Args...)> function_;
559 // When an unexpected function call is encountered, Google Mock will
560 // let it return a default value if the user has specified one for its
561 // return type, or if the return type has a built-in default value;
562 // otherwise Google Mock won't know what value to return and will have
563 // to abort the process.
565 // The DefaultValue<T> class allows a user to specify the
566 // default value for a type T that is both copyable and publicly
567 // destructible (i.e. anything that can be used as a function return
568 // type). The usage is:
570 // // Sets the default value for type T to be foo.
571 // DefaultValue<T>::Set(foo);
572 template <typename T>
575 // Sets the default value for type T; requires T to be
576 // copy-constructable and have a public destructor.
577 static void Set(T x) {
579 producer_ = new FixedValueProducer(x);
582 // Provides a factory function to be called to generate the default value.
583 // This method can be used even if T is only move-constructible, but it is not
584 // limited to that case.
585 typedef T (*FactoryFunction)();
586 static void SetFactory(FactoryFunction factory) {
588 producer_ = new FactoryValueProducer(factory);
591 // Unsets the default value for type T.
592 static void Clear() {
597 // Returns true if and only if the user has set the default value for type T.
598 static bool IsSet() { return producer_ != nullptr; }
600 // Returns true if T has a default return value set by the user or there
601 // exists a built-in default value.
602 static bool Exists() {
603 return IsSet() || internal::BuiltInDefaultValue<T>::Exists();
606 // Returns the default value for type T if the user has set one;
607 // otherwise returns the built-in default value. Requires that Exists()
608 // is true, which ensures that the return value is well-defined.
610 return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()
611 : producer_->Produce();
615 class ValueProducer {
617 virtual ~ValueProducer() {}
618 virtual T Produce() = 0;
621 class FixedValueProducer : public ValueProducer {
623 explicit FixedValueProducer(T value) : value_(value) {}
624 T Produce() override { return value_; }
628 FixedValueProducer(const FixedValueProducer&) = delete;
629 FixedValueProducer& operator=(const FixedValueProducer&) = delete;
632 class FactoryValueProducer : public ValueProducer {
634 explicit FactoryValueProducer(FactoryFunction factory)
635 : factory_(factory) {}
636 T Produce() override { return factory_(); }
639 const FactoryFunction factory_;
640 FactoryValueProducer(const FactoryValueProducer&) = delete;
641 FactoryValueProducer& operator=(const FactoryValueProducer&) = delete;
644 static ValueProducer* producer_;
647 // This partial specialization allows a user to set default values for
649 template <typename T>
650 class DefaultValue<T&> {
652 // Sets the default value for type T&.
653 static void Set(T& x) { // NOLINT
657 // Unsets the default value for type T&.
658 static void Clear() { address_ = nullptr; }
660 // Returns true if and only if the user has set the default value for type T&.
661 static bool IsSet() { return address_ != nullptr; }
663 // Returns true if T has a default return value set by the user or there
664 // exists a built-in default value.
665 static bool Exists() {
666 return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();
669 // Returns the default value for type T& if the user has set one;
670 // otherwise returns the built-in default value if there is one;
671 // otherwise aborts the process.
673 return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()
681 // This specialization allows DefaultValue<void>::Get() to
684 class DefaultValue<void> {
686 static bool Exists() { return true; }
690 // Points to the user-set default value for type T.
691 template <typename T>
692 typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;
694 // Points to the user-set default value for type T&.
695 template <typename T>
696 T* DefaultValue<T&>::address_ = nullptr;
698 // Implement this interface to define an action for function type F.
699 template <typename F>
700 class ActionInterface {
702 typedef typename internal::Function<F>::Result Result;
703 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
706 virtual ~ActionInterface() {}
708 // Performs the action. This method is not const, as in general an
709 // action can have side effects and be stateful. For example, a
710 // get-the-next-element-from-the-collection action will need to
711 // remember the current element.
712 virtual Result Perform(const ArgumentTuple& args) = 0;
715 ActionInterface(const ActionInterface&) = delete;
716 ActionInterface& operator=(const ActionInterface&) = delete;
719 template <typename F>
722 // An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)
723 // object that represents an action to be taken when a mock function of type
724 // R(Args...) is called. The implementation of Action<T> is just a
725 // std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! You
726 // can view an object implementing ActionInterface<F> as a concrete action
727 // (including its current state), and an Action<F> object as a handle to it.
728 template <typename R, typename... Args>
729 class Action<R(Args...)> {
731 using F = R(Args...);
733 // Adapter class to allow constructing Action from a legacy ActionInterface.
734 // New code should create Actions from functors instead.
735 struct ActionAdapter {
736 // Adapter must be copyable to satisfy std::function requirements.
737 ::std::shared_ptr<ActionInterface<F>> impl_;
739 template <typename... InArgs>
740 typename internal::Function<F>::Result operator()(InArgs&&... args) {
741 return impl_->Perform(
742 ::std::forward_as_tuple(::std::forward<InArgs>(args)...));
746 template <typename G>
747 using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;
750 typedef typename internal::Function<F>::Result Result;
751 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
753 // Constructs a null Action. Needed for storing Action objects in
757 // Construct an Action from a specified callable.
758 // This cannot take std::function directly, because then Action would not be
759 // directly constructible from lambda (it would require two conversions).
762 typename = typename std::enable_if<internal::disjunction<
763 IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,
765 Action(G&& fun) { // NOLINT
766 Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());
769 // Constructs an Action from its implementation.
770 explicit Action(ActionInterface<F>* impl)
771 : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}
773 // This constructor allows us to turn an Action<Func> object into an
774 // Action<F>, as long as F's arguments can be implicitly converted
775 // to Func's and Func's return type can be implicitly converted to F's.
776 template <typename Func>
777 Action(const Action<Func>& action) // NOLINT
778 : fun_(action.fun_) {}
780 // Returns true if and only if this is the DoDefault() action.
781 bool IsDoDefault() const { return fun_ == nullptr; }
783 // Performs the action. Note that this method is const even though
784 // the corresponding method in ActionInterface is not. The reason
785 // is that a const Action<F> means that it cannot be re-bound to
786 // another concrete action, not that the concrete action it binds to
787 // cannot change state. (Think of the difference between a const
788 // pointer and a pointer to const.)
789 Result Perform(ArgumentTuple args) const {
791 internal::IllegalDoDefault(__FILE__, __LINE__);
793 return internal::Apply(fun_, ::std::move(args));
796 // An action can be used as a OnceAction, since it's obviously safe to call it
798 operator OnceAction<F>() const { // NOLINT
799 // Return a OnceAction-compatible callable that calls Perform with the
800 // arguments it is provided. We could instead just return fun_, but then
801 // we'd need to handle the IsDoDefault() case separately.
805 R operator()(Args... args) && {
806 return action.Perform(
807 std::forward_as_tuple(std::forward<Args>(args)...));
815 template <typename G>
818 template <typename G>
819 void Init(G&& g, ::std::true_type) {
820 fun_ = ::std::forward<G>(g);
823 template <typename G>
824 void Init(G&& g, ::std::false_type) {
825 fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};
828 template <typename FunctionImpl>
830 template <typename... InArgs>
831 Result operator()(const InArgs&...) const {
832 return function_impl();
835 FunctionImpl function_impl;
838 // fun_ is an empty function if and only if this is the DoDefault() action.
839 ::std::function<F> fun_;
842 // The PolymorphicAction class template makes it easy to implement a
843 // polymorphic action (i.e. an action that can be used in mock
844 // functions of than one type, e.g. Return()).
846 // To define a polymorphic action, a user first provides a COPYABLE
847 // implementation class that has a Perform() method template:
851 // template <typename Result, typename ArgumentTuple>
852 // Result Perform(const ArgumentTuple& args) const {
853 // // Processes the arguments and returns a result, using
854 // // std::get<N>(args) to get the N-th (0-based) argument in the tuple.
859 // Then the user creates the polymorphic action using
860 // MakePolymorphicAction(object) where object has type FooAction. See
861 // the definition of Return(void) and SetArgumentPointee<N>(value) for
862 // complete examples.
863 template <typename Impl>
864 class PolymorphicAction {
866 explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}
868 template <typename F>
869 operator Action<F>() const {
870 return Action<F>(new MonomorphicImpl<F>(impl_));
874 template <typename F>
875 class MonomorphicImpl : public ActionInterface<F> {
877 typedef typename internal::Function<F>::Result Result;
878 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
880 explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}
882 Result Perform(const ArgumentTuple& args) override {
883 return impl_.template Perform<Result>(args);
893 // Creates an Action from its implementation and returns it. The
894 // created Action object owns the implementation.
895 template <typename F>
896 Action<F> MakeAction(ActionInterface<F>* impl) {
897 return Action<F>(impl);
900 // Creates a polymorphic action from its implementation. This is
901 // easier to use than the PolymorphicAction<Impl> constructor as it
902 // doesn't require you to explicitly write the template argument, e.g.
904 // MakePolymorphicAction(foo);
906 // PolymorphicAction<TypeOfFoo>(foo);
907 template <typename Impl>
908 inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {
909 return PolymorphicAction<Impl>(impl);
914 // Helper struct to specialize ReturnAction to execute a move instead of a copy
915 // on return. Useful for move-only types, but could be used on any type.
916 template <typename T>
917 struct ByMoveWrapper {
918 explicit ByMoveWrapper(T value) : payload(std::move(value)) {}
922 // The general implementation of Return(R). Specializations follow below.
923 template <typename R>
924 class ReturnAction final {
926 explicit ReturnAction(R value) : value_(std::move(value)) {}
928 template <typename U, typename... Args,
929 typename = typename std::enable_if<conjunction<
930 // See the requirements documented on Return.
931 negation<std::is_same<void, U>>, //
932 negation<std::is_reference<U>>, //
933 std::is_convertible<R, U>, //
934 std::is_move_constructible<U>>::value>::type>
935 operator OnceAction<U(Args...)>() && { // NOLINT
936 return Impl<U>(std::move(value_));
939 template <typename U, typename... Args,
940 typename = typename std::enable_if<conjunction<
941 // See the requirements documented on Return.
942 negation<std::is_same<void, U>>, //
943 negation<std::is_reference<U>>, //
944 std::is_convertible<const R&, U>, //
945 std::is_copy_constructible<U>>::value>::type>
946 operator Action<U(Args...)>() const { // NOLINT
947 return Impl<U>(value_);
951 // Implements the Return(x) action for a mock function that returns type U.
952 template <typename U>
955 // The constructor used when the return value is allowed to move from the
956 // input value (i.e. we are converting to OnceAction).
957 explicit Impl(R&& input_value)
958 : state_(new State(std::move(input_value))) {}
960 // The constructor used when the return value is not allowed to move from
961 // the input value (i.e. we are converting to Action).
962 explicit Impl(const R& input_value) : state_(new State(input_value)) {}
964 U operator()() && { return std::move(state_->value); }
965 U operator()() const& { return state_->value; }
968 // We put our state on the heap so that the compiler-generated copy/move
969 // constructors work correctly even when U is a reference-like type. This is
970 // necessary only because we eagerly create State::value (see the note on
971 // that symbol for details). If we instead had only the input value as a
972 // member then the default constructors would work fine.
974 // For example, when R is std::string and U is std::string_view, value is a
975 // reference to the string backed by input_value. The copy constructor would
976 // copy both, so that we wind up with a new input_value object (with the
977 // same contents) and a reference to the *old* input_value object rather
980 explicit State(const R& input_value_in)
981 : input_value(input_value_in),
982 // Make an implicit conversion to Result before initializing the U
983 // object we store, avoiding calling any explicit constructor of U
986 // This simulates the language rules: a function with return type U
987 // that does `return R()` requires R to be implicitly convertible to
988 // U, and uses that path for the conversion, even U Result has an
989 // explicit constructor from R.
990 value(ImplicitCast_<U>(internal::as_const(input_value))) {}
992 // As above, but for the case where we're moving from the ReturnAction
993 // object because it's being used as a OnceAction.
994 explicit State(R&& input_value_in)
995 : input_value(std::move(input_value_in)),
996 // For the same reason as above we make an implicit conversion to U
997 // before initializing the value.
999 // Unlike above we provide the input value as an rvalue to the
1000 // implicit conversion because this is a OnceAction: it's fine if it
1001 // wants to consume the input value.
1002 value(ImplicitCast_<U>(std::move(input_value))) {}
1004 // A copy of the value originally provided by the user. We retain this in
1005 // addition to the value of the mock function's result type below in case
1006 // the latter is a reference-like type. See the std::string_view example
1007 // in the documentation on Return.
1010 // The value we actually return, as the type returned by the mock function
1013 // We eagerly initialize this here, rather than lazily doing the implicit
1014 // conversion automatically each time Perform is called, for historical
1015 // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126)
1016 // made the Action<U()> conversion operator eagerly convert the R value to
1017 // U, but without keeping the R alive. This broke the use case discussed
1018 // in the documentation for Return, making reference-like types such as
1019 // std::string_view not safe to use as U where the input type R is a
1020 // value-like type such as std::string.
1022 // The example the commit gave was not very clear, nor was the issue
1023 // thread (https://github.com/google/googlemock/issues/86), but it seems
1024 // the worry was about reference-like input types R that flatten to a
1025 // value-like type U when being implicitly converted. An example of this
1026 // is std::vector<bool>::reference, which is often a proxy type with an
1027 // reference to the underlying vector:
1029 // // Helper method: have the mock function return bools according
1030 // // to the supplied script.
1031 // void SetActions(MockFunction<bool(size_t)>& mock,
1032 // const std::vector<bool>& script) {
1033 // for (size_t i = 0; i < script.size(); ++i) {
1034 // EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i]));
1039 // // Set actions using a temporary vector, whose operator[]
1040 // // returns proxy objects that references that will be
1041 // // dangling once the call to SetActions finishes and the
1042 // // vector is destroyed.
1043 // MockFunction<bool(size_t)> mock;
1044 // SetActions(mock, {false, true});
1046 // EXPECT_FALSE(mock.AsStdFunction()(0));
1047 // EXPECT_TRUE(mock.AsStdFunction()(1));
1050 // This eager conversion helps with a simple case like this, but doesn't
1051 // fully make these types work in general. For example the following still
1052 // uses a dangling reference:
1055 // MockFunction<std::vector<std::string>()> mock;
1057 // // Return the same vector twice, and then the empty vector
1059 // auto action = Return(std::initializer_list<std::string>{
1060 // "taco", "burrito",
1063 // EXPECT_CALL(mock, Call)
1064 // .WillOnce(action)
1065 // .WillOnce(action)
1066 // .WillRepeatedly(Return(std::vector<std::string>{}));
1068 // EXPECT_THAT(mock.AsStdFunction()(),
1069 // ElementsAre("taco", "burrito"));
1070 // EXPECT_THAT(mock.AsStdFunction()(),
1071 // ElementsAre("taco", "burrito"));
1072 // EXPECT_THAT(mock.AsStdFunction()(), IsEmpty());
1078 const std::shared_ptr<State> state_;
1084 // A specialization of ReturnAction<R> when R is ByMoveWrapper<T> for some T.
1086 // This version applies the type system-defeating hack of moving from T even in
1087 // the const call operator, checking at runtime that it isn't called more than
1088 // once, since the user has declared their intent to do so by using ByMove.
1089 template <typename T>
1090 class ReturnAction<ByMoveWrapper<T>> final {
1092 explicit ReturnAction(ByMoveWrapper<T> wrapper)
1093 : state_(new State(std::move(wrapper.payload))) {}
1095 T operator()() const {
1096 GTEST_CHECK_(!state_->called)
1097 << "A ByMove() action must be performed at most once.";
1099 state_->called = true;
1100 return std::move(state_->value);
1104 // We store our state on the heap so that we are copyable as required by
1105 // Action, despite the fact that we are stateful and T may not be copyable.
1107 explicit State(T&& value_in) : value(std::move(value_in)) {}
1110 bool called = false;
1113 const std::shared_ptr<State> state_;
1116 // Implements the ReturnNull() action.
1117 class ReturnNullAction {
1119 // Allows ReturnNull() to be used in any pointer-returning function. In C++11
1120 // this is enforced by returning nullptr, and in non-C++11 by asserting a
1121 // pointer type on compile time.
1122 template <typename Result, typename ArgumentTuple>
1123 static Result Perform(const ArgumentTuple&) {
1128 // Implements the Return() action.
1129 class ReturnVoidAction {
1131 // Allows Return() to be used in any void-returning function.
1132 template <typename Result, typename ArgumentTuple>
1133 static void Perform(const ArgumentTuple&) {
1134 static_assert(std::is_void<Result>::value, "Result should be void.");
1138 // Implements the polymorphic ReturnRef(x) action, which can be used
1139 // in any function that returns a reference to the type of x,
1140 // regardless of the argument types.
1141 template <typename T>
1142 class ReturnRefAction {
1144 // Constructs a ReturnRefAction object from the reference to be returned.
1145 explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT
1147 // This template type conversion operator allows ReturnRef(x) to be
1148 // used in ANY function that returns a reference to x's type.
1149 template <typename F>
1150 operator Action<F>() const {
1151 typedef typename Function<F>::Result Result;
1152 // Asserts that the function return type is a reference. This
1153 // catches the user error of using ReturnRef(x) when Return(x)
1154 // should be used, and generates some helpful error message.
1155 static_assert(std::is_reference<Result>::value,
1156 "use Return instead of ReturnRef to return a value");
1157 return Action<F>(new Impl<F>(ref_));
1161 // Implements the ReturnRef(x) action for a particular function type F.
1162 template <typename F>
1163 class Impl : public ActionInterface<F> {
1165 typedef typename Function<F>::Result Result;
1166 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1168 explicit Impl(T& ref) : ref_(ref) {} // NOLINT
1170 Result Perform(const ArgumentTuple&) override { return ref_; }
1179 // Implements the polymorphic ReturnRefOfCopy(x) action, which can be
1180 // used in any function that returns a reference to the type of x,
1181 // regardless of the argument types.
1182 template <typename T>
1183 class ReturnRefOfCopyAction {
1185 // Constructs a ReturnRefOfCopyAction object from the reference to
1187 explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT
1189 // This template type conversion operator allows ReturnRefOfCopy(x) to be
1190 // used in ANY function that returns a reference to x's type.
1191 template <typename F>
1192 operator Action<F>() const {
1193 typedef typename Function<F>::Result Result;
1194 // Asserts that the function return type is a reference. This
1195 // catches the user error of using ReturnRefOfCopy(x) when Return(x)
1196 // should be used, and generates some helpful error message.
1197 static_assert(std::is_reference<Result>::value,
1198 "use Return instead of ReturnRefOfCopy to return a value");
1199 return Action<F>(new Impl<F>(value_));
1203 // Implements the ReturnRefOfCopy(x) action for a particular function type F.
1204 template <typename F>
1205 class Impl : public ActionInterface<F> {
1207 typedef typename Function<F>::Result Result;
1208 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1210 explicit Impl(const T& value) : value_(value) {} // NOLINT
1212 Result Perform(const ArgumentTuple&) override { return value_; }
1221 // Implements the polymorphic ReturnRoundRobin(v) action, which can be
1222 // used in any function that returns the element_type of v.
1223 template <typename T>
1224 class ReturnRoundRobinAction {
1226 explicit ReturnRoundRobinAction(std::vector<T> values) {
1227 GTEST_CHECK_(!values.empty())
1228 << "ReturnRoundRobin requires at least one element.";
1229 state_->values = std::move(values);
1232 template <typename... Args>
1233 T operator()(Args&&...) const {
1234 return state_->Next();
1240 T ret_val = values[i++];
1241 if (i == values.size()) i = 0;
1245 std::vector<T> values;
1248 std::shared_ptr<State> state_ = std::make_shared<State>();
1251 // Implements the polymorphic DoDefault() action.
1252 class DoDefaultAction {
1254 // This template type conversion operator allows DoDefault() to be
1255 // used in any function.
1256 template <typename F>
1257 operator Action<F>() const {
1262 // Implements the Assign action to set a given pointer referent to a
1263 // particular value.
1264 template <typename T1, typename T2>
1265 class AssignAction {
1267 AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}
1269 template <typename Result, typename ArgumentTuple>
1270 void Perform(const ArgumentTuple& /* args */) const {
1279 #if !GTEST_OS_WINDOWS_MOBILE
1281 // Implements the SetErrnoAndReturn action to simulate return from
1282 // various system calls and libc functions.
1283 template <typename T>
1284 class SetErrnoAndReturnAction {
1286 SetErrnoAndReturnAction(int errno_value, T result)
1287 : errno_(errno_value), result_(result) {}
1288 template <typename Result, typename ArgumentTuple>
1289 Result Perform(const ArgumentTuple& /* args */) const {
1299 #endif // !GTEST_OS_WINDOWS_MOBILE
1301 // Implements the SetArgumentPointee<N>(x) action for any function
1302 // whose N-th argument (0-based) is a pointer to x's type.
1303 template <size_t N, typename A, typename = void>
1304 struct SetArgumentPointeeAction {
1307 template <typename... Args>
1308 void operator()(const Args&... args) const {
1309 *::std::get<N>(std::tie(args...)) = value;
1313 // Implements the Invoke(object_ptr, &Class::Method) action.
1314 template <class Class, typename MethodPtr>
1315 struct InvokeMethodAction {
1316 Class* const obj_ptr;
1317 const MethodPtr method_ptr;
1319 template <typename... Args>
1320 auto operator()(Args&&... args) const
1321 -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {
1322 return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);
1326 // Implements the InvokeWithoutArgs(f) action. The template argument
1327 // FunctionImpl is the implementation type of f, which can be either a
1328 // function pointer or a functor. InvokeWithoutArgs(f) can be used as an
1329 // Action<F> as long as f's type is compatible with F.
1330 template <typename FunctionImpl>
1331 struct InvokeWithoutArgsAction {
1332 FunctionImpl function_impl;
1334 // Allows InvokeWithoutArgs(f) to be used as any action whose type is
1335 // compatible with f.
1336 template <typename... Args>
1337 auto operator()(const Args&...) -> decltype(function_impl()) {
1338 return function_impl();
1342 // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.
1343 template <class Class, typename MethodPtr>
1344 struct InvokeMethodWithoutArgsAction {
1345 Class* const obj_ptr;
1346 const MethodPtr method_ptr;
1349 decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());
1351 template <typename... Args>
1352 ReturnType operator()(const Args&...) const {
1353 return (obj_ptr->*method_ptr)();
1357 // Implements the IgnoreResult(action) action.
1358 template <typename A>
1359 class IgnoreResultAction {
1361 explicit IgnoreResultAction(const A& action) : action_(action) {}
1363 template <typename F>
1364 operator Action<F>() const {
1365 // Assert statement belongs here because this is the best place to verify
1366 // conditions on F. It produces the clearest error messages
1367 // in most compilers.
1368 // Impl really belongs in this scope as a local class but can't
1369 // because MSVC produces duplicate symbols in different translation units
1370 // in this case. Until MS fixes that bug we put Impl into the class scope
1371 // and put the typedef both here (for use in assert statement) and
1372 // in the Impl class. But both definitions must be the same.
1373 typedef typename internal::Function<F>::Result Result;
1375 // Asserts at compile time that F returns void.
1376 static_assert(std::is_void<Result>::value, "Result type should be void.");
1378 return Action<F>(new Impl<F>(action_));
1382 template <typename F>
1383 class Impl : public ActionInterface<F> {
1385 typedef typename internal::Function<F>::Result Result;
1386 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1388 explicit Impl(const A& action) : action_(action) {}
1390 void Perform(const ArgumentTuple& args) override {
1391 // Performs the action and ignores its result.
1392 action_.Perform(args);
1396 // Type OriginalFunction is the same as F except that its return
1397 // type is IgnoredValue.
1399 typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;
1401 const Action<OriginalFunction> action_;
1407 template <typename InnerAction, size_t... I>
1408 struct WithArgsAction {
1409 InnerAction inner_action;
1411 // The signature of the function as seen by the inner action, given an out
1412 // action with the given result and argument types.
1413 template <typename R, typename... Args>
1414 using InnerSignature =
1415 R(typename std::tuple_element<I, std::tuple<Args...>>::type...);
1417 // Rather than a call operator, we must define conversion operators to
1418 // particular action types. This is necessary for embedded actions like
1419 // DoDefault(), which rely on an action conversion operators rather than
1420 // providing a call operator because even with a particular set of arguments
1421 // they don't have a fixed return type.
1423 template <typename R, typename... Args,
1424 typename std::enable_if<
1425 std::is_convertible<
1427 // Unfortunately we can't use the InnerSignature alias here;
1428 // MSVC complains about the I parameter pack not being
1429 // expanded (error C3520) despite it being expanded in the
1431 OnceAction<R(typename std::tuple_element<
1432 I, std::tuple<Args...>>::type...)>>::value,
1434 operator OnceAction<R(Args...)>() && { // NOLINT
1436 OnceAction<InnerSignature<R, Args...>> inner_action;
1438 R operator()(Args&&... args) && {
1439 return std::move(inner_action)
1441 std::forward_as_tuple(std::forward<Args>(args)...))...);
1445 return OA{std::move(inner_action)};
1448 template <typename R, typename... Args,
1449 typename std::enable_if<
1450 std::is_convertible<
1452 // Unfortunately we can't use the InnerSignature alias here;
1453 // MSVC complains about the I parameter pack not being
1454 // expanded (error C3520) despite it being expanded in the
1456 Action<R(typename std::tuple_element<
1457 I, std::tuple<Args...>>::type...)>>::value,
1459 operator Action<R(Args...)>() const { // NOLINT
1460 Action<InnerSignature<R, Args...>> converted(inner_action);
1462 return [converted](Args&&... args) -> R {
1463 return converted.Perform(std::forward_as_tuple(
1464 std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));
1469 template <typename... Actions>
1472 // Base case: only a single action.
1473 template <typename FinalAction>
1474 class DoAllAction<FinalAction> {
1476 struct UserConstructorTag {};
1478 template <typename T>
1479 explicit DoAllAction(UserConstructorTag, T&& action)
1480 : final_action_(std::forward<T>(action)) {}
1482 // Rather than a call operator, we must define conversion operators to
1483 // particular action types. This is necessary for embedded actions like
1484 // DoDefault(), which rely on an action conversion operators rather than
1485 // providing a call operator because even with a particular set of arguments
1486 // they don't have a fixed return type.
1488 template <typename R, typename... Args,
1489 typename std::enable_if<
1490 std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,
1492 operator OnceAction<R(Args...)>() && { // NOLINT
1493 return std::move(final_action_);
1497 typename R, typename... Args,
1498 typename std::enable_if<
1499 std::is_convertible<const FinalAction&, Action<R(Args...)>>::value,
1501 operator Action<R(Args...)>() const { // NOLINT
1502 return final_action_;
1506 FinalAction final_action_;
1509 // Recursive case: support N actions by calling the initial action and then
1510 // calling through to the base class containing N-1 actions.
1511 template <typename InitialAction, typename... OtherActions>
1512 class DoAllAction<InitialAction, OtherActions...>
1513 : private DoAllAction<OtherActions...> {
1515 using Base = DoAllAction<OtherActions...>;
1517 // The type of reference that should be provided to an initial action for a
1518 // mocked function parameter of type T.
1520 // There are two quirks here:
1522 // * Unlike most forwarding functions, we pass scalars through by value.
1523 // This isn't strictly necessary because an lvalue reference would work
1524 // fine too and be consistent with other non-reference types, but it's
1525 // perhaps less surprising.
1527 // For example if the mocked function has signature void(int), then it
1528 // might seem surprising for the user's initial action to need to be
1529 // convertible to Action<void(const int&)>. This is perhaps less
1530 // surprising for a non-scalar type where there may be a performance
1531 // impact, or it might even be impossible, to pass by value.
1533 // * More surprisingly, `const T&` is often not a const reference type.
1534 // By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to
1535 // U& or U&& for some non-scalar type U, then InitialActionArgType<T> is
1536 // U&. In other words, we may hand over a non-const reference.
1538 // So for example, given some non-scalar type Obj we have the following
1541 // T InitialActionArgType<T>
1542 // ------- -----------------------
1546 // const Obj const Obj&
1547 // const Obj& const Obj&
1548 // const Obj&& const Obj&
1550 // In other words, the initial actions get a mutable view of an non-scalar
1551 // argument if and only if the mock function itself accepts a non-const
1552 // reference type. They are never given an rvalue reference to an
1555 // This situation makes sense if you imagine use with a matcher that is
1556 // designed to write through a reference. For example, if the caller wants
1557 // to fill in a reference argument and then return a canned value:
1559 // EXPECT_CALL(mock, Call)
1560 // .WillOnce(DoAll(SetArgReferee<0>(17), Return(19)));
1562 template <typename T>
1563 using InitialActionArgType =
1564 typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;
1567 struct UserConstructorTag {};
1569 template <typename T, typename... U>
1570 explicit DoAllAction(UserConstructorTag, T&& initial_action,
1571 U&&... other_actions)
1572 : Base({}, std::forward<U>(other_actions)...),
1573 initial_action_(std::forward<T>(initial_action)) {}
1575 template <typename R, typename... Args,
1576 typename std::enable_if<
1578 // Both the initial action and the rest must support
1579 // conversion to OnceAction.
1580 std::is_convertible<
1582 OnceAction<void(InitialActionArgType<Args>...)>>,
1583 std::is_convertible<Base, OnceAction<R(Args...)>>>::value,
1585 operator OnceAction<R(Args...)>() && { // NOLINT
1586 // Return an action that first calls the initial action with arguments
1587 // filtered through InitialActionArgType, then forwards arguments directly
1588 // to the base class to deal with the remaining actions.
1590 OnceAction<void(InitialActionArgType<Args>...)> initial_action;
1591 OnceAction<R(Args...)> remaining_actions;
1593 R operator()(Args... args) && {
1594 std::move(initial_action)
1595 .Call(static_cast<InitialActionArgType<Args>>(args)...);
1597 return std::move(remaining_actions).Call(std::forward<Args>(args)...);
1602 std::move(initial_action_),
1603 std::move(static_cast<Base&>(*this)),
1608 typename R, typename... Args,
1609 typename std::enable_if<
1611 // Both the initial action and the rest must support conversion to
1613 std::is_convertible<const InitialAction&,
1614 Action<void(InitialActionArgType<Args>...)>>,
1615 std::is_convertible<const Base&, Action<R(Args...)>>>::value,
1617 operator Action<R(Args...)>() const { // NOLINT
1618 // Return an action that first calls the initial action with arguments
1619 // filtered through InitialActionArgType, then forwards arguments directly
1620 // to the base class to deal with the remaining actions.
1622 Action<void(InitialActionArgType<Args>...)> initial_action;
1623 Action<R(Args...)> remaining_actions;
1625 R operator()(Args... args) const {
1626 initial_action.Perform(std::forward_as_tuple(
1627 static_cast<InitialActionArgType<Args>>(args)...));
1629 return remaining_actions.Perform(
1630 std::forward_as_tuple(std::forward<Args>(args)...));
1636 static_cast<const Base&>(*this),
1641 InitialAction initial_action_;
1644 template <typename T, typename... Params>
1645 struct ReturnNewAction {
1646 T* operator()() const {
1647 return internal::Apply(
1648 [](const Params&... unpacked_params) {
1649 return new T(unpacked_params...);
1653 std::tuple<Params...> params;
1657 struct ReturnArgAction {
1658 template <typename... Args,
1659 typename = typename std::enable_if<(k < sizeof...(Args))>::type>
1660 auto operator()(Args&&... args) const -> decltype(std::get<k>(
1661 std::forward_as_tuple(std::forward<Args>(args)...))) {
1662 return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...));
1666 template <size_t k, typename Ptr>
1667 struct SaveArgAction {
1670 template <typename... Args>
1671 void operator()(const Args&... args) const {
1672 *pointer = std::get<k>(std::tie(args...));
1676 template <size_t k, typename Ptr>
1677 struct SaveArgPointeeAction {
1680 template <typename... Args>
1681 void operator()(const Args&... args) const {
1682 *pointer = *std::get<k>(std::tie(args...));
1686 template <size_t k, typename T>
1687 struct SetArgRefereeAction {
1690 template <typename... Args>
1691 void operator()(Args&&... args) const {
1693 typename ::std::tuple_element<k, std::tuple<Args...>>::type;
1694 static_assert(std::is_lvalue_reference<argk_type>::value,
1695 "Argument must be a reference type.");
1696 std::get<k>(std::tie(args...)) = value;
1700 template <size_t k, typename I1, typename I2>
1701 struct SetArrayArgumentAction {
1705 template <typename... Args>
1706 void operator()(const Args&... args) const {
1707 auto value = std::get<k>(std::tie(args...));
1708 for (auto it = first; it != last; ++it, (void)++value) {
1715 struct DeleteArgAction {
1716 template <typename... Args>
1717 void operator()(const Args&... args) const {
1718 delete std::get<k>(std::tie(args...));
1722 template <typename Ptr>
1723 struct ReturnPointeeAction {
1725 template <typename... Args>
1726 auto operator()(const Args&...) const -> decltype(*pointer) {
1731 #if GTEST_HAS_EXCEPTIONS
1732 template <typename T>
1733 struct ThrowAction {
1735 // We use a conversion operator to adapt to any return type.
1736 template <typename R, typename... Args>
1737 operator Action<R(Args...)>() const { // NOLINT
1739 return [copy](Args...) -> R { throw copy; };
1742 #endif // GTEST_HAS_EXCEPTIONS
1744 } // namespace internal
1746 // An Unused object can be implicitly constructed from ANY value.
1747 // This is handy when defining actions that ignore some or all of the
1748 // mock function arguments. For example, given
1750 // MOCK_METHOD3(Foo, double(const string& label, double x, double y));
1751 // MOCK_METHOD3(Bar, double(int index, double x, double y));
1755 // double DistanceToOriginWithLabel(const string& label, double x, double y) {
1756 // return sqrt(x*x + y*y);
1758 // double DistanceToOriginWithIndex(int index, double x, double y) {
1759 // return sqrt(x*x + y*y);
1762 // EXPECT_CALL(mock, Foo("abc", _, _))
1763 // .WillOnce(Invoke(DistanceToOriginWithLabel));
1764 // EXPECT_CALL(mock, Bar(5, _, _))
1765 // .WillOnce(Invoke(DistanceToOriginWithIndex));
1769 // // We can declare any uninteresting argument as Unused.
1770 // double DistanceToOrigin(Unused, double x, double y) {
1771 // return sqrt(x*x + y*y);
1774 // EXPECT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin));
1775 // EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));
1776 typedef internal::IgnoredValue Unused;
1778 // Creates an action that does actions a1, a2, ..., sequentially in
1779 // each invocation. All but the last action will have a readonly view of the
1781 template <typename... Action>
1782 internal::DoAllAction<typename std::decay<Action>::type...> DoAll(
1783 Action&&... action) {
1784 return internal::DoAllAction<typename std::decay<Action>::type...>(
1785 {}, std::forward<Action>(action)...);
1788 // WithArg<k>(an_action) creates an action that passes the k-th
1789 // (0-based) argument of the mock function to an_action and performs
1790 // it. It adapts an action accepting one argument to one that accepts
1791 // multiple arguments. For convenience, we also provide
1792 // WithArgs<k>(an_action) (defined below) as a synonym.
1793 template <size_t k, typename InnerAction>
1794 internal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(
1795 InnerAction&& action) {
1796 return {std::forward<InnerAction>(action)};
1799 // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes
1800 // the selected arguments of the mock function to an_action and
1801 // performs it. It serves as an adaptor between actions with
1802 // different argument lists.
1803 template <size_t k, size_t... ks, typename InnerAction>
1804 internal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>
1805 WithArgs(InnerAction&& action) {
1806 return {std::forward<InnerAction>(action)};
1809 // WithoutArgs(inner_action) can be used in a mock function with a
1810 // non-empty argument list to perform inner_action, which takes no
1811 // argument. In other words, it adapts an action accepting no
1812 // argument to one that accepts (and ignores) arguments.
1813 template <typename InnerAction>
1814 internal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(
1815 InnerAction&& action) {
1816 return {std::forward<InnerAction>(action)};
1819 // Creates an action that returns a value.
1821 // The returned type can be used with a mock function returning a non-void,
1822 // non-reference type U as follows:
1824 // * If R is convertible to U and U is move-constructible, then the action can
1825 // be used with WillOnce.
1827 // * If const R& is convertible to U and U is copy-constructible, then the
1828 // action can be used with both WillOnce and WillRepeatedly.
1830 // The mock expectation contains the R value from which the U return value is
1831 // constructed (a move/copy of the argument to Return). This means that the R
1832 // value will survive at least until the mock object's expectations are cleared
1833 // or the mock object is destroyed, meaning that U can safely be a
1834 // reference-like type such as std::string_view:
1836 // // The mock function returns a view of a copy of the string fed to
1837 // // Return. The view is valid even after the action is performed.
1838 // MockFunction<std::string_view()> mock;
1839 // EXPECT_CALL(mock, Call).WillOnce(Return(std::string("taco")));
1840 // const std::string_view result = mock.AsStdFunction()();
1841 // EXPECT_EQ("taco", result);
1843 template <typename R>
1844 internal::ReturnAction<R> Return(R value) {
1845 return internal::ReturnAction<R>(std::move(value));
1848 // Creates an action that returns NULL.
1849 inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {
1850 return MakePolymorphicAction(internal::ReturnNullAction());
1853 // Creates an action that returns from a void function.
1854 inline PolymorphicAction<internal::ReturnVoidAction> Return() {
1855 return MakePolymorphicAction(internal::ReturnVoidAction());
1858 // Creates an action that returns the reference to a variable.
1859 template <typename R>
1860 inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT
1861 return internal::ReturnRefAction<R>(x);
1864 // Prevent using ReturnRef on reference to temporary.
1865 template <typename R, R* = nullptr>
1866 internal::ReturnRefAction<R> ReturnRef(R&&) = delete;
1868 // Creates an action that returns the reference to a copy of the
1869 // argument. The copy is created when the action is constructed and
1870 // lives as long as the action.
1871 template <typename R>
1872 inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {
1873 return internal::ReturnRefOfCopyAction<R>(x);
1876 // DEPRECATED: use Return(x) directly with WillOnce.
1878 // Modifies the parent action (a Return() action) to perform a move of the
1879 // argument instead of a copy.
1880 // Return(ByMove()) actions can only be executed once and will assert this
1882 template <typename R>
1883 internal::ByMoveWrapper<R> ByMove(R x) {
1884 return internal::ByMoveWrapper<R>(std::move(x));
1887 // Creates an action that returns an element of `vals`. Calling this action will
1888 // repeatedly return the next value from `vals` until it reaches the end and
1889 // will restart from the beginning.
1890 template <typename T>
1891 internal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {
1892 return internal::ReturnRoundRobinAction<T>(std::move(vals));
1895 // Creates an action that returns an element of `vals`. Calling this action will
1896 // repeatedly return the next value from `vals` until it reaches the end and
1897 // will restart from the beginning.
1898 template <typename T>
1899 internal::ReturnRoundRobinAction<T> ReturnRoundRobin(
1900 std::initializer_list<T> vals) {
1901 return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));
1904 // Creates an action that does the default action for the give mock function.
1905 inline internal::DoDefaultAction DoDefault() {
1906 return internal::DoDefaultAction();
1909 // Creates an action that sets the variable pointed by the N-th
1910 // (0-based) function argument to 'value'.
1911 template <size_t N, typename T>
1912 internal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {
1913 return {std::move(value)};
1916 // The following version is DEPRECATED.
1917 template <size_t N, typename T>
1918 internal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {
1919 return {std::move(value)};
1922 // Creates an action that sets a pointer referent to a given value.
1923 template <typename T1, typename T2>
1924 PolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {
1925 return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));
1928 #if !GTEST_OS_WINDOWS_MOBILE
1930 // Creates an action that sets errno and returns the appropriate error.
1931 template <typename T>
1932 PolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(
1933 int errval, T result) {
1934 return MakePolymorphicAction(
1935 internal::SetErrnoAndReturnAction<T>(errval, result));
1938 #endif // !GTEST_OS_WINDOWS_MOBILE
1940 // Various overloads for Invoke().
1943 // Actions can now be implicitly constructed from callables. No need to create
1945 // This function exists for backwards compatibility.
1946 template <typename FunctionImpl>
1947 typename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {
1948 return std::forward<FunctionImpl>(function_impl);
1951 // Creates an action that invokes the given method on the given object
1952 // with the mock function's arguments.
1953 template <class Class, typename MethodPtr>
1954 internal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,
1955 MethodPtr method_ptr) {
1956 return {obj_ptr, method_ptr};
1959 // Creates an action that invokes 'function_impl' with no argument.
1960 template <typename FunctionImpl>
1961 internal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>
1962 InvokeWithoutArgs(FunctionImpl function_impl) {
1963 return {std::move(function_impl)};
1966 // Creates an action that invokes the given method on the given object
1967 // with no argument.
1968 template <class Class, typename MethodPtr>
1969 internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(
1970 Class* obj_ptr, MethodPtr method_ptr) {
1971 return {obj_ptr, method_ptr};
1974 // Creates an action that performs an_action and throws away its
1975 // result. In other words, it changes the return type of an_action to
1976 // void. an_action MUST NOT return void, or the code won't compile.
1977 template <typename A>
1978 inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {
1979 return internal::IgnoreResultAction<A>(an_action);
1982 // Creates a reference wrapper for the given L-value. If necessary,
1983 // you can explicitly specify the type of the reference. For example,
1984 // suppose 'derived' is an object of type Derived, ByRef(derived)
1985 // would wrap a Derived&. If you want to wrap a const Base& instead,
1986 // where Base is a base class of Derived, just write:
1988 // ByRef<const Base>(derived)
1990 // N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.
1991 // However, it may still be used for consistency with ByMove().
1992 template <typename T>
1993 inline ::std::reference_wrapper<T> ByRef(T& l_value) { // NOLINT
1994 return ::std::reference_wrapper<T>(l_value);
1997 // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new
1998 // instance of type T, constructed on the heap with constructor arguments
1999 // a1, a2, ..., and a_k. The caller assumes ownership of the returned value.
2000 template <typename T, typename... Params>
2001 internal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(
2002 Params&&... params) {
2003 return {std::forward_as_tuple(std::forward<Params>(params)...)};
2006 // Action ReturnArg<k>() returns the k-th argument of the mock function.
2008 internal::ReturnArgAction<k> ReturnArg() {
2012 // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the
2013 // mock function to *pointer.
2014 template <size_t k, typename Ptr>
2015 internal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {
2019 // Action SaveArgPointee<k>(pointer) saves the value pointed to
2020 // by the k-th (0-based) argument of the mock function to *pointer.
2021 template <size_t k, typename Ptr>
2022 internal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {
2026 // Action SetArgReferee<k>(value) assigns 'value' to the variable
2027 // referenced by the k-th (0-based) argument of the mock function.
2028 template <size_t k, typename T>
2029 internal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(
2031 return {std::forward<T>(value)};
2034 // Action SetArrayArgument<k>(first, last) copies the elements in
2035 // source range [first, last) to the array pointed to by the k-th
2036 // (0-based) argument, which can be either a pointer or an
2037 // iterator. The action does not take ownership of the elements in the
2039 template <size_t k, typename I1, typename I2>
2040 internal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,
2042 return {first, last};
2045 // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock
2048 internal::DeleteArgAction<k> DeleteArg() {
2052 // This action returns the value pointed to by 'pointer'.
2053 template <typename Ptr>
2054 internal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {
2058 // Action Throw(exception) can be used in a mock function of any type
2059 // to throw the given exception. Any copyable value can be thrown.
2060 #if GTEST_HAS_EXCEPTIONS
2061 template <typename T>
2062 internal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {
2063 return {std::forward<T>(exception)};
2065 #endif // GTEST_HAS_EXCEPTIONS
2067 namespace internal {
2069 // A macro from the ACTION* family (defined later in gmock-generated-actions.h)
2070 // defines an action that can be used in a mock function. Typically,
2071 // these actions only care about a subset of the arguments of the mock
2072 // function. For example, if such an action only uses the second
2073 // argument, it can be used in any mock function that takes >= 2
2074 // arguments where the type of the second argument is compatible.
2076 // Therefore, the action implementation must be prepared to take more
2077 // arguments than it needs. The ExcessiveArg type is used to
2078 // represent those excessive arguments. In order to keep the compiler
2079 // error messages tractable, we define it in the testing namespace
2080 // instead of testing::internal. However, this is an INTERNAL TYPE
2081 // and subject to change without notice, so a user MUST NOT USE THIS
2083 struct ExcessiveArg {};
2085 // Builds an implementation of an Action<> for some particular signature, using
2086 // a class defined by an ACTION* macro.
2087 template <typename F, typename Impl>
2090 template <typename Impl>
2093 // Allows each copy of the Action<> to get to the Impl.
2094 explicit operator const Impl&() const { return *ptr; }
2095 std::shared_ptr<Impl> ptr;
2097 using type = typename std::conditional<std::is_constructible<Impl>::value,
2098 Impl, Holder>::type;
2101 template <typename R, typename... Args, typename Impl>
2102 struct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {
2103 using Base = typename ImplBase<Impl>::type;
2104 using function_type = R(Args...);
2105 using args_type = std::tuple<Args...>;
2107 ActionImpl() = default; // Only defined if appropriate for Base.
2108 explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {}
2110 R operator()(Args&&... arg) const {
2111 static constexpr size_t kMaxArgs =
2112 sizeof...(Args) <= 10 ? sizeof...(Args) : 10;
2113 return Apply(MakeIndexSequence<kMaxArgs>{},
2114 MakeIndexSequence<10 - kMaxArgs>{},
2115 args_type{std::forward<Args>(arg)...});
2118 template <std::size_t... arg_id, std::size_t... excess_id>
2119 R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,
2120 const args_type& args) const {
2121 // Impl need not be specific to the signature of action being implemented;
2122 // only the implementing function body needs to have all of the specific
2123 // types instantiated. Up to 10 of the args that are provided by the
2124 // args_type get passed, followed by a dummy of unspecified type for the
2125 // remainder up to 10 explicit args.
2126 static constexpr ExcessiveArg kExcessArg{};
2127 return static_cast<const Impl&>(*this)
2128 .template gmock_PerformImpl<
2129 /*function_type=*/function_type, /*return_type=*/R,
2130 /*args_type=*/args_type,
2132 typename std::tuple_element<arg_id, args_type>::type...>(
2133 /*args=*/args, std::get<arg_id>(args)...,
2134 ((void)excess_id, kExcessArg)...);
2138 // Stores a default-constructed Impl as part of the Action<>'s
2139 // std::function<>. The Impl should be trivial to copy.
2140 template <typename F, typename Impl>
2141 ::testing::Action<F> MakeAction() {
2142 return ::testing::Action<F>(ActionImpl<F, Impl>());
2145 // Stores just the one given instance of Impl.
2146 template <typename F, typename Impl>
2147 ::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {
2148 return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));
2151 #define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \
2152 , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_
2153 #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_ \
2154 const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \
2155 GMOCK_INTERNAL_ARG_UNUSED, , 10)
2157 #define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i
2158 #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \
2159 const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)
2161 #define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type
2162 #define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \
2163 GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))
2165 #define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type
2166 #define GMOCK_ACTION_TYPENAME_PARAMS_(params) \
2167 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))
2169 #define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type
2170 #define GMOCK_ACTION_TYPE_PARAMS_(params) \
2171 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))
2173 #define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \
2174 , param##_type gmock_p##i
2175 #define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \
2176 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))
2178 #define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \
2179 , std::forward<param##_type>(gmock_p##i)
2180 #define GMOCK_ACTION_GVALUE_PARAMS_(params) \
2181 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))
2183 #define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \
2184 , param(::std::forward<param##_type>(gmock_p##i))
2185 #define GMOCK_ACTION_INIT_PARAMS_(params) \
2186 GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))
2188 #define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;
2189 #define GMOCK_ACTION_FIELD_PARAMS_(params) \
2190 GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)
2192 #define GMOCK_INTERNAL_ACTION(name, full_name, params) \
2193 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2196 explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
2197 : impl_(std::make_shared<gmock_Impl>( \
2198 GMOCK_ACTION_GVALUE_PARAMS_(params))) {} \
2199 full_name(const full_name&) = default; \
2200 full_name(full_name&&) noexcept = default; \
2201 template <typename F> \
2202 operator ::testing::Action<F>() const { \
2203 return ::testing::internal::MakeAction<F>(impl_); \
2207 class gmock_Impl { \
2209 explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) \
2210 : GMOCK_ACTION_INIT_PARAMS_(params) {} \
2211 template <typename function_type, typename return_type, \
2212 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2213 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
2214 GMOCK_ACTION_FIELD_PARAMS_(params) \
2216 std::shared_ptr<const gmock_Impl> impl_; \
2218 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2219 inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
2220 GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_; \
2221 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2222 inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name( \
2223 GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) { \
2224 return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>( \
2225 GMOCK_ACTION_GVALUE_PARAMS_(params)); \
2227 template <GMOCK_ACTION_TYPENAME_PARAMS_(params)> \
2228 template <typename function_type, typename return_type, typename args_type, \
2229 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2231 full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \
2232 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2234 } // namespace internal
2236 // Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.
2237 #define ACTION(name) \
2238 class name##Action { \
2240 explicit name##Action() noexcept {} \
2241 name##Action(const name##Action&) noexcept {} \
2242 template <typename F> \
2243 operator ::testing::Action<F>() const { \
2244 return ::testing::internal::MakeAction<F, gmock_Impl>(); \
2248 class gmock_Impl { \
2250 template <typename function_type, typename return_type, \
2251 typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2252 return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \
2255 inline name##Action name() GTEST_MUST_USE_RESULT_; \
2256 inline name##Action name() { return name##Action(); } \
2257 template <typename function_type, typename return_type, typename args_type, \
2258 GMOCK_ACTION_TEMPLATE_ARGS_NAMES_> \
2259 return_type name##Action::gmock_Impl::gmock_PerformImpl( \
2260 GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const
2262 #define ACTION_P(name, ...) \
2263 GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))
2265 #define ACTION_P2(name, ...) \
2266 GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))
2268 #define ACTION_P3(name, ...) \
2269 GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))
2271 #define ACTION_P4(name, ...) \
2272 GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))
2274 #define ACTION_P5(name, ...) \
2275 GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))
2277 #define ACTION_P6(name, ...) \
2278 GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))
2280 #define ACTION_P7(name, ...) \
2281 GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))
2283 #define ACTION_P8(name, ...) \
2284 GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))
2286 #define ACTION_P9(name, ...) \
2287 GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))
2289 #define ACTION_P10(name, ...) \
2290 GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))
2292 } // namespace testing
2295 #pragma warning(pop)
2298 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_