1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Google Mock - a framework for writing C++ mock classes.
33 // This file tests the built-in actions.
35 // Silence C4800 (C4800: 'int *const ': forcing value
36 // to bool 'true' or 'false') for MSVC 15
39 # pragma warning(push)
40 # pragma warning(disable:4800)
44 #include "gmock/gmock-actions.h"
49 #include "gmock/gmock.h"
50 #include "gmock/internal/gmock-port.h"
51 #include "gtest/gtest.h"
52 #include "gtest/gtest-spi.h"
56 // This list should be kept sorted.
58 using testing::Action;
59 using testing::ActionInterface;
60 using testing::Assign;
61 using testing::ByMove;
63 using testing::DefaultValue;
65 using testing::DoDefault;
66 using testing::IgnoreResult;
67 using testing::Invoke;
68 using testing::InvokeWithoutArgs;
69 using testing::MakePolymorphicAction;
71 using testing::PolymorphicAction;
72 using testing::Return;
73 using testing::ReturnNull;
74 using testing::ReturnRef;
75 using testing::ReturnRefOfCopy;
76 using testing::SetArgPointee;
77 using testing::SetArgumentPointee;
78 using testing::Unused;
79 using testing::WithArgs;
80 using testing::internal::BuiltInDefaultValue;
81 using testing::internal::Int64;
82 using testing::internal::UInt64;
84 #if !GTEST_OS_WINDOWS_MOBILE
85 using testing::SetErrnoAndReturn;
88 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
89 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
90 EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);
91 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);
92 EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);
95 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
96 TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
97 EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
98 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
99 EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
102 // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
103 // built-in numeric type.
104 TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
105 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
106 EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
107 EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
108 #if GMOCK_WCHAR_T_IS_NATIVE_
109 #if !defined(__WCHAR_UNSIGNED__)
110 EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
112 EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
115 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
116 EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
117 EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
118 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
119 EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
120 EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
121 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
122 EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
123 EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
124 EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
125 EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
126 EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
127 EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
130 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
131 // built-in numeric type.
132 TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
133 EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
134 EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
135 EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
136 #if GMOCK_WCHAR_T_IS_NATIVE_
137 EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
139 EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT
140 EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT
141 EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT
142 EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
143 EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
144 EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
145 EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
146 EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
147 EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
148 EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists());
149 EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists());
150 EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
151 EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
154 // Tests that BuiltInDefaultValue<bool>::Get() returns false.
155 TEST(BuiltInDefaultValueTest, IsFalseForBool) {
156 EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
159 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
160 TEST(BuiltInDefaultValueTest, BoolExists) {
161 EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
164 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
166 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
167 EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
170 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
172 TEST(BuiltInDefaultValueTest, ExistsForString) {
173 EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
176 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
177 // value as BuiltInDefaultValue<T>::Get() does.
178 TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
179 EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
180 EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
181 EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);
182 EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
185 // A type that's default constructible.
186 class MyDefaultConstructible {
188 MyDefaultConstructible() : value_(42) {}
190 int value() const { return value_; }
196 // A type that's not default constructible.
197 class MyNonDefaultConstructible {
199 // Does not have a default ctor.
200 explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
202 int value() const { return value_; }
209 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
210 EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
213 TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
214 EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
218 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
219 EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
222 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
223 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
224 EXPECT_DEATH_IF_SUPPORTED({
225 BuiltInDefaultValue<int&>::Get();
227 EXPECT_DEATH_IF_SUPPORTED({
228 BuiltInDefaultValue<const char&>::Get();
232 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
233 EXPECT_DEATH_IF_SUPPORTED({
234 BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
238 // Tests that DefaultValue<T>::IsSet() is false initially.
239 TEST(DefaultValueTest, IsInitiallyUnset) {
240 EXPECT_FALSE(DefaultValue<int>::IsSet());
241 EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
242 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
245 // Tests that DefaultValue<T> can be set and then unset.
246 TEST(DefaultValueTest, CanBeSetAndUnset) {
247 EXPECT_TRUE(DefaultValue<int>::Exists());
248 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
250 DefaultValue<int>::Set(1);
251 DefaultValue<const MyNonDefaultConstructible>::Set(
252 MyNonDefaultConstructible(42));
254 EXPECT_EQ(1, DefaultValue<int>::Get());
255 EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
257 EXPECT_TRUE(DefaultValue<int>::Exists());
258 EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
260 DefaultValue<int>::Clear();
261 DefaultValue<const MyNonDefaultConstructible>::Clear();
263 EXPECT_FALSE(DefaultValue<int>::IsSet());
264 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
266 EXPECT_TRUE(DefaultValue<int>::Exists());
267 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
270 // Tests that DefaultValue<T>::Get() returns the
271 // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
273 TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
274 EXPECT_FALSE(DefaultValue<int>::IsSet());
275 EXPECT_TRUE(DefaultValue<int>::Exists());
276 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
277 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
279 EXPECT_EQ(0, DefaultValue<int>::Get());
281 EXPECT_DEATH_IF_SUPPORTED({
282 DefaultValue<MyNonDefaultConstructible>::Get();
286 TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
287 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
288 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);
289 DefaultValue<std::unique_ptr<int>>::SetFactory([] {
290 return std::unique_ptr<int>(new int(42));
292 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
293 std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
297 // Tests that DefaultValue<void>::Get() returns void.
298 TEST(DefaultValueTest, GetWorksForVoid) {
299 return DefaultValue<void>::Get();
302 // Tests using DefaultValue with a reference type.
304 // Tests that DefaultValue<T&>::IsSet() is false initially.
305 TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
306 EXPECT_FALSE(DefaultValue<int&>::IsSet());
307 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
308 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
311 // Tests that DefaultValue<T&>::Exists is false initiallly.
312 TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
313 EXPECT_FALSE(DefaultValue<int&>::Exists());
314 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
315 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
318 // Tests that DefaultValue<T&> can be set and then unset.
319 TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
321 DefaultValue<const int&>::Set(n);
322 MyNonDefaultConstructible x(42);
323 DefaultValue<MyNonDefaultConstructible&>::Set(x);
325 EXPECT_TRUE(DefaultValue<const int&>::Exists());
326 EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
328 EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
329 EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
331 DefaultValue<const int&>::Clear();
332 DefaultValue<MyNonDefaultConstructible&>::Clear();
334 EXPECT_FALSE(DefaultValue<const int&>::Exists());
335 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
337 EXPECT_FALSE(DefaultValue<const int&>::IsSet());
338 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
341 // Tests that DefaultValue<T&>::Get() returns the
342 // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
344 TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
345 EXPECT_FALSE(DefaultValue<int&>::IsSet());
346 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
348 EXPECT_DEATH_IF_SUPPORTED({
349 DefaultValue<int&>::Get();
351 EXPECT_DEATH_IF_SUPPORTED({
352 DefaultValue<MyNonDefaultConstructible>::Get();
356 // Tests that ActionInterface can be implemented by defining the
359 typedef int MyGlobalFunction(bool, int);
361 class MyActionImpl : public ActionInterface<MyGlobalFunction> {
363 int Perform(const std::tuple<bool, int>& args) override {
364 return std::get<0>(args) ? std::get<1>(args) : 0;
368 TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
369 MyActionImpl my_action_impl;
370 (void)my_action_impl;
373 TEST(ActionInterfaceTest, MakeAction) {
374 Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
376 // When exercising the Perform() method of Action<F>, we must pass
377 // it a tuple whose size and type are compatible with F's argument
378 // types. For example, if F is int(), then Perform() takes a
379 // 0-tuple; if F is void(bool, int), then Perform() takes a
380 // std::tuple<bool, int>, and so on.
381 EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
384 // Tests that Action<F> can be contructed from a pointer to
385 // ActionInterface<F>.
386 TEST(ActionTest, CanBeConstructedFromActionInterface) {
387 Action<MyGlobalFunction> action(new MyActionImpl);
390 // Tests that Action<F> delegates actual work to ActionInterface<F>.
391 TEST(ActionTest, DelegatesWorkToActionInterface) {
392 const Action<MyGlobalFunction> action(new MyActionImpl);
394 EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));
395 EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));
398 // Tests that Action<F> can be copied.
399 TEST(ActionTest, IsCopyable) {
400 Action<MyGlobalFunction> a1(new MyActionImpl);
401 Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.
403 // a1 should continue to work after being copied from.
404 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
405 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
407 // a2 should work like the action it was copied from.
408 EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
409 EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
411 a2 = a1; // Tests the assignment operator.
413 // a1 should continue to work after being copied from.
414 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
415 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));
417 // a2 should work like the action it was copied from.
418 EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));
419 EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));
422 // Tests that an Action<From> object can be converted to a
423 // compatible Action<To> object.
425 class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
427 bool Perform(const std::tuple<int>& arg) override {
428 return std::get<0>(arg) != 0;
432 TEST(ActionTest, CanBeConvertedToOtherActionType) {
433 const Action<bool(int)> a1(new IsNotZero); // NOLINT
434 const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT
435 EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));
436 EXPECT_EQ(0, a2.Perform(std::make_tuple('\0')));
439 // The following two classes are for testing MakePolymorphicAction().
441 // Implements a polymorphic action that returns the second of the
442 // arguments it receives.
443 class ReturnSecondArgumentAction {
445 // We want to verify that MakePolymorphicAction() can work with a
446 // polymorphic action whose Perform() method template is either
447 // const or not. This lets us verify the non-const case.
448 template <typename Result, typename ArgumentTuple>
449 Result Perform(const ArgumentTuple& args) {
450 return std::get<1>(args);
454 // Implements a polymorphic action that can be used in a nullary
455 // function to return 0.
456 class ReturnZeroFromNullaryFunctionAction {
458 // For testing that MakePolymorphicAction() works when the
459 // implementation class' Perform() method template takes only one
460 // template parameter.
462 // We want to verify that MakePolymorphicAction() can work with a
463 // polymorphic action whose Perform() method template is either
464 // const or not. This lets us verify the const case.
465 template <typename Result>
466 Result Perform(const std::tuple<>&) const {
471 // These functions verify that MakePolymorphicAction() returns a
472 // PolymorphicAction<T> where T is the argument's type.
474 PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
475 return MakePolymorphicAction(ReturnSecondArgumentAction());
478 PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
479 ReturnZeroFromNullaryFunction() {
480 return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
483 // Tests that MakePolymorphicAction() turns a polymorphic action
484 // implementation class into a polymorphic action.
485 TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
486 Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT
487 EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));
490 // Tests that MakePolymorphicAction() works when the implementation
491 // class' Perform() method template has only one template parameter.
492 TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
493 Action<int()> a1 = ReturnZeroFromNullaryFunction();
494 EXPECT_EQ(0, a1.Perform(std::make_tuple()));
496 Action<void*()> a2 = ReturnZeroFromNullaryFunction();
497 EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);
500 // Tests that Return() works as an action for void-returning
502 TEST(ReturnTest, WorksForVoid) {
503 const Action<void(int)> ret = Return(); // NOLINT
504 return ret.Perform(std::make_tuple(1));
507 // Tests that Return(v) returns v.
508 TEST(ReturnTest, ReturnsGivenValue) {
509 Action<int()> ret = Return(1); // NOLINT
510 EXPECT_EQ(1, ret.Perform(std::make_tuple()));
513 EXPECT_EQ(-5, ret.Perform(std::make_tuple()));
516 // Tests that Return("string literal") works.
517 TEST(ReturnTest, AcceptsStringLiteral) {
518 Action<const char*()> a1 = Return("Hello");
519 EXPECT_STREQ("Hello", a1.Perform(std::make_tuple()));
521 Action<std::string()> a2 = Return("world");
522 EXPECT_EQ("world", a2.Perform(std::make_tuple()));
525 // Test struct which wraps a vector of integers. Used in
526 // 'SupportsWrapperReturnType' test.
527 struct IntegerVectorWrapper {
528 std::vector<int> * v;
529 IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT
532 // Tests that Return() works when return type is a wrapper type.
533 TEST(ReturnTest, SupportsWrapperReturnType) {
534 // Initialize vector of integers.
536 for (int i = 0; i < 5; ++i) v.push_back(i);
538 // Return() called with 'v' as argument. The Action will return the same data
539 // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
540 Action<IntegerVectorWrapper()> a = Return(v);
541 const std::vector<int>& result = *(a.Perform(std::make_tuple()).v);
542 EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
545 // Tests that Return(v) is covaraint.
548 bool operator==(const Base&) { return true; }
551 struct Derived : public Base {
552 bool operator==(const Derived&) { return true; }
555 TEST(ReturnTest, IsCovariant) {
558 Action<Base*()> ret = Return(&base);
559 EXPECT_EQ(&base, ret.Perform(std::make_tuple()));
561 ret = Return(&derived);
562 EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));
565 // Tests that the type of the value passed into Return is converted into T
566 // when the action is cast to Action<T(...)> rather than when the action is
567 // performed. See comments on testing::internal::ReturnAction in
568 // gmock-actions.h for more information.
571 explicit FromType(bool* is_converted) : converted_(is_converted) {}
572 bool* converted() const { return converted_; }
575 bool* const converted_;
577 GTEST_DISALLOW_ASSIGN_(FromType);
582 // Must allow implicit conversion due to use in ImplicitCast_<T>.
583 ToType(const FromType& x) { *x.converted() = true; } // NOLINT
586 TEST(ReturnTest, ConvertsArgumentWhenConverted) {
587 bool converted = false;
588 FromType x(&converted);
589 Action<ToType()> action(Return(x));
590 EXPECT_TRUE(converted) << "Return must convert its argument in its own "
591 << "conversion operator.";
593 action.Perform(std::tuple<>());
594 EXPECT_FALSE(converted) << "Action must NOT convert its argument "
595 << "when performed.";
598 class DestinationType {};
602 // Note: a non-const typecast operator.
603 operator DestinationType() { return DestinationType(); }
606 TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
608 Action<DestinationType()> action(Return(s));
611 // Tests that ReturnNull() returns NULL in a pointer-returning function.
612 TEST(ReturnNullTest, WorksInPointerReturningFunction) {
613 const Action<int*()> a1 = ReturnNull();
614 EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
616 const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT
617 EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);
620 // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
622 TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
623 const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
624 EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);
626 const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
627 EXPECT_TRUE(a2.Perform(std::make_tuple("foo")) == nullptr);
630 // Tests that ReturnRef(v) works for reference types.
631 TEST(ReturnRefTest, WorksForReference) {
633 const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT
635 EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));
638 // Tests that ReturnRef(v) is covariant.
639 TEST(ReturnRefTest, IsCovariant) {
642 Action<Base&()> a = ReturnRef(base);
643 EXPECT_EQ(&base, &a.Perform(std::make_tuple()));
645 a = ReturnRef(derived);
646 EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));
649 // Tests that ReturnRefOfCopy(v) works for reference types.
650 TEST(ReturnRefOfCopyTest, WorksForReference) {
652 const Action<const int&()> ret = ReturnRefOfCopy(n);
654 EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
655 EXPECT_EQ(42, ret.Perform(std::make_tuple()));
658 EXPECT_NE(&n, &ret.Perform(std::make_tuple()));
659 EXPECT_EQ(42, ret.Perform(std::make_tuple()));
662 // Tests that ReturnRefOfCopy(v) is covariant.
663 TEST(ReturnRefOfCopyTest, IsCovariant) {
666 Action<Base&()> a = ReturnRefOfCopy(base);
667 EXPECT_NE(&base, &a.Perform(std::make_tuple()));
669 a = ReturnRefOfCopy(derived);
670 EXPECT_NE(&derived, &a.Perform(std::make_tuple()));
673 // Tests that DoDefault() does the default action for the mock method.
679 MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
680 MOCK_METHOD0(Foo, MyNonDefaultConstructible());
681 MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
682 MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
683 MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
684 MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
685 MOCK_METHOD2(TakeUnique,
686 int(const std::unique_ptr<int>&, std::unique_ptr<int>));
689 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
692 // Tests that DoDefault() returns the built-in default value for the
693 // return type by default.
694 TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
696 EXPECT_CALL(mock, IntFunc(_))
697 .WillOnce(DoDefault());
698 EXPECT_EQ(0, mock.IntFunc(true));
701 // Tests that DoDefault() throws (when exceptions are enabled) or aborts
702 // the process when there is no built-in default value for the return type.
703 TEST(DoDefaultDeathTest, DiesForUnknowType) {
705 EXPECT_CALL(mock, Foo())
706 .WillRepeatedly(DoDefault());
707 #if GTEST_HAS_EXCEPTIONS
708 EXPECT_ANY_THROW(mock.Foo());
710 EXPECT_DEATH_IF_SUPPORTED({
716 // Tests that using DoDefault() inside a composite action leads to a
719 void VoidFunc(bool /* flag */) {}
721 TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
723 EXPECT_CALL(mock, IntFunc(_))
724 .WillRepeatedly(DoAll(Invoke(VoidFunc),
727 // Ideally we should verify the error message as well. Sadly,
728 // EXPECT_DEATH() can only capture stderr, while Google Mock's
729 // errors are printed on stdout. Therefore we have to settle for
730 // not verifying the message.
731 EXPECT_DEATH_IF_SUPPORTED({
736 // Tests that DoDefault() returns the default value set by
737 // DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
738 TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
739 DefaultValue<int>::Set(1);
741 EXPECT_CALL(mock, IntFunc(_))
742 .WillOnce(DoDefault());
743 EXPECT_EQ(1, mock.IntFunc(false));
744 DefaultValue<int>::Clear();
747 // Tests that DoDefault() does the action specified by ON_CALL().
748 TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
750 ON_CALL(mock, IntFunc(_))
751 .WillByDefault(Return(2));
752 EXPECT_CALL(mock, IntFunc(_))
753 .WillOnce(DoDefault());
754 EXPECT_EQ(2, mock.IntFunc(false));
757 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
758 TEST(DoDefaultTest, CannotBeUsedInOnCall) {
760 EXPECT_NONFATAL_FAILURE({ // NOLINT
761 ON_CALL(mock, IntFunc(_))
762 .WillByDefault(DoDefault());
763 }, "DoDefault() cannot be used in ON_CALL()");
766 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
767 // the N-th (0-based) argument to v.
768 TEST(SetArgPointeeTest, SetsTheNthPointee) {
769 typedef void MyFunction(bool, int*, char*);
770 Action<MyFunction> a = SetArgPointee<1>(2);
774 a.Perform(std::make_tuple(true, &n, &ch));
778 a = SetArgPointee<2>('a');
781 a.Perform(std::make_tuple(true, &n, &ch));
786 // Tests that SetArgPointee<N>() accepts a string literal.
787 TEST(SetArgPointeeTest, AcceptsStringLiteral) {
788 typedef void MyFunction(std::string*, const char**);
789 Action<MyFunction> a = SetArgPointee<0>("hi");
791 const char* ptr = nullptr;
792 a.Perform(std::make_tuple(&str, &ptr));
793 EXPECT_EQ("hi", str);
794 EXPECT_TRUE(ptr == nullptr);
796 a = SetArgPointee<1>("world");
798 a.Perform(std::make_tuple(&str, &ptr));
800 EXPECT_STREQ("world", ptr);
803 TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
804 typedef void MyFunction(const wchar_t**);
805 Action<MyFunction> a = SetArgPointee<0>(L"world");
806 const wchar_t* ptr = nullptr;
807 a.Perform(std::make_tuple(&ptr));
808 EXPECT_STREQ(L"world", ptr);
810 # if GTEST_HAS_STD_WSTRING
812 typedef void MyStringFunction(std::wstring*);
813 Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
814 std::wstring str = L"";
815 a2.Perform(std::make_tuple(&str));
816 EXPECT_EQ(L"world", str);
821 // Tests that SetArgPointee<N>() accepts a char pointer.
822 TEST(SetArgPointeeTest, AcceptsCharPointer) {
823 typedef void MyFunction(bool, std::string*, const char**);
824 const char* const hi = "hi";
825 Action<MyFunction> a = SetArgPointee<1>(hi);
827 const char* ptr = nullptr;
828 a.Perform(std::make_tuple(true, &str, &ptr));
829 EXPECT_EQ("hi", str);
830 EXPECT_TRUE(ptr == nullptr);
832 char world_array[] = "world";
833 char* const world = world_array;
834 a = SetArgPointee<2>(world);
836 a.Perform(std::make_tuple(true, &str, &ptr));
838 EXPECT_EQ(world, ptr);
841 TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
842 typedef void MyFunction(bool, const wchar_t**);
843 const wchar_t* const hi = L"hi";
844 Action<MyFunction> a = SetArgPointee<1>(hi);
845 const wchar_t* ptr = nullptr;
846 a.Perform(std::make_tuple(true, &ptr));
849 # if GTEST_HAS_STD_WSTRING
851 typedef void MyStringFunction(bool, std::wstring*);
852 wchar_t world_array[] = L"world";
853 wchar_t* const world = world_array;
854 Action<MyStringFunction> a2 = SetArgPointee<1>(world);
856 a2.Perform(std::make_tuple(true, &str));
857 EXPECT_EQ(world_array, str);
861 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
862 // the N-th (0-based) argument to v.
863 TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
864 typedef void MyFunction(bool, int*, char*);
865 Action<MyFunction> a = SetArgumentPointee<1>(2);
869 a.Perform(std::make_tuple(true, &n, &ch));
873 a = SetArgumentPointee<2>('a');
876 a.Perform(std::make_tuple(true, &n, &ch));
881 // Sample functions and functors for testing Invoke() and etc.
882 int Nullary() { return 1; }
884 class NullaryFunctor {
886 int operator()() { return 2; }
890 void VoidNullary() { g_done = true; }
892 class VoidNullaryFunctor {
894 void operator()() { g_done = true; }
897 short Short(short n) { return n; } // NOLINT
898 char Char(char ch) { return ch; }
900 const char* CharPtr(const char* s) { return s; }
902 bool Unary(int x) { return x < 0; }
904 const char* Binary(const char* input, short n) { return input + n; } // NOLINT
906 void VoidBinary(int, char) { g_done = true; }
908 int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
910 int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
914 Foo() : value_(123) {}
916 int Nullary() const { return value_; }
922 // Tests InvokeWithoutArgs(function).
923 TEST(InvokeWithoutArgsTest, Function) {
924 // As an action that takes one argument.
925 Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT
926 EXPECT_EQ(1, a.Perform(std::make_tuple(2)));
928 // As an action that takes two arguments.
929 Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT
930 EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));
932 // As an action that returns void.
933 Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT
935 a3.Perform(std::make_tuple(1));
939 // Tests InvokeWithoutArgs(functor).
940 TEST(InvokeWithoutArgsTest, Functor) {
941 // As an action that takes no argument.
942 Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT
943 EXPECT_EQ(2, a.Perform(std::make_tuple()));
945 // As an action that takes three arguments.
946 Action<int(int, double, char)> a2 = // NOLINT
947 InvokeWithoutArgs(NullaryFunctor());
948 EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));
950 // As an action that returns void.
951 Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
953 a3.Perform(std::make_tuple());
957 // Tests InvokeWithoutArgs(obj_ptr, method).
958 TEST(InvokeWithoutArgsTest, Method) {
960 Action<int(bool, char)> a = // NOLINT
961 InvokeWithoutArgs(&foo, &Foo::Nullary);
962 EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));
965 // Tests using IgnoreResult() on a polymorphic action.
966 TEST(IgnoreResultTest, PolymorphicAction) {
967 Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT
968 a.Perform(std::make_tuple(1));
971 // Tests using IgnoreResult() on a monomorphic action.
978 TEST(IgnoreResultTest, MonomorphicAction) {
980 Action<void()> a = IgnoreResult(Invoke(ReturnOne));
981 a.Perform(std::make_tuple());
985 // Tests using IgnoreResult() on an action that returns a class type.
987 MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
989 return MyNonDefaultConstructible(42);
992 TEST(IgnoreResultTest, ActionReturningClass) {
994 Action<void(int)> a =
995 IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
996 a.Perform(std::make_tuple(2));
1000 TEST(AssignTest, Int) {
1002 Action<void(int)> a = Assign(&x, 5);
1003 a.Perform(std::make_tuple(0));
1007 TEST(AssignTest, String) {
1009 Action<void(void)> a = Assign(&x, "Hello, world");
1010 a.Perform(std::make_tuple());
1011 EXPECT_EQ("Hello, world", x);
1014 TEST(AssignTest, CompatibleTypes) {
1016 Action<void(int)> a = Assign(&x, 5);
1017 a.Perform(std::make_tuple(0));
1018 EXPECT_DOUBLE_EQ(5, x);
1022 // Tests using WithArgs and with an action that takes 1 argument.
1023 TEST(WithArgsTest, OneArg) {
1024 Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary)); // NOLINT
1025 EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));
1026 EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));
1029 // Tests using WithArgs with an action that takes 2 arguments.
1030 TEST(WithArgsTest, TwoArgs) {
1031 Action<const char*(const char* s, double x, short n)> a = // NOLINT
1032 WithArgs<0, 2>(Invoke(Binary));
1033 const char s[] = "Hello";
1034 EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));
1038 std::string operator()() const { return {}; }
1039 template <typename... I>
1040 std::string operator()(const char* a, I... i) const {
1041 return a + ConcatAll()(i...);
1045 // Tests using WithArgs with an action that takes 10 arguments.
1046 TEST(WithArgsTest, TenArgs) {
1047 Action<std::string(const char*, const char*, const char*, const char*)> a =
1048 WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));
1049 EXPECT_EQ("0123210123",
1050 a.Perform(std::make_tuple(CharPtr("0"), CharPtr("1"), CharPtr("2"),
1054 // Tests using WithArgs with an action that is not Invoke().
1055 class SubtractAction : public ActionInterface<int(int, int)> {
1057 int Perform(const std::tuple<int, int>& args) override {
1058 return std::get<0>(args) - std::get<1>(args);
1062 TEST(WithArgsTest, NonInvokeAction) {
1063 Action<int(const std::string&, int, int)> a =
1064 WithArgs<2, 1>(MakeAction(new SubtractAction));
1065 std::tuple<std::string, int, int> dummy =
1066 std::make_tuple(std::string("hi"), 2, 10);
1067 EXPECT_EQ(8, a.Perform(dummy));
1070 // Tests using WithArgs to pass all original arguments in the original order.
1071 TEST(WithArgsTest, Identity) {
1072 Action<int(int x, char y, short z)> a = // NOLINT
1073 WithArgs<0, 1, 2>(Invoke(Ternary));
1074 EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));
1077 // Tests using WithArgs with repeated arguments.
1078 TEST(WithArgsTest, RepeatedArguments) {
1079 Action<int(bool, int m, int n)> a = // NOLINT
1080 WithArgs<1, 1, 1, 1>(Invoke(SumOf4));
1081 EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));
1084 // Tests using WithArgs with reversed argument order.
1085 TEST(WithArgsTest, ReversedArgumentOrder) {
1086 Action<const char*(short n, const char* input)> a = // NOLINT
1087 WithArgs<1, 0>(Invoke(Binary));
1088 const char s[] = "Hello";
1089 EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));
1092 // Tests using WithArgs with compatible, but not identical, argument types.
1093 TEST(WithArgsTest, ArgsOfCompatibleTypes) {
1094 Action<long(short x, char y, double z, char c)> a = // NOLINT
1095 WithArgs<0, 1, 3>(Invoke(Ternary));
1097 a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));
1100 // Tests using WithArgs with an action that returns void.
1101 TEST(WithArgsTest, VoidAction) {
1102 Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));
1104 a.Perform(std::make_tuple(1.5, 'a', 3));
1105 EXPECT_TRUE(g_done);
1108 TEST(WithArgsTest, ReturnReference) {
1109 Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });
1111 const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));
1112 EXPECT_EQ(&i, &res);
1115 TEST(WithArgsTest, InnerActionWithConversion) {
1116 Action<Derived*()> inner = [] { return nullptr; };
1117 Action<Base*(double)> a = testing::WithoutArgs(inner);
1118 EXPECT_EQ(nullptr, a.Perform(std::make_tuple(1.1)));
1121 #if !GTEST_OS_WINDOWS_MOBILE
1123 class SetErrnoAndReturnTest : public testing::Test {
1125 void SetUp() override { errno = 0; }
1126 void TearDown() override { errno = 0; }
1129 TEST_F(SetErrnoAndReturnTest, Int) {
1130 Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1131 EXPECT_EQ(-5, a.Perform(std::make_tuple()));
1132 EXPECT_EQ(ENOTTY, errno);
1135 TEST_F(SetErrnoAndReturnTest, Ptr) {
1137 Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1138 EXPECT_EQ(&x, a.Perform(std::make_tuple()));
1139 EXPECT_EQ(ENOTTY, errno);
1142 TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1143 Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1144 EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));
1145 EXPECT_EQ(EINVAL, errno);
1148 #endif // !GTEST_OS_WINDOWS_MOBILE
1152 // Tests that the result of ByRef() is copyable.
1153 TEST(ByRefTest, IsCopyable) {
1154 const std::string s1 = "Hi";
1155 const std::string s2 = "Hello";
1157 auto ref_wrapper = ByRef(s1);
1158 const std::string& r1 = ref_wrapper;
1159 EXPECT_EQ(&s1, &r1);
1161 // Assigns a new value to ref_wrapper.
1162 ref_wrapper = ByRef(s2);
1163 const std::string& r2 = ref_wrapper;
1164 EXPECT_EQ(&s2, &r2);
1166 auto ref_wrapper1 = ByRef(s1);
1167 // Copies ref_wrapper1 to ref_wrapper.
1168 ref_wrapper = ref_wrapper1;
1169 const std::string& r3 = ref_wrapper;
1170 EXPECT_EQ(&s1, &r3);
1173 // Tests using ByRef() on a const value.
1174 TEST(ByRefTest, ConstValue) {
1176 // int& ref = ByRef(n); // This shouldn't compile - we have a
1177 // negative compilation test to catch it.
1178 const int& const_ref = ByRef(n);
1179 EXPECT_EQ(&n, &const_ref);
1182 // Tests using ByRef() on a non-const value.
1183 TEST(ByRefTest, NonConstValue) {
1186 // ByRef(n) can be used as either an int&,
1187 int& ref = ByRef(n);
1188 EXPECT_EQ(&n, &ref);
1191 const int& const_ref = ByRef(n);
1192 EXPECT_EQ(&n, &const_ref);
1195 // Tests explicitly specifying the type when using ByRef().
1196 TEST(ByRefTest, ExplicitType) {
1198 const int& r1 = ByRef<const int>(n);
1201 // ByRef<char>(n); // This shouldn't compile - we have a negative
1202 // compilation test to catch it.
1205 Derived& r2 = ByRef<Derived>(d);
1208 const Derived& r3 = ByRef<const Derived>(d);
1211 Base& r4 = ByRef<Base>(d);
1214 const Base& r5 = ByRef<const Base>(d);
1217 // The following shouldn't compile - we have a negative compilation
1221 // ByRef<Derived>(b);
1224 // Tests that Google Mock prints expression ByRef(x) as a reference to x.
1225 TEST(ByRefTest, PrintsCorrectly) {
1227 ::std::stringstream expected, actual;
1228 testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
1229 testing::internal::UniversalPrint(ByRef(n), &actual);
1230 EXPECT_EQ(expected.str(), actual.str());
1234 std::unique_ptr<int> UniquePtrSource() {
1235 return std::unique_ptr<int>(new int(19));
1238 std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
1239 std::vector<std::unique_ptr<int>> out;
1240 out.emplace_back(new int(7));
1244 TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
1246 std::unique_ptr<int> i(new int(19));
1247 EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
1248 EXPECT_CALL(mock, MakeVectorUnique())
1249 .WillOnce(Return(ByMove(VectorUniquePtrSource())));
1250 Derived* d = new Derived;
1251 EXPECT_CALL(mock, MakeUniqueBase())
1252 .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
1254 std::unique_ptr<int> result1 = mock.MakeUnique();
1255 EXPECT_EQ(19, *result1);
1257 std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1258 EXPECT_EQ(1u, vresult.size());
1259 EXPECT_NE(nullptr, vresult[0]);
1260 EXPECT_EQ(7, *vresult[0]);
1262 std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
1263 EXPECT_EQ(d, result2.get());
1266 TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
1267 testing::MockFunction<void()> mock_function;
1269 std::unique_ptr<int> i(new int(19));
1270 EXPECT_CALL(mock_function, Call());
1271 EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
1272 InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
1273 Return(ByMove(std::move(i)))));
1275 std::unique_ptr<int> result1 = mock.MakeUnique();
1276 EXPECT_EQ(19, *result1);
1279 TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1282 // Check default value
1283 DefaultValue<std::unique_ptr<int>>::SetFactory([] {
1284 return std::unique_ptr<int>(new int(42));
1286 EXPECT_EQ(42, *mock.MakeUnique());
1288 EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1289 EXPECT_CALL(mock, MakeVectorUnique())
1290 .WillRepeatedly(Invoke(VectorUniquePtrSource));
1291 std::unique_ptr<int> result1 = mock.MakeUnique();
1292 EXPECT_EQ(19, *result1);
1293 std::unique_ptr<int> result2 = mock.MakeUnique();
1294 EXPECT_EQ(19, *result2);
1295 EXPECT_NE(result1, result2);
1297 std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1298 EXPECT_EQ(1u, vresult.size());
1299 EXPECT_NE(nullptr, vresult[0]);
1300 EXPECT_EQ(7, *vresult[0]);
1303 TEST(MockMethodTest, CanTakeMoveOnlyValue) {
1305 auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
1307 EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
1310 // DoAll() does not compile, since it would move from its arguments twice.
1311 // EXPECT_CALL(mock, TakeUnique(_, _))
1312 // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
1314 EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
1315 .WillOnce(Return(-7))
1316 .RetiresOnSaturation();
1317 EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
1318 .WillOnce(Return(-1))
1319 .RetiresOnSaturation();
1321 EXPECT_EQ(5, mock.TakeUnique(make(5)));
1322 EXPECT_EQ(-7, mock.TakeUnique(make(7)));
1323 EXPECT_EQ(7, mock.TakeUnique(make(7)));
1324 EXPECT_EQ(7, mock.TakeUnique(make(7)));
1325 EXPECT_EQ(-1, mock.TakeUnique({}));
1327 // Some arguments are moved, some passed by reference.
1328 auto lvalue = make(6);
1329 EXPECT_CALL(mock, TakeUnique(_, _))
1330 .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
1333 EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
1335 // The unique_ptr can be saved by the action.
1336 std::unique_ptr<int> saved;
1337 EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
1338 saved = std::move(i);
1341 EXPECT_EQ(0, mock.TakeUnique(make(42)));
1342 EXPECT_EQ(42, *saved);
1346 // Tests for std::function based action.
1348 int Add(int val, int& ref, int* ptr) { // NOLINT
1349 int result = val + ref + *ptr;
1355 int Deref(std::unique_ptr<int> ptr) { return *ptr; }
1358 template <typename T>
1359 T operator()(T t) { return 2 * t; }
1362 std::unique_ptr<int> UniqueInt(int i) {
1363 return std::unique_ptr<int>(new int(i));
1366 TEST(FunctorActionTest, ActionFromFunction) {
1367 Action<int(int, int&, int*)> a = &Add;
1368 int x = 1, y = 2, z = 3;
1369 EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
1373 Action<int(std::unique_ptr<int>)> a1 = &Deref;
1374 EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
1377 TEST(FunctorActionTest, ActionFromLambda) {
1378 Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
1379 EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));
1380 EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));
1382 std::unique_ptr<int> saved;
1383 Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
1384 saved = std::move(p);
1386 a2.Perform(std::make_tuple(UniqueInt(5)));
1387 EXPECT_EQ(5, *saved);
1390 TEST(FunctorActionTest, PolymorphicFunctor) {
1391 Action<int(int)> ai = Double();
1392 EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));
1393 Action<double(double)> ad = Double(); // Double? Double double!
1394 EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));
1397 TEST(FunctorActionTest, TypeConversion) {
1398 // Numeric promotions are allowed.
1399 const Action<bool(int)> a1 = [](int i) { return i > 1; };
1400 const Action<int(bool)> a2 = Action<int(bool)>(a1);
1401 EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));
1402 EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));
1404 // Implicit constructors are allowed.
1405 const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
1406 const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
1407 EXPECT_EQ(0, s2.Perform(std::make_tuple("")));
1408 EXPECT_EQ(1, s2.Perform(std::make_tuple("hello")));
1410 // Also between the lambda and the action itself.
1411 const Action<bool(std::string)> x = [](Unused) { return 42; };
1412 EXPECT_TRUE(x.Perform(std::make_tuple("hello")));
1415 TEST(FunctorActionTest, UnusedArguments) {
1416 // Verify that users can ignore uninteresting arguments.
1417 Action<int(int, double y, double z)> a =
1418 [](int i, Unused, Unused) { return 2 * i; };
1419 std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);
1420 EXPECT_EQ(6, a.Perform(dummy));
1423 // Test that basic built-in actions work with move-only arguments.
1424 TEST(MoveOnlyArgumentsTest, ReturningActions) {
1425 Action<int(std::unique_ptr<int>)> a = Return(1);
1426 EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));
1428 a = testing::WithoutArgs([]() { return 7; });
1429 EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));
1431 Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
1433 a2.Perform(std::make_tuple(nullptr, &x));
1438 } // Unnamed namespace
1441 #if _MSC_VER == 1900
1442 # pragma warning(pop)