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 // This file tests the built-in actions.
34 // Silence C4100 (unreferenced formal parameter) and C4503 (decorated name
35 // length exceeded) for MSVC.
38 #pragma warning(disable : 4100)
39 #pragma warning(disable : 4503)
41 // and silence C4800 (C4800: 'int *const ': forcing value
42 // to bool 'true' or 'false') for MSVC 15
43 #pragma warning(disable : 4800)
47 #include "gmock/gmock-actions.h"
54 #include <type_traits>
57 #include "gmock/gmock.h"
58 #include "gmock/internal/gmock-port.h"
59 #include "gtest/gtest-spi.h"
60 #include "gtest/gtest.h"
65 using ::testing::internal::BuiltInDefaultValue;
67 TEST(TypeTraits, Negation) {
68 // Direct use with std types.
69 static_assert(std::is_base_of<std::false_type,
70 internal::negation<std::true_type>>::value,
73 static_assert(std::is_base_of<std::true_type,
74 internal::negation<std::false_type>>::value,
77 // With other types that fit the requirement of a value member that is
78 // convertible to bool.
79 static_assert(std::is_base_of<
81 internal::negation<std::integral_constant<int, 0>>>::value,
84 static_assert(std::is_base_of<
86 internal::negation<std::integral_constant<int, 1>>>::value,
89 static_assert(std::is_base_of<
91 internal::negation<std::integral_constant<int, -1>>>::value,
95 // Weird false/true types that aren't actually bool constants (but should still
96 // be legal according to [meta.logical] because `bool(T::value)` is valid), are
97 // distinct from std::false_type and std::true_type, and are distinct from other
98 // instantiations of the same template.
100 // These let us check finicky details mandated by the standard like
101 // "std::conjunction should evaluate to a type that inherits from the first
104 struct MyFalse : std::integral_constant<int, 0> {};
107 struct MyTrue : std::integral_constant<int, -1> {};
109 TEST(TypeTraits, Conjunction) {
110 // Base case: always true.
111 static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value,
114 // One predicate: inherits from that predicate, regardless of value.
116 std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value,
120 std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, "");
122 // Multiple predicates, with at least one false: inherits from that one.
124 std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
129 std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
133 // Short circuiting: in the case above, additional predicates need not even
134 // define a value member.
137 std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,
141 // All predicates true: inherits from the last.
143 std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>,
148 TEST(TypeTraits, Disjunction) {
149 // Base case: always false.
151 std::is_base_of<std::false_type, internal::disjunction<>>::value, "");
153 // One predicate: inherits from that predicate, regardless of value.
155 std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value,
159 std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, "");
161 // Multiple predicates, with at least one true: inherits from that one.
163 std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
168 std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
172 // Short circuiting: in the case above, additional predicates need not even
173 // define a value member.
176 std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,
180 // All predicates false: inherits from the last.
182 std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>,
187 TEST(TypeTraits, IsInvocableRV) {
189 int operator()() const { return 0; }
190 void operator()(int) & {}
191 std::string operator()(int) && { return ""; };
194 // The first overload is callable for const and non-const rvalues and lvalues.
195 // It can be used to obtain an int, cv void, or anything int is convertible
197 static_assert(internal::is_callable_r<int, C>::value, "");
198 static_assert(internal::is_callable_r<int, C&>::value, "");
199 static_assert(internal::is_callable_r<int, const C>::value, "");
200 static_assert(internal::is_callable_r<int, const C&>::value, "");
202 static_assert(internal::is_callable_r<void, C>::value, "");
203 static_assert(internal::is_callable_r<const volatile void, C>::value, "");
204 static_assert(internal::is_callable_r<char, C>::value, "");
206 // It's possible to provide an int. If it's given to an lvalue, the result is
207 // void. Otherwise it is std::string (which is also treated as allowed for a
208 // void result type).
209 static_assert(internal::is_callable_r<void, C&, int>::value, "");
210 static_assert(!internal::is_callable_r<int, C&, int>::value, "");
211 static_assert(!internal::is_callable_r<std::string, C&, int>::value, "");
212 static_assert(!internal::is_callable_r<void, const C&, int>::value, "");
214 static_assert(internal::is_callable_r<std::string, C, int>::value, "");
215 static_assert(internal::is_callable_r<void, C, int>::value, "");
216 static_assert(!internal::is_callable_r<int, C, int>::value, "");
218 // It's not possible to provide other arguments.
219 static_assert(!internal::is_callable_r<void, C, std::string>::value, "");
220 static_assert(!internal::is_callable_r<void, C, int, int>::value, "");
222 // In C++17 and above, where it's guaranteed that functions can return
223 // non-moveable objects, everything should work fine for non-moveable rsult
225 #if defined(__cplusplus) && __cplusplus >= 201703L
228 NonMoveable() = default;
229 NonMoveable(NonMoveable&&) = delete;
232 static_assert(!std::is_move_constructible_v<NonMoveable>);
235 NonMoveable operator()() { return NonMoveable(); }
238 static_assert(internal::is_callable_r<NonMoveable, Callable>::value);
239 static_assert(internal::is_callable_r<void, Callable>::value);
241 internal::is_callable_r<const volatile void, Callable>::value);
243 static_assert(!internal::is_callable_r<int, Callable>::value);
244 static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);
246 #endif // C++17 and above
248 // Nothing should choke when we try to call other arguments besides directly
249 // callable objects, but they should not show up as callable.
250 static_assert(!internal::is_callable_r<void, int>::value, "");
251 static_assert(!internal::is_callable_r<void, void (C::*)()>::value, "");
252 static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, "");
255 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
256 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
257 EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);
258 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);
259 EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);
262 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
263 TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
264 EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
265 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
266 EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
269 // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
270 // built-in numeric type.
271 TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
272 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
273 EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
274 EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
275 #if GMOCK_WCHAR_T_IS_NATIVE_
276 #if !defined(__WCHAR_UNSIGNED__)
277 EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
279 EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
282 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
283 EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
284 EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
285 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
286 EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
287 EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
288 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
289 EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
290 EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
291 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get()); // NOLINT
292 EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get()); // NOLINT
293 EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get()); // NOLINT
294 EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
295 EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
298 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
299 // built-in numeric type.
300 TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
301 EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
302 EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
303 EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
304 #if GMOCK_WCHAR_T_IS_NATIVE_
305 EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
307 EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT
308 EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT
309 EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT
310 EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
311 EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
312 EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
313 EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
314 EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
315 EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
316 EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists()); // NOLINT
317 EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists()); // NOLINT
318 EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists()); // NOLINT
319 EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
320 EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
323 // Tests that BuiltInDefaultValue<bool>::Get() returns false.
324 TEST(BuiltInDefaultValueTest, IsFalseForBool) {
325 EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
328 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
329 TEST(BuiltInDefaultValueTest, BoolExists) {
330 EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
333 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
335 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
336 EXPECT_EQ("", BuiltInDefaultValue<::std::string>::Get());
339 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
341 TEST(BuiltInDefaultValueTest, ExistsForString) {
342 EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists());
345 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
346 // value as BuiltInDefaultValue<T>::Get() does.
347 TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
348 EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
349 EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
350 EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);
351 EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
354 // A type that's default constructible.
355 class MyDefaultConstructible {
357 MyDefaultConstructible() : value_(42) {}
359 int value() const { return value_; }
365 // A type that's not default constructible.
366 class MyNonDefaultConstructible {
368 // Does not have a default ctor.
369 explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
371 int value() const { return value_; }
377 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
378 EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
381 TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
382 EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
385 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
386 EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
389 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
390 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
391 EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, "");
392 EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, "");
395 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
396 EXPECT_DEATH_IF_SUPPORTED(
397 { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, "");
400 // Tests that DefaultValue<T>::IsSet() is false initially.
401 TEST(DefaultValueTest, IsInitiallyUnset) {
402 EXPECT_FALSE(DefaultValue<int>::IsSet());
403 EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
404 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
407 // Tests that DefaultValue<T> can be set and then unset.
408 TEST(DefaultValueTest, CanBeSetAndUnset) {
409 EXPECT_TRUE(DefaultValue<int>::Exists());
410 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
412 DefaultValue<int>::Set(1);
413 DefaultValue<const MyNonDefaultConstructible>::Set(
414 MyNonDefaultConstructible(42));
416 EXPECT_EQ(1, DefaultValue<int>::Get());
417 EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
419 EXPECT_TRUE(DefaultValue<int>::Exists());
420 EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
422 DefaultValue<int>::Clear();
423 DefaultValue<const MyNonDefaultConstructible>::Clear();
425 EXPECT_FALSE(DefaultValue<int>::IsSet());
426 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
428 EXPECT_TRUE(DefaultValue<int>::Exists());
429 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
432 // Tests that DefaultValue<T>::Get() returns the
433 // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
435 TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
436 EXPECT_FALSE(DefaultValue<int>::IsSet());
437 EXPECT_TRUE(DefaultValue<int>::Exists());
438 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
439 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
441 EXPECT_EQ(0, DefaultValue<int>::Get());
443 EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
447 TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
448 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
449 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
450 DefaultValue<std::unique_ptr<int>>::SetFactory(
451 [] { return std::unique_ptr<int>(new int(42)); });
452 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
453 std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
457 // Tests that DefaultValue<void>::Get() returns void.
458 TEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }
460 // Tests using DefaultValue with a reference type.
462 // Tests that DefaultValue<T&>::IsSet() is false initially.
463 TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
464 EXPECT_FALSE(DefaultValue<int&>::IsSet());
465 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
466 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
469 // Tests that DefaultValue<T&>::Exists is false initiallly.
470 TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
471 EXPECT_FALSE(DefaultValue<int&>::Exists());
472 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
473 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
476 // Tests that DefaultValue<T&> can be set and then unset.
477 TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
479 DefaultValue<const int&>::Set(n);
480 MyNonDefaultConstructible x(42);
481 DefaultValue<MyNonDefaultConstructible&>::Set(x);
483 EXPECT_TRUE(DefaultValue<const int&>::Exists());
484 EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
486 EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
487 EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
489 DefaultValue<const int&>::Clear();
490 DefaultValue<MyNonDefaultConstructible&>::Clear();
492 EXPECT_FALSE(DefaultValue<const int&>::Exists());
493 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
495 EXPECT_FALSE(DefaultValue<const int&>::IsSet());
496 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
499 // Tests that DefaultValue<T&>::Get() returns the
500 // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
502 TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
503 EXPECT_FALSE(DefaultValue<int&>::IsSet());
504 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
506 EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, "");
507 EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },
511 // Tests that ActionInterface can be implemented by defining the
514 typedef int MyGlobalFunction(bool, int);
516 class MyActionImpl : public ActionInterface<MyGlobalFunction> {
518 int Perform(const std::tuple<bool, int>& args) override {
519 return std::get<0>(args) ? std::get<1>(args) : 0;
523 TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
524 MyActionImpl my_action_impl;
525 (void)my_action_impl;
528 TEST(ActionInterfaceTest, MakeAction) {
529 Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
531 // When exercising the Perform() method of Action<F>, we must pass
532 // it a tuple whose size and type are compatible with F's argument
533 // types. For example, if F is int(), then Perform() takes a
534 // 0-tuple; if F is void(bool, int), then Perform() takes a
535 // std::tuple<bool, int>, and so on.
536 EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
539 // Tests that Action<F> can be constructed from a pointer to
540 // ActionInterface<F>.
541 TEST(ActionTest, CanBeConstructedFromActionInterface) {
542 Action<MyGlobalFunction> action(new MyActionImpl);
545 // Tests that Action<F> delegates actual work to ActionInterface<F>.
546 TEST(ActionTest, DelegatesWorkToActionInterface) {
547 const Action<MyGlobalFunction> action(new MyActionImpl);
549 EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
550 EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));
553 // Tests that Action<F> can be copied.
554 TEST(ActionTest, IsCopyable) {
555 Action<MyGlobalFunction> a1(new MyActionImpl);
556 Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.
558 // a1 should continue to work after being copied from.
559 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
560 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
562 // a2 should work like the action it was copied from.
563 EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
564 EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
566 a2 = a1; // Tests the assignment operator.
568 // a1 should continue to work after being copied from.
569 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
570 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
572 // a2 should work like the action it was copied from.
573 EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
574 EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
577 // Tests that an Action<From> object can be converted to a
578 // compatible Action<To> object.
580 class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
582 bool Perform(const std::tuple<int>& arg) override {
583 return std::get<0>(arg) != 0;
587 TEST(ActionTest, CanBeConvertedToOtherActionType) {
588 const Action<bool(int)> a1(new IsNotZero); // NOLINT
589 const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT
590 EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
591 EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));
594 // The following two classes are for testing MakePolymorphicAction().
596 // Implements a polymorphic action that returns the second of the
597 // arguments it receives.
598 class ReturnSecondArgumentAction {
600 // We want to verify that MakePolymorphicAction() can work with a
601 // polymorphic action whose Perform() method template is either
602 // const or not. This lets us verify the non-const case.
603 template <typename Result, typename ArgumentTuple>
604 Result Perform(const ArgumentTuple& args) {
605 return std::get<1>(args);
609 // Implements a polymorphic action that can be used in a nullary
610 // function to return 0.
611 class ReturnZeroFromNullaryFunctionAction {
613 // For testing that MakePolymorphicAction() works when the
614 // implementation class' Perform() method template takes only one
615 // template parameter.
617 // We want to verify that MakePolymorphicAction() can work with a
618 // polymorphic action whose Perform() method template is either
619 // const or not. This lets us verify the const case.
620 template <typename Result>
621 Result Perform(const std::tuple<>&) const {
626 // These functions verify that MakePolymorphicAction() returns a
627 // PolymorphicAction<T> where T is the argument's type.
629 PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
630 return MakePolymorphicAction(ReturnSecondArgumentAction());
633 PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
634 ReturnZeroFromNullaryFunction() {
635 return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
638 // Tests that MakePolymorphicAction() turns a polymorphic action
639 // implementation class into a polymorphic action.
640 TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
641 Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT
642 EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));
645 // Tests that MakePolymorphicAction() works when the implementation
646 // class' Perform() method template has only one template parameter.
647 TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
648 Action<int()> a1 = ReturnZeroFromNullaryFunction();
649 EXPECT_EQ(0, a1.Perform(std::make_tuple()));
651 Action<void*()> a2 = ReturnZeroFromNullaryFunction();
652 EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);
655 // Tests that Return() works as an action for void-returning
657 TEST(ReturnTest, WorksForVoid) {
658 const Action<void(int)> ret = Return(); // NOLINT
659 return ret.Perform(std::make_tuple(1));
662 // Tests that Return(v) returns v.
663 TEST(ReturnTest, ReturnsGivenValue) {
664 Action<int()> ret = Return(1); // NOLINT
665 EXPECT_EQ(1, ret.Perform(std::make_tuple()));
668 EXPECT_EQ(-5, ret.Perform(std::make_tuple()));
671 // Tests that Return("string literal") works.
672 TEST(ReturnTest, AcceptsStringLiteral) {
673 Action<const char*()> a1 = Return("Hello");
674 EXPECT_STREQ("Hello", a1.Perform(std::make_tuple()));
676 Action<std::string()> a2 = Return("world");
677 EXPECT_EQ("world", a2.Perform(std::make_tuple()));
680 // Return(x) should work fine when the mock function's return type is a
681 // reference-like wrapper for decltype(x), as when x is a std::string and the
682 // mock function returns std::string_view.
683 TEST(ReturnTest, SupportsReferenceLikeReturnType) {
684 // A reference wrapper for std::vector<int>, implicitly convertible from it.
686 const std::vector<int>* v;
687 Result(const std::vector<int>& v) : v(&v) {} // NOLINT
690 // Set up an action for a mock function that returns the reference wrapper
691 // type, initializing it with an actual vector.
693 // The returned wrapper should be initialized with a copy of that vector
694 // that's embedded within the action itself (which should stay alive as long
695 // as the mock object is alive), rather than e.g. a reference to the temporary
696 // we feed to Return. This should work fine both for WillOnce and
698 MockFunction<Result()> mock;
699 EXPECT_CALL(mock, Call)
700 .WillOnce(Return(std::vector<int>{17, 19, 23}))
701 .WillRepeatedly(Return(std::vector<int>{29, 31, 37}));
703 EXPECT_THAT(mock.AsStdFunction()(),
704 Field(&Result::v, Pointee(ElementsAre(17, 19, 23))));
706 EXPECT_THAT(mock.AsStdFunction()(),
707 Field(&Result::v, Pointee(ElementsAre(29, 31, 37))));
710 TEST(ReturnTest, PrefersConversionOperator) {
711 // Define types In and Out such that:
713 // * In is implicitly convertible to Out.
714 // * Out also has an explicit constructor from In.
720 explicit Out(const int x) : x(x) {}
721 explicit Out(const In&) : x(0) {}
725 operator Out() const { return Out{19}; } // NOLINT
728 // Assumption check: the C++ language rules are such that a function that
729 // returns Out which uses In a return statement will use the implicit
730 // conversion path rather than the explicit constructor.
731 EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19));
733 // Return should work the same way: if the mock function's return type is Out
734 // and we feed Return an In value, then the Out should be created through the
735 // implicit conversion path rather than the explicit constructor.
736 MockFunction<Out()> mock;
737 EXPECT_CALL(mock, Call).WillOnce(Return(In()));
738 EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19));
741 // It should be possible to use Return(R) with a mock function result type U
742 // that is convertible from const R& but *not* R (such as
743 // std::reference_wrapper). This should work for both WillOnce and
745 TEST(ReturnTest, ConversionRequiresConstLvalueReference) {
747 using U = std::reference_wrapper<const int>;
749 static_assert(std::is_convertible<const R&, U>::value, "");
750 static_assert(!std::is_convertible<R, U>::value, "");
752 MockFunction<U()> mock;
753 EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19));
755 EXPECT_EQ(17, mock.AsStdFunction()());
756 EXPECT_EQ(19, mock.AsStdFunction()());
759 // Return(x) should not be usable with a mock function result type that's
760 // implicitly convertible from decltype(x) but requires a non-const lvalue
761 // reference to the input. It doesn't make sense for the conversion operator to
763 TEST(ReturnTest, ConversionRequiresMutableLvalueReference) {
764 // Set up a type that is implicitly convertible from std::string&, but not
765 // std::string&& or `const std::string&`.
767 // Avoid asserting about conversion from std::string on MSVC, which seems to
768 // implement std::is_convertible incorrectly in this case.
770 S(std::string&) {} // NOLINT
773 static_assert(std::is_convertible<std::string&, S>::value, "");
775 static_assert(!std::is_convertible<std::string&&, S>::value, "");
777 static_assert(!std::is_convertible<const std::string&, S>::value, "");
779 // It shouldn't be possible to use the result of Return(std::string) in a
780 // context where an S is needed.
782 // Here too we disable the assertion for MSVC, since its incorrect
783 // implementation of is_convertible causes our SFINAE to be wrong.
784 using RA = decltype(Return(std::string()));
786 static_assert(!std::is_convertible<RA, Action<S()>>::value, "");
788 static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, "");
792 TEST(ReturnTest, MoveOnlyResultType) {
793 // Return should support move-only result types when used with WillOnce.
795 MockFunction<std::unique_ptr<int>()> mock;
796 EXPECT_CALL(mock, Call)
798 .WillOnce(Return(std::unique_ptr<int>(new int(17))));
800 EXPECT_THAT(mock.AsStdFunction()(), Pointee(17));
803 // The result of Return should not be convertible to Action (so it can't be
804 // used with WillRepeatedly).
805 static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())),
806 Action<std::unique_ptr<int>()>>::value,
810 // Tests that Return(v) is covaraint.
813 bool operator==(const Base&) { return true; }
816 struct Derived : public Base {
817 bool operator==(const Derived&) { return true; }
820 TEST(ReturnTest, IsCovariant) {
823 Action<Base*()> ret = Return(&base);
824 EXPECT_EQ(&base, ret.Perform(std::make_tuple()));
826 ret = Return(&derived);
827 EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));
830 // Tests that the type of the value passed into Return is converted into T
831 // when the action is cast to Action<T(...)> rather than when the action is
832 // performed. See comments on testing::internal::ReturnAction in
833 // gmock-actions.h for more information.
836 explicit FromType(bool* is_converted) : converted_(is_converted) {}
837 bool* converted() const { return converted_; }
840 bool* const converted_;
845 // Must allow implicit conversion due to use in ImplicitCast_<T>.
846 ToType(const FromType& x) { *x.converted() = true; } // NOLINT
849 TEST(ReturnTest, ConvertsArgumentWhenConverted) {
850 bool converted = false;
851 FromType x(&converted);
852 Action<ToType()> action(Return(x));
853 EXPECT_TRUE(converted) << "Return must convert its argument in its own "
854 << "conversion operator.";
856 action.Perform(std::tuple<>());
857 EXPECT_FALSE(converted) << "Action must NOT convert its argument "
858 << "when performed.";
861 // Tests that ReturnNull() returns NULL in a pointer-returning function.
862 TEST(ReturnNullTest, WorksInPointerReturningFunction) {
863 const Action<int*()> a1 = ReturnNull();
864 EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
866 const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT
867 EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);
870 // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
872 TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
873 const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
874 EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
876 const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
877 EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr);
880 // Tests that ReturnRef(v) works for reference types.
881 TEST(ReturnRefTest, WorksForReference) {
883 const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT
885 EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));
888 // Tests that ReturnRef(v) is covariant.
889 TEST(ReturnRefTest, IsCovariant) {
892 Action<Base&()> a = ReturnRef(base);
893 EXPECT_EQ(&base, &a.Perform(std::make_tuple()));
895 a = ReturnRef(derived);
896 EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
899 template <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>
900 bool CanCallReturnRef(T&&) {
903 bool CanCallReturnRef(Unused) { return false; }
905 // Tests that ReturnRef(v) is working with non-temporaries (T&)
906 TEST(ReturnRefTest, WorksForNonTemporary) {
907 int scalar_value = 123;
908 EXPECT_TRUE(CanCallReturnRef(scalar_value));
910 std::string non_scalar_value("ABC");
911 EXPECT_TRUE(CanCallReturnRef(non_scalar_value));
913 const int const_scalar_value{321};
914 EXPECT_TRUE(CanCallReturnRef(const_scalar_value));
916 const std::string const_non_scalar_value("CBA");
917 EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));
920 // Tests that ReturnRef(v) is not working with temporaries (T&&)
921 TEST(ReturnRefTest, DoesNotWorkForTemporary) {
922 auto scalar_value = []() -> int { return 123; };
923 EXPECT_FALSE(CanCallReturnRef(scalar_value()));
925 auto non_scalar_value = []() -> std::string { return "ABC"; };
926 EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));
928 // cannot use here callable returning "const scalar type",
929 // because such const for scalar return type is ignored
930 EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));
932 auto const_non_scalar_value = []() -> const std::string { return "CBA"; };
933 EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));
936 // Tests that ReturnRefOfCopy(v) works for reference types.
937 TEST(ReturnRefOfCopyTest, WorksForReference) {
939 const Action<const int&()> ret = ReturnRefOfCopy(n);
941 EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
942 EXPECT_EQ(42, ret.Perform(std::make_tuple()));
945 EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
946 EXPECT_EQ(42, ret.Perform(std::make_tuple()));
949 // Tests that ReturnRefOfCopy(v) is covariant.
950 TEST(ReturnRefOfCopyTest, IsCovariant) {
953 Action<Base&()> a = ReturnRefOfCopy(base);
954 EXPECT_NE(&base, &a.Perform(std::make_tuple()));
956 a = ReturnRefOfCopy(derived);
957 EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
960 // Tests that ReturnRoundRobin(v) works with initializer lists
961 TEST(ReturnRoundRobinTest, WorksForInitList) {
962 Action<int()> ret = ReturnRoundRobin({1, 2, 3});
964 EXPECT_EQ(1, ret.Perform(std::make_tuple()));
965 EXPECT_EQ(2, ret.Perform(std::make_tuple()));
966 EXPECT_EQ(3, ret.Perform(std::make_tuple()));
967 EXPECT_EQ(1, ret.Perform(std::make_tuple()));
968 EXPECT_EQ(2, ret.Perform(std::make_tuple()));
969 EXPECT_EQ(3, ret.Perform(std::make_tuple()));
972 // Tests that ReturnRoundRobin(v) works with vectors
973 TEST(ReturnRoundRobinTest, WorksForVector) {
974 std::vector<double> v = {4.4, 5.5, 6.6};
975 Action<double()> ret = ReturnRoundRobin(v);
977 EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
978 EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
979 EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
980 EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));
981 EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));
982 EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));
985 // Tests that DoDefault() does the default action for the mock method.
991 MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
992 MOCK_METHOD0(Foo, MyNonDefaultConstructible());
993 MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
994 MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
995 MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
996 MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
997 MOCK_METHOD2(TakeUnique,
998 int(const std::unique_ptr<int>&, std::unique_ptr<int>));
1001 MockClass(const MockClass&) = delete;
1002 MockClass& operator=(const MockClass&) = delete;
1005 // Tests that DoDefault() returns the built-in default value for the
1006 // return type by default.
1007 TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
1009 EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
1010 EXPECT_EQ(0, mock.IntFunc(true));
1013 // Tests that DoDefault() throws (when exceptions are enabled) or aborts
1014 // the process when there is no built-in default value for the return type.
1015 TEST(DoDefaultDeathTest, DiesForUnknowType) {
1017 EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());
1018 #if GTEST_HAS_EXCEPTIONS
1019 EXPECT_ANY_THROW(mock.Foo());
1021 EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, "");
1025 // Tests that using DoDefault() inside a composite action leads to a
1028 void VoidFunc(bool /* flag */) {}
1030 TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
1032 EXPECT_CALL(mock, IntFunc(_))
1033 .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));
1035 // Ideally we should verify the error message as well. Sadly,
1036 // EXPECT_DEATH() can only capture stderr, while Google Mock's
1037 // errors are printed on stdout. Therefore we have to settle for
1038 // not verifying the message.
1039 EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, "");
1042 // Tests that DoDefault() returns the default value set by
1043 // DefaultValue<T>::Set() when it's not overridden by an ON_CALL().
1044 TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
1045 DefaultValue<int>::Set(1);
1047 EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
1048 EXPECT_EQ(1, mock.IntFunc(false));
1049 DefaultValue<int>::Clear();
1052 // Tests that DoDefault() does the action specified by ON_CALL().
1053 TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
1055 ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));
1056 EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());
1057 EXPECT_EQ(2, mock.IntFunc(false));
1060 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
1061 TEST(DoDefaultTest, CannotBeUsedInOnCall) {
1063 EXPECT_NONFATAL_FAILURE(
1065 ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault());
1067 "DoDefault() cannot be used in ON_CALL()");
1070 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
1071 // the N-th (0-based) argument to v.
1072 TEST(SetArgPointeeTest, SetsTheNthPointee) {
1073 typedef void MyFunction(bool, int*, char*);
1074 Action<MyFunction> a = SetArgPointee<1>(2);
1078 a.Perform(std::make_tuple(true, &n, &ch));
1080 EXPECT_EQ('\0', ch);
1082 a = SetArgPointee<2>('a');
1085 a.Perform(std::make_tuple(true, &n, &ch));
1090 // Tests that SetArgPointee<N>() accepts a string literal.
1091 TEST(SetArgPointeeTest, AcceptsStringLiteral) {
1092 typedef void MyFunction(std::string*, const char**);
1093 Action<MyFunction> a = SetArgPointee<0>("hi");
1095 const char* ptr = nullptr;
1096 a.Perform(std::make_tuple(&str, &ptr));
1097 EXPECT_EQ("hi", str);
1098 EXPECT_TRUE(ptr == nullptr);
1100 a = SetArgPointee<1>("world");
1102 a.Perform(std::make_tuple(&str, &ptr));
1104 EXPECT_STREQ("world", ptr);
1107 TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
1108 typedef void MyFunction(const wchar_t**);
1109 Action<MyFunction> a = SetArgPointee<0>(L"world");
1110 const wchar_t* ptr = nullptr;
1111 a.Perform(std::make_tuple(&ptr));
1112 EXPECT_STREQ(L"world", ptr);
1114 #if GTEST_HAS_STD_WSTRING
1116 typedef void MyStringFunction(std::wstring*);
1117 Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
1118 std::wstring str = L"";
1119 a2.Perform(std::make_tuple(&str));
1120 EXPECT_EQ(L"world", str);
1125 // Tests that SetArgPointee<N>() accepts a char pointer.
1126 TEST(SetArgPointeeTest, AcceptsCharPointer) {
1127 typedef void MyFunction(bool, std::string*, const char**);
1128 const char* const hi = "hi";
1129 Action<MyFunction> a = SetArgPointee<1>(hi);
1131 const char* ptr = nullptr;
1132 a.Perform(std::make_tuple(true, &str, &ptr));
1133 EXPECT_EQ("hi", str);
1134 EXPECT_TRUE(ptr == nullptr);
1136 char world_array[] = "world";
1137 char* const world = world_array;
1138 a = SetArgPointee<2>(world);
1140 a.Perform(std::make_tuple(true, &str, &ptr));
1142 EXPECT_EQ(world, ptr);
1145 TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
1146 typedef void MyFunction(bool, const wchar_t**);
1147 const wchar_t* const hi = L"hi";
1148 Action<MyFunction> a = SetArgPointee<1>(hi);
1149 const wchar_t* ptr = nullptr;
1150 a.Perform(std::make_tuple(true, &ptr));
1153 #if GTEST_HAS_STD_WSTRING
1155 typedef void MyStringFunction(bool, std::wstring*);
1156 wchar_t world_array[] = L"world";
1157 wchar_t* const world = world_array;
1158 Action<MyStringFunction> a2 = SetArgPointee<1>(world);
1160 a2.Perform(std::make_tuple(true, &str));
1161 EXPECT_EQ(world_array, str);
1165 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
1166 // the N-th (0-based) argument to v.
1167 TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
1168 typedef void MyFunction(bool, int*, char*);
1169 Action<MyFunction> a = SetArgumentPointee<1>(2);
1173 a.Perform(std::make_tuple(true, &n, &ch));
1175 EXPECT_EQ('\0', ch);
1177 a = SetArgumentPointee<2>('a');
1180 a.Perform(std::make_tuple(true, &n, &ch));
1185 // Sample functions and functors for testing Invoke() and etc.
1186 int Nullary() { return 1; }
1188 class NullaryFunctor {
1190 int operator()() { return 2; }
1193 bool g_done = false;
1194 void VoidNullary() { g_done = true; }
1196 class VoidNullaryFunctor {
1198 void operator()() { g_done = true; }
1201 short Short(short n) { return n; } // NOLINT
1202 char Char(char ch) { return ch; }
1204 const char* CharPtr(const char* s) { return s; }
1206 bool Unary(int x) { return x < 0; }
1208 const char* Binary(const char* input, short n) { return input + n; } // NOLINT
1210 void VoidBinary(int, char) { g_done = true; }
1212 int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
1214 int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
1218 Foo() : value_(123) {}
1220 int Nullary() const { return value_; }
1226 // Tests InvokeWithoutArgs(function).
1227 TEST(InvokeWithoutArgsTest, Function) {
1228 // As an action that takes one argument.
1229 Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT
1230 EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
1232 // As an action that takes two arguments.
1233 Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT
1234 EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));
1236 // As an action that returns void.
1237 Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT
1239 a3.Perform(std::make_tuple(1));
1240 EXPECT_TRUE(g_done);
1243 // Tests InvokeWithoutArgs(functor).
1244 TEST(InvokeWithoutArgsTest, Functor) {
1245 // As an action that takes no argument.
1246 Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT
1247 EXPECT_EQ(2, a.Perform(std::make_tuple()));
1249 // As an action that takes three arguments.
1250 Action<int(int, double, char)> a2 = // NOLINT
1251 InvokeWithoutArgs(NullaryFunctor());
1252 EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));
1254 // As an action that returns void.
1255 Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
1257 a3.Perform(std::make_tuple());
1258 EXPECT_TRUE(g_done);
1261 // Tests InvokeWithoutArgs(obj_ptr, method).
1262 TEST(InvokeWithoutArgsTest, Method) {
1264 Action<int(bool, char)> a = // NOLINT
1265 InvokeWithoutArgs(&foo, &Foo::Nullary);
1266 EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));
1269 // Tests using IgnoreResult() on a polymorphic action.
1270 TEST(IgnoreResultTest, PolymorphicAction) {
1271 Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT
1272 a.Perform(std::make_tuple(1));
1275 // Tests using IgnoreResult() on a monomorphic action.
1282 TEST(IgnoreResultTest, MonomorphicAction) {
1284 Action<void()> a = IgnoreResult(Invoke(ReturnOne));
1285 a.Perform(std::make_tuple());
1286 EXPECT_TRUE(g_done);
1289 // Tests using IgnoreResult() on an action that returns a class type.
1291 MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1293 return MyNonDefaultConstructible(42);
1296 TEST(IgnoreResultTest, ActionReturningClass) {
1298 Action<void(int)> a =
1299 IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
1300 a.Perform(std::make_tuple(2));
1301 EXPECT_TRUE(g_done);
1304 TEST(AssignTest, Int) {
1306 Action<void(int)> a = Assign(&x, 5);
1307 a.Perform(std::make_tuple(0));
1311 TEST(AssignTest, String) {
1313 Action<void(void)> a = Assign(&x, "Hello, world");
1314 a.Perform(std::make_tuple());
1315 EXPECT_EQ("Hello, world", x);
1318 TEST(AssignTest, CompatibleTypes) {
1320 Action<void(int)> a = Assign(&x, 5);
1321 a.Perform(std::make_tuple(0));
1322 EXPECT_DOUBLE_EQ(5, x);
1325 // DoAll should support &&-qualified actions when used with WillOnce.
1326 TEST(DoAll, SupportsRefQualifiedActions) {
1327 struct InitialAction {
1328 void operator()(const int arg) && { EXPECT_EQ(17, arg); }
1331 struct FinalAction {
1332 int operator()() && { return 19; }
1335 MockFunction<int(int)> mock;
1336 EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{}));
1337 EXPECT_EQ(19, mock.AsStdFunction()(17));
1340 // DoAll should never provide rvalue references to the initial actions. If the
1341 // mock action itself accepts an rvalue reference or a non-scalar object by
1342 // value then the final action should receive an rvalue reference, but initial
1343 // actions should receive only lvalue references.
1344 TEST(DoAll, ProvidesLvalueReferencesToInitialActions) {
1347 // Mock action accepts by value: the initial action should be fed a const
1348 // lvalue reference, and the final action an rvalue reference.
1350 struct InitialAction {
1351 void operator()(Obj&) const { FAIL() << "Unexpected call"; }
1352 void operator()(const Obj&) const {}
1353 void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
1354 void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
1357 MockFunction<void(Obj)> mock;
1358 EXPECT_CALL(mock, Call)
1359 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
1360 .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
1362 mock.AsStdFunction()(Obj{});
1363 mock.AsStdFunction()(Obj{});
1366 // Mock action accepts by const lvalue reference: both actions should receive
1367 // a const lvalue reference.
1369 struct InitialAction {
1370 void operator()(Obj&) const { FAIL() << "Unexpected call"; }
1371 void operator()(const Obj&) const {}
1372 void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
1373 void operator()(const Obj&&) const { FAIL() << "Unexpected call"; }
1376 MockFunction<void(const Obj&)> mock;
1377 EXPECT_CALL(mock, Call)
1378 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}))
1380 DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}));
1382 mock.AsStdFunction()(Obj{});
1383 mock.AsStdFunction()(Obj{});
1386 // Mock action accepts by non-const lvalue reference: both actions should get
1387 // a non-const lvalue reference if they want them.
1389 struct InitialAction {
1390 void operator()(Obj&) const {}
1391 void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
1394 MockFunction<void(Obj&)> mock;
1395 EXPECT_CALL(mock, Call)
1396 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}))
1397 .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));
1400 mock.AsStdFunction()(obj);
1401 mock.AsStdFunction()(obj);
1404 // Mock action accepts by rvalue reference: the initial actions should receive
1405 // a non-const lvalue reference if it wants it, and the final action an rvalue
1408 struct InitialAction {
1409 void operator()(Obj&) const {}
1410 void operator()(Obj&&) const { FAIL() << "Unexpected call"; }
1413 MockFunction<void(Obj &&)> mock;
1414 EXPECT_CALL(mock, Call)
1415 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))
1416 .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
1418 mock.AsStdFunction()(Obj{});
1419 mock.AsStdFunction()(Obj{});
1422 // &&-qualified initial actions should also be allowed with WillOnce.
1424 struct InitialAction {
1425 void operator()(Obj&) && {}
1428 MockFunction<void(Obj&)> mock;
1429 EXPECT_CALL(mock, Call)
1430 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));
1433 mock.AsStdFunction()(obj);
1437 struct InitialAction {
1438 void operator()(Obj&) && {}
1441 MockFunction<void(Obj &&)> mock;
1442 EXPECT_CALL(mock, Call)
1443 .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));
1445 mock.AsStdFunction()(Obj{});
1449 // DoAll should support being used with type-erased Action objects, both through
1450 // WillOnce and WillRepeatedly.
1451 TEST(DoAll, SupportsTypeErasedActions) {
1452 // With only type-erased actions.
1453 const Action<void()> initial_action = [] {};
1454 const Action<int()> final_action = [] { return 17; };
1456 MockFunction<int()> mock;
1457 EXPECT_CALL(mock, Call)
1458 .WillOnce(DoAll(initial_action, initial_action, final_action))
1459 .WillRepeatedly(DoAll(initial_action, initial_action, final_action));
1461 EXPECT_EQ(17, mock.AsStdFunction()());
1463 // With &&-qualified and move-only final action.
1465 struct FinalAction {
1466 FinalAction() = default;
1467 FinalAction(FinalAction&&) = default;
1469 int operator()() && { return 17; }
1472 EXPECT_CALL(mock, Call)
1473 .WillOnce(DoAll(initial_action, initial_action, FinalAction{}));
1475 EXPECT_EQ(17, mock.AsStdFunction()());
1479 // Tests using WithArgs and with an action that takes 1 argument.
1480 TEST(WithArgsTest, OneArg) {
1481 Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
1482 EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
1483 EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
1486 // Tests using WithArgs with an action that takes 2 arguments.
1487 TEST(WithArgsTest, TwoArgs) {
1488 Action<const char*(const char* s, double x, short n)> a = // NOLINT
1489 WithArgs<0, 2>(Invoke(Binary));
1490 const char s[] = "Hello";
1491 EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
1495 std::string operator()() const { return {}; }
1496 template <typename... I>
1497 std::string operator()(const char* a, I... i) const {
1498 return a + ConcatAll()(i...);
1502 // Tests using WithArgs with an action that takes 10 arguments.
1503 TEST(WithArgsTest, TenArgs) {
1504 Action<std::string(const char*, const char*, const char*, const char*)> a =
1505 WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
1506 EXPECT_EQ("0123210123",
1507 a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
1511 // Tests using WithArgs with an action that is not Invoke().
1512 class SubtractAction : public ActionInterface<int(int, int)> {
1514 int Perform(const std::tuple<int, int>& args) override {
1515 return std::get<0>(args) - std::get<1>(args);
1519 TEST(WithArgsTest, NonInvokeAction) {
1520 Action<int(const std::string&, int, int)> a =
1521 WithArgs<2, 1>(MakeAction(new SubtractAction));
1522 std::tuple<std::string, int, int> dummy =
1523 std::make_tuple(std::string("hi"), 2, 10);
1524 EXPECT_EQ(8, a.Perform(dummy));
1527 // Tests using WithArgs to pass all original arguments in the original order.
1528 TEST(WithArgsTest, Identity) {
1529 Action<int(int x, char y, short z)> a = // NOLINT
1530 WithArgs<0, 1, 2>(Invoke(Ternary));
1531 EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
1534 // Tests using WithArgs with repeated arguments.
1535 TEST(WithArgsTest, RepeatedArguments) {
1536 Action<int(bool, int m, int n)> a = // NOLINT
1537 WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
1538 EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
1541 // Tests using WithArgs with reversed argument order.
1542 TEST(WithArgsTest, ReversedArgumentOrder) {
1543 Action<const char*(short n, const char* input)> a = // NOLINT
1544 WithArgs<1, 0>(Invoke(Binary));
1545 const char s[] = "Hello";
1546 EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
1549 // Tests using WithArgs with compatible, but not identical, argument types.
1550 TEST(WithArgsTest, ArgsOfCompatibleTypes) {
1551 Action<long(short x, char y, double z, char c)> a = // NOLINT
1552 WithArgs<0, 1, 3>(Invoke(Ternary));
1554 a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
1557 // Tests using WithArgs with an action that returns void.
1558 TEST(WithArgsTest, VoidAction) {
1559 Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
1561 a.Perform(std::make_tuple(1.5, 'a', 3));
1562 EXPECT_TRUE(g_done);
1565 TEST(WithArgsTest, ReturnReference) {
1566 Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });
1568 const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));
1569 EXPECT_EQ(&i, &res);
1572 TEST(WithArgsTest, InnerActionWithConversion) {
1573 Action<Derived*()> inner = [] { return nullptr; };
1575 MockFunction<Base*(double)> mock;
1576 EXPECT_CALL(mock, Call)
1577 .WillOnce(WithoutArgs(inner))
1578 .WillRepeatedly(WithoutArgs(inner));
1580 EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
1581 EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));
1584 // It should be possible to use an &&-qualified inner action as long as the
1585 // whole shebang is used as an rvalue with WillOnce.
1586 TEST(WithArgsTest, RefQualifiedInnerAction) {
1588 int operator()(const int arg) && {
1594 MockFunction<int(int, int)> mock;
1595 EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{}));
1596 EXPECT_EQ(19, mock.AsStdFunction()(0, 17));
1599 #if !GTEST_OS_WINDOWS_MOBILE
1601 class SetErrnoAndReturnTest : public testing::Test {
1603 void SetUp() override { errno = 0; }
1604 void TearDown() override { errno = 0; }
1607 TEST_F(SetErrnoAndReturnTest, Int) {
1608 Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1609 EXPECT_EQ(-5, a.Perform(std::make_tuple()));
1610 EXPECT_EQ(ENOTTY, errno);
1613 TEST_F(SetErrnoAndReturnTest, Ptr) {
1615 Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1616 EXPECT_EQ(&x, a.Perform(std::make_tuple()));
1617 EXPECT_EQ(ENOTTY, errno);
1620 TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1621 Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1622 EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));
1623 EXPECT_EQ(EINVAL, errno);
1626 #endif // !GTEST_OS_WINDOWS_MOBILE
1630 // Tests that the result of ByRef() is copyable.
1631 TEST(ByRefTest, IsCopyable) {
1632 const std::string s1 = "Hi";
1633 const std::string s2 = "Hello";
1635 auto ref_wrapper = ByRef(s1);
1636 const std::string& r1 = ref_wrapper;
1637 EXPECT_EQ(&s1, &r1);
1639 // Assigns a new value to ref_wrapper.
1640 ref_wrapper = ByRef(s2);
1641 const std::string& r2 = ref_wrapper;
1642 EXPECT_EQ(&s2, &r2);
1644 auto ref_wrapper1 = ByRef(s1);
1645 // Copies ref_wrapper1 to ref_wrapper.
1646 ref_wrapper = ref_wrapper1;
1647 const std::string& r3 = ref_wrapper;
1648 EXPECT_EQ(&s1, &r3);
1651 // Tests using ByRef() on a const value.
1652 TEST(ByRefTest, ConstValue) {
1654 // int& ref = ByRef(n); // This shouldn't compile - we have a
1655 // negative compilation test to catch it.
1656 const int& const_ref = ByRef(n);
1657 EXPECT_EQ(&n, &const_ref);
1660 // Tests using ByRef() on a non-const value.
1661 TEST(ByRefTest, NonConstValue) {
1664 // ByRef(n) can be used as either an int&,
1665 int& ref = ByRef(n);
1666 EXPECT_EQ(&n, &ref);
1669 const int& const_ref = ByRef(n);
1670 EXPECT_EQ(&n, &const_ref);
1673 // Tests explicitly specifying the type when using ByRef().
1674 TEST(ByRefTest, ExplicitType) {
1676 const int& r1 = ByRef<const int>(n);
1679 // ByRef<char>(n); // This shouldn't compile - we have a negative
1680 // compilation test to catch it.
1683 Derived& r2 = ByRef<Derived>(d);
1686 const Derived& r3 = ByRef<const Derived>(d);
1689 Base& r4 = ByRef<Base>(d);
1692 const Base& r5 = ByRef<const Base>(d);
1695 // The following shouldn't compile - we have a negative compilation
1699 // ByRef<Derived>(b);
1702 // Tests that Google Mock prints expression ByRef(x) as a reference to x.
1703 TEST(ByRefTest, PrintsCorrectly) {
1705 ::std::stringstream expected, actual;
1706 testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
1707 testing::internal::UniversalPrint(ByRef(n), &actual);
1708 EXPECT_EQ(expected.str(), actual.str());
1711 struct UnaryConstructorClass {
1712 explicit UnaryConstructorClass(int v) : value(v) {}
1716 // Tests using ReturnNew() with a unary constructor.
1717 TEST(ReturnNewTest, Unary) {
1718 Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);
1719 UnaryConstructorClass* c = a.Perform(std::make_tuple());
1720 EXPECT_EQ(4000, c->value);
1724 TEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {
1725 Action<UnaryConstructorClass*(bool, int)> a =
1726 ReturnNew<UnaryConstructorClass>(4000);
1727 UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));
1728 EXPECT_EQ(4000, c->value);
1732 TEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {
1733 Action<const UnaryConstructorClass*()> a =
1734 ReturnNew<UnaryConstructorClass>(4000);
1735 const UnaryConstructorClass* c = a.Perform(std::make_tuple());
1736 EXPECT_EQ(4000, c->value);
1740 class TenArgConstructorClass {
1742 TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,
1743 int a8, int a9, int a10)
1744 : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}
1748 // Tests using ReturnNew() with a 10-argument constructor.
1749 TEST(ReturnNewTest, ConstructorThatTakes10Arguments) {
1750 Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(
1751 1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,
1753 TenArgConstructorClass* c = a.Perform(std::make_tuple());
1754 EXPECT_EQ(1234567890, c->value_);
1758 std::unique_ptr<int> UniquePtrSource() {
1759 return std::unique_ptr<int>(new int(19));
1762 std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
1763 std::vector<std::unique_ptr<int>> out;
1764 out.emplace_back(new int(7));
1768 TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
1770 std::unique_ptr<int> i(new int(19));
1771 EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
1772 EXPECT_CALL(mock, MakeVectorUnique())
1773 .WillOnce(Return(ByMove(VectorUniquePtrSource())));
1774 Derived* d = new Derived;
1775 EXPECT_CALL(mock, MakeUniqueBase())
1776 .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
1778 std::unique_ptr<int> result1 = mock.MakeUnique();
1779 EXPECT_EQ(19, *result1);
1781 std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1782 EXPECT_EQ(1u, vresult.size());
1783 EXPECT_NE(nullptr, vresult[0]);
1784 EXPECT_EQ(7, *vresult[0]);
1786 std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
1787 EXPECT_EQ(d, result2.get());
1790 TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
1791 testing::MockFunction<void()> mock_function;
1793 std::unique_ptr<int> i(new int(19));
1794 EXPECT_CALL(mock_function, Call());
1795 EXPECT_CALL(mock, MakeUnique())
1796 .WillOnce(DoAll(InvokeWithoutArgs(&mock_function,
1797 &testing::MockFunction<void()>::Call),
1798 Return(ByMove(std::move(i)))));
1800 std::unique_ptr<int> result1 = mock.MakeUnique();
1801 EXPECT_EQ(19, *result1);
1804 TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1807 // Check default value
1808 DefaultValue<std::unique_ptr<int>>::SetFactory(
1809 [] { return std::unique_ptr<int>(new int(42)); });
1810 EXPECT_EQ(42, *mock.MakeUnique());
1812 EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1813 EXPECT_CALL(mock, MakeVectorUnique())
1814 .WillRepeatedly(Invoke(VectorUniquePtrSource));
1815 std::unique_ptr<int> result1 = mock.MakeUnique();
1816 EXPECT_EQ(19, *result1);
1817 std::unique_ptr<int> result2 = mock.MakeUnique();
1818 EXPECT_EQ(19, *result2);
1819 EXPECT_NE(result1, result2);
1821 std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1822 EXPECT_EQ(1u, vresult.size());
1823 EXPECT_NE(nullptr, vresult[0]);
1824 EXPECT_EQ(7, *vresult[0]);
1827 TEST(MockMethodTest, CanTakeMoveOnlyValue) {
1829 auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
1831 EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
1834 // DoAll() does not compile, since it would move from its arguments twice.
1835 // EXPECT_CALL(mock, TakeUnique(_, _))
1836 // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
1838 EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
1839 .WillOnce(Return(-7))
1840 .RetiresOnSaturation();
1841 EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
1842 .WillOnce(Return(-1))
1843 .RetiresOnSaturation();
1845 EXPECT_EQ(5, mock.TakeUnique(make(5)));
1846 EXPECT_EQ(-7, mock.TakeUnique(make(7)));
1847 EXPECT_EQ(7, mock.TakeUnique(make(7)));
1848 EXPECT_EQ(7, mock.TakeUnique(make(7)));
1849 EXPECT_EQ(-1, mock.TakeUnique({}));
1851 // Some arguments are moved, some passed by reference.
1852 auto lvalue = make(6);
1853 EXPECT_CALL(mock, TakeUnique(_, _))
1854 .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
1857 EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
1859 // The unique_ptr can be saved by the action.
1860 std::unique_ptr<int> saved;
1861 EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
1862 saved = std::move(i);
1865 EXPECT_EQ(0, mock.TakeUnique(make(42)));
1866 EXPECT_EQ(42, *saved);
1869 // It should be possible to use callables with an &&-qualified call operator
1870 // with WillOnce, since they will be called only once. This allows actions to
1871 // contain and manipulate move-only types.
1872 TEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) {
1874 int operator()() && { return 17; }
1877 // Action is directly compatible with mocked function type.
1879 MockFunction<int()> mock;
1880 EXPECT_CALL(mock, Call).WillOnce(Return17());
1882 EXPECT_EQ(17, mock.AsStdFunction()());
1885 // Action doesn't want mocked function arguments.
1887 MockFunction<int(int)> mock;
1888 EXPECT_CALL(mock, Call).WillOnce(Return17());
1890 EXPECT_EQ(17, mock.AsStdFunction()(0));
1894 // Edge case: if an action has both a const-qualified and an &&-qualified call
1895 // operator, there should be no "ambiguous call" errors. The &&-qualified
1896 // operator should be used by WillOnce (since it doesn't need to retain the
1897 // action beyond one call), and the const-qualified one by WillRepeatedly.
1898 TEST(MockMethodTest, ActionHasMultipleCallOperators) {
1900 int operator()() && { return 17; }
1901 int operator()() const& { return 19; }
1904 // Directly compatible with mocked function type.
1906 MockFunction<int()> mock;
1907 EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
1909 EXPECT_EQ(17, mock.AsStdFunction()());
1910 EXPECT_EQ(19, mock.AsStdFunction()());
1911 EXPECT_EQ(19, mock.AsStdFunction()());
1914 // Ignores function arguments.
1916 MockFunction<int(int)> mock;
1917 EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
1919 EXPECT_EQ(17, mock.AsStdFunction()(0));
1920 EXPECT_EQ(19, mock.AsStdFunction()(0));
1921 EXPECT_EQ(19, mock.AsStdFunction()(0));
1925 // WillOnce should have no problem coping with a move-only action, whether it is
1926 // &&-qualified or not.
1927 TEST(MockMethodTest, MoveOnlyAction) {
1931 Return17() = default;
1932 Return17(Return17&&) = default;
1934 Return17(const Return17&) = delete;
1935 Return17 operator=(const Return17&) = delete;
1937 int operator()() && { return 17; }
1940 MockFunction<int()> mock;
1941 EXPECT_CALL(mock, Call).WillOnce(Return17());
1942 EXPECT_EQ(17, mock.AsStdFunction()());
1948 Return17() = default;
1949 Return17(Return17&&) = default;
1951 Return17(const Return17&) = delete;
1952 Return17 operator=(const Return17&) = delete;
1954 int operator()() const { return 17; }
1957 MockFunction<int()> mock;
1958 EXPECT_CALL(mock, Call).WillOnce(Return17());
1959 EXPECT_EQ(17, mock.AsStdFunction()());
1963 // It should be possible to use an action that returns a value with a mock
1964 // function that doesn't, both through WillOnce and WillRepeatedly.
1965 TEST(MockMethodTest, ActionReturnsIgnoredValue) {
1967 int operator()() const { return 0; }
1970 MockFunction<void()> mock;
1971 EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());
1973 mock.AsStdFunction()();
1974 mock.AsStdFunction()();
1977 // Despite the fanciness around move-only actions and so on, it should still be
1978 // possible to hand an lvalue reference to a copyable action to WillOnce.
1979 TEST(MockMethodTest, WillOnceCanAcceptLvalueReference) {
1980 MockFunction<int()> mock;
1982 const auto action = [] { return 17; };
1983 EXPECT_CALL(mock, Call).WillOnce(action);
1985 EXPECT_EQ(17, mock.AsStdFunction()());
1988 // A callable that doesn't use SFINAE to restrict its call operator's overload
1989 // set, but is still picky about which arguments it will accept.
1990 struct StaticAssertSingleArgument {
1991 template <typename... Args>
1992 static constexpr bool CheckArgs() {
1993 static_assert(sizeof...(Args) == 1, "");
1997 template <typename... Args, bool = CheckArgs<Args...>()>
1998 int operator()(Args...) const {
2003 // WillOnce and WillRepeatedly should both work fine with naïve implementations
2004 // of actions that don't use SFINAE to limit the overload set for their call
2005 // operator. If they are compatible with the actual mocked signature, we
2006 // shouldn't probe them with no arguments and trip a static_assert.
2007 TEST(MockMethodTest, ActionSwallowsAllArguments) {
2008 MockFunction<int(int)> mock;
2009 EXPECT_CALL(mock, Call)
2010 .WillOnce(StaticAssertSingleArgument{})
2011 .WillRepeatedly(StaticAssertSingleArgument{});
2013 EXPECT_EQ(17, mock.AsStdFunction()(0));
2014 EXPECT_EQ(17, mock.AsStdFunction()(0));
2017 struct ActionWithTemplatedConversionOperators {
2018 template <typename... Args>
2019 operator OnceAction<int(Args...)>() && { // NOLINT
2020 return [] { return 17; };
2023 template <typename... Args>
2024 operator Action<int(Args...)>() const { // NOLINT
2025 return [] { return 19; };
2029 // It should be fine to hand both WillOnce and WillRepeatedly a function that
2030 // defines templated conversion operators to OnceAction and Action. WillOnce
2031 // should prefer the OnceAction version.
2032 TEST(MockMethodTest, ActionHasTemplatedConversionOperators) {
2033 MockFunction<int()> mock;
2034 EXPECT_CALL(mock, Call)
2035 .WillOnce(ActionWithTemplatedConversionOperators{})
2036 .WillRepeatedly(ActionWithTemplatedConversionOperators{});
2038 EXPECT_EQ(17, mock.AsStdFunction()());
2039 EXPECT_EQ(19, mock.AsStdFunction()());
2042 // Tests for std::function based action.
2044 int Add(int val, int& ref, int* ptr) { // NOLINT
2045 int result = val + ref + *ptr;
2051 int Deref(std::unique_ptr<int> ptr) { return *ptr; }
2054 template <typename T>
2060 std::unique_ptr<int> UniqueInt(int i) {
2061 return std::unique_ptr<int>(new int(i));
2064 TEST(FunctorActionTest, ActionFromFunction) {
2065 Action<int(int, int&, int*)> a = &Add;
2066 int x = 1, y = 2, z = 3;
2067 EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
2071 Action<int(std::unique_ptr<int>)> a1 = &Deref;
2072 EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
2075 TEST(FunctorActionTest, ActionFromLambda) {
2076 Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
2077 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
2078 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));
2080 std::unique_ptr<int> saved;
2081 Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
2082 saved = std::move(p);
2084 a2.Perform(std::make_tuple(UniqueInt(5)));
2085 EXPECT_EQ(5, *saved);
2088 TEST(FunctorActionTest, PolymorphicFunctor) {
2089 Action<int(int)> ai = Double();
2090 EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));
2091 Action<double(double)> ad = Double(); // Double? Double double!
2092 EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));
2095 TEST(FunctorActionTest, TypeConversion) {
2096 // Numeric promotions are allowed.
2097 const Action<bool(int)> a1 = [](int i) { return i > 1; };
2098 const Action<int(bool)> a2 = Action<int(bool)>(a1);
2099 EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));
2100 EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));
2102 // Implicit constructors are allowed.
2103 const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
2104 const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
2105 EXPECT_EQ(0, s2.Perform(std::make_tuple("")));
2106 EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
2108 // Also between the lambda and the action itself.
2109 const Action<bool(std::string)> x1 = [](Unused) { return 42; };
2110 const Action<bool(std::string)> x2 = [] { return 42; };
2111 EXPECT_TRUE(x1.Perform(std::make_tuple("hello")));
2112 EXPECT_TRUE(x2.Perform(std::make_tuple("hello")));
2114 // Ensure decay occurs where required.
2115 std::function<int()> f = [] { return 7; };
2116 Action<int(int)> d = f;
2118 EXPECT_EQ(7, d.Perform(std::make_tuple(1)));
2120 // Ensure creation of an empty action succeeds.
2121 Action<void(int)>(nullptr);
2124 TEST(FunctorActionTest, UnusedArguments) {
2125 // Verify that users can ignore uninteresting arguments.
2126 Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {
2129 std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
2130 EXPECT_EQ(6, a.Perform(dummy));
2133 // Test that basic built-in actions work with move-only arguments.
2134 TEST(MoveOnlyArgumentsTest, ReturningActions) {
2135 Action<int(std::unique_ptr<int>)> a = Return(1);
2136 EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));
2138 a = testing::WithoutArgs([]() { return 7; });
2139 EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));
2141 Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
2143 a2.Perform(std::make_tuple(nullptr, &x));
2147 ACTION(ReturnArity) { return std::tuple_size<args_type>::value; }
2149 TEST(ActionMacro, LargeArity) {
2151 1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));
2154 testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(
2156 .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));
2159 testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,
2160 int, int, int, int, int, int, int, int, int)>(
2162 .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
2163 14, 15, 16, 17, 18, 19)));
2167 } // namespace testing