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 14,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.
57 using testing::Action;
58 using testing::ActionInterface;
59 using testing::Assign;
60 using testing::ByMove;
62 using testing::DefaultValue;
63 using testing::DoDefault;
64 using testing::IgnoreResult;
65 using testing::Invoke;
66 using testing::InvokeWithoutArgs;
67 using testing::MakePolymorphicAction;
69 using testing::PolymorphicAction;
70 using testing::Return;
71 using testing::ReturnNull;
72 using testing::ReturnRef;
73 using testing::ReturnRefOfCopy;
74 using testing::SetArgPointee;
75 using testing::SetArgumentPointee;
76 using testing::Unused;
79 using testing::internal::BuiltInDefaultValue;
80 using testing::internal::Int64;
81 using testing::internal::UInt64;
82 using testing::make_tuple;
84 using testing::tuple_element;
86 #if !GTEST_OS_WINDOWS_MOBILE
87 using testing::SetErrnoAndReturn;
90 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
91 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
92 EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
93 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL);
94 EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL);
97 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
98 TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
99 EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
100 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
101 EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
104 // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
105 // built-in numeric type.
106 TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
107 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
108 EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
109 EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
110 #if GMOCK_HAS_SIGNED_WCHAR_T_
111 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get());
112 EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get());
114 #if GMOCK_WCHAR_T_IS_NATIVE_
115 #if !defined(__WCHAR_UNSIGNED__)
116 EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
118 EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
121 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
122 EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
123 EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
124 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
125 EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
126 EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
127 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
128 EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
129 EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
130 EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
131 EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
132 EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
133 EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
136 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
137 // built-in numeric type.
138 TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
139 EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
140 EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
141 EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
142 #if GMOCK_HAS_SIGNED_WCHAR_T_
143 EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists());
144 EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists());
146 #if GMOCK_WCHAR_T_IS_NATIVE_
147 EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
149 EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT
150 EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT
151 EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT
152 EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
153 EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
154 EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
155 EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
156 EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
157 EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
158 EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists());
159 EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists());
160 EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
161 EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
164 // Tests that BuiltInDefaultValue<bool>::Get() returns false.
165 TEST(BuiltInDefaultValueTest, IsFalseForBool) {
166 EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
169 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
170 TEST(BuiltInDefaultValueTest, BoolExists) {
171 EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
174 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
176 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
177 #if GTEST_HAS_GLOBAL_STRING
178 EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
179 #endif // GTEST_HAS_GLOBAL_STRING
181 EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
184 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
186 TEST(BuiltInDefaultValueTest, ExistsForString) {
187 #if GTEST_HAS_GLOBAL_STRING
188 EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists());
189 #endif // GTEST_HAS_GLOBAL_STRING
191 EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
194 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
195 // value as BuiltInDefaultValue<T>::Get() does.
196 TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
197 EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
198 EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
199 EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL);
200 EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
203 // A type that's default constructible.
204 class MyDefaultConstructible {
206 MyDefaultConstructible() : value_(42) {}
208 int value() const { return value_; }
214 // A type that's not default constructible.
215 class MyNonDefaultConstructible {
217 // Does not have a default ctor.
218 explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
220 int value() const { return value_; }
228 TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
229 EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
232 TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
233 EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
236 #endif // GTEST_LANG_CXX11
238 TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
239 EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
242 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
243 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
244 EXPECT_DEATH_IF_SUPPORTED({
245 BuiltInDefaultValue<int&>::Get();
247 EXPECT_DEATH_IF_SUPPORTED({
248 BuiltInDefaultValue<const char&>::Get();
252 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
253 EXPECT_DEATH_IF_SUPPORTED({
254 BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
258 // Tests that DefaultValue<T>::IsSet() is false initially.
259 TEST(DefaultValueTest, IsInitiallyUnset) {
260 EXPECT_FALSE(DefaultValue<int>::IsSet());
261 EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
262 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
265 // Tests that DefaultValue<T> can be set and then unset.
266 TEST(DefaultValueTest, CanBeSetAndUnset) {
267 EXPECT_TRUE(DefaultValue<int>::Exists());
268 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
270 DefaultValue<int>::Set(1);
271 DefaultValue<const MyNonDefaultConstructible>::Set(
272 MyNonDefaultConstructible(42));
274 EXPECT_EQ(1, DefaultValue<int>::Get());
275 EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
277 EXPECT_TRUE(DefaultValue<int>::Exists());
278 EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
280 DefaultValue<int>::Clear();
281 DefaultValue<const MyNonDefaultConstructible>::Clear();
283 EXPECT_FALSE(DefaultValue<int>::IsSet());
284 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
286 EXPECT_TRUE(DefaultValue<int>::Exists());
287 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
290 // Tests that DefaultValue<T>::Get() returns the
291 // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
293 TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
294 EXPECT_FALSE(DefaultValue<int>::IsSet());
295 EXPECT_TRUE(DefaultValue<int>::Exists());
296 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());
297 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());
299 EXPECT_EQ(0, DefaultValue<int>::Get());
301 EXPECT_DEATH_IF_SUPPORTED({
302 DefaultValue<MyNonDefaultConstructible>::Get();
306 #if GTEST_HAS_STD_UNIQUE_PTR_
307 TEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {
308 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
309 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == NULL);
310 DefaultValue<std::unique_ptr<int>>::SetFactory([] {
311 return std::unique_ptr<int>(new int(42));
313 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
314 std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
317 #endif // GTEST_HAS_STD_UNIQUE_PTR_
319 // Tests that DefaultValue<void>::Get() returns void.
320 TEST(DefaultValueTest, GetWorksForVoid) {
321 return DefaultValue<void>::Get();
324 // Tests using DefaultValue with a reference type.
326 // Tests that DefaultValue<T&>::IsSet() is false initially.
327 TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
328 EXPECT_FALSE(DefaultValue<int&>::IsSet());
329 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
330 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
333 // Tests that DefaultValue<T&>::Exists is false initiallly.
334 TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
335 EXPECT_FALSE(DefaultValue<int&>::Exists());
336 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
337 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
340 // Tests that DefaultValue<T&> can be set and then unset.
341 TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
343 DefaultValue<const int&>::Set(n);
344 MyNonDefaultConstructible x(42);
345 DefaultValue<MyNonDefaultConstructible&>::Set(x);
347 EXPECT_TRUE(DefaultValue<const int&>::Exists());
348 EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
350 EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
351 EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
353 DefaultValue<const int&>::Clear();
354 DefaultValue<MyNonDefaultConstructible&>::Clear();
356 EXPECT_FALSE(DefaultValue<const int&>::Exists());
357 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
359 EXPECT_FALSE(DefaultValue<const int&>::IsSet());
360 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
363 // Tests that DefaultValue<T&>::Get() returns the
364 // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
366 TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
367 EXPECT_FALSE(DefaultValue<int&>::IsSet());
368 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
370 EXPECT_DEATH_IF_SUPPORTED({
371 DefaultValue<int&>::Get();
373 EXPECT_DEATH_IF_SUPPORTED({
374 DefaultValue<MyNonDefaultConstructible>::Get();
378 // Tests that ActionInterface can be implemented by defining the
381 typedef int MyGlobalFunction(bool, int);
383 class MyActionImpl : public ActionInterface<MyGlobalFunction> {
385 virtual int Perform(const tuple<bool, int>& args) {
386 return get<0>(args) ? get<1>(args) : 0;
390 TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
391 MyActionImpl my_action_impl;
392 (void)my_action_impl;
395 TEST(ActionInterfaceTest, MakeAction) {
396 Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
398 // When exercising the Perform() method of Action<F>, we must pass
399 // it a tuple whose size and type are compatible with F's argument
400 // types. For example, if F is int(), then Perform() takes a
401 // 0-tuple; if F is void(bool, int), then Perform() takes a
402 // tuple<bool, int>, and so on.
403 EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
406 // Tests that Action<F> can be contructed from a pointer to
407 // ActionInterface<F>.
408 TEST(ActionTest, CanBeConstructedFromActionInterface) {
409 Action<MyGlobalFunction> action(new MyActionImpl);
412 // Tests that Action<F> delegates actual work to ActionInterface<F>.
413 TEST(ActionTest, DelegatesWorkToActionInterface) {
414 const Action<MyGlobalFunction> action(new MyActionImpl);
416 EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
417 EXPECT_EQ(0, action.Perform(make_tuple(false, 1)));
420 // Tests that Action<F> can be copied.
421 TEST(ActionTest, IsCopyable) {
422 Action<MyGlobalFunction> a1(new MyActionImpl);
423 Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.
425 // a1 should continue to work after being copied from.
426 EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
427 EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
429 // a2 should work like the action it was copied from.
430 EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
431 EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
433 a2 = a1; // Tests the assignment operator.
435 // a1 should continue to work after being copied from.
436 EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
437 EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
439 // a2 should work like the action it was copied from.
440 EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
441 EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
444 // Tests that an Action<From> object can be converted to a
445 // compatible Action<To> object.
447 class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
449 virtual bool Perform(const tuple<int>& arg) {
450 return get<0>(arg) != 0;
454 #if !GTEST_OS_SYMBIAN
455 // Compiling this test on Nokia's Symbian compiler fails with:
456 // 'Result' is not a member of class 'testing::internal::Function<int>'
457 // (point of instantiation: '@unnamed@gmock_actions_test_cc@::
458 // ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')
459 // with no obvious fix.
460 TEST(ActionTest, CanBeConvertedToOtherActionType) {
461 const Action<bool(int)> a1(new IsNotZero); // NOLINT
462 const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT
463 EXPECT_EQ(1, a2.Perform(make_tuple('a')));
464 EXPECT_EQ(0, a2.Perform(make_tuple('\0')));
466 #endif // !GTEST_OS_SYMBIAN
468 // The following two classes are for testing MakePolymorphicAction().
470 // Implements a polymorphic action that returns the second of the
471 // arguments it receives.
472 class ReturnSecondArgumentAction {
474 // We want to verify that MakePolymorphicAction() can work with a
475 // polymorphic action whose Perform() method template is either
476 // const or not. This lets us verify the non-const case.
477 template <typename Result, typename ArgumentTuple>
478 Result Perform(const ArgumentTuple& args) { return get<1>(args); }
481 // Implements a polymorphic action that can be used in a nullary
482 // function to return 0.
483 class ReturnZeroFromNullaryFunctionAction {
485 // For testing that MakePolymorphicAction() works when the
486 // implementation class' Perform() method template takes only one
487 // template parameter.
489 // We want to verify that MakePolymorphicAction() can work with a
490 // polymorphic action whose Perform() method template is either
491 // const or not. This lets us verify the const case.
492 template <typename Result>
493 Result Perform(const tuple<>&) const { return 0; }
496 // These functions verify that MakePolymorphicAction() returns a
497 // PolymorphicAction<T> where T is the argument's type.
499 PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
500 return MakePolymorphicAction(ReturnSecondArgumentAction());
503 PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
504 ReturnZeroFromNullaryFunction() {
505 return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
508 // Tests that MakePolymorphicAction() turns a polymorphic action
509 // implementation class into a polymorphic action.
510 TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
511 Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT
512 EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0)));
515 // Tests that MakePolymorphicAction() works when the implementation
516 // class' Perform() method template has only one template parameter.
517 TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
518 Action<int()> a1 = ReturnZeroFromNullaryFunction();
519 EXPECT_EQ(0, a1.Perform(make_tuple()));
521 Action<void*()> a2 = ReturnZeroFromNullaryFunction();
522 EXPECT_TRUE(a2.Perform(make_tuple()) == NULL);
525 // Tests that Return() works as an action for void-returning
527 TEST(ReturnTest, WorksForVoid) {
528 const Action<void(int)> ret = Return(); // NOLINT
529 return ret.Perform(make_tuple(1));
532 // Tests that Return(v) returns v.
533 TEST(ReturnTest, ReturnsGivenValue) {
534 Action<int()> ret = Return(1); // NOLINT
535 EXPECT_EQ(1, ret.Perform(make_tuple()));
538 EXPECT_EQ(-5, ret.Perform(make_tuple()));
541 // Tests that Return("string literal") works.
542 TEST(ReturnTest, AcceptsStringLiteral) {
543 Action<const char*()> a1 = Return("Hello");
544 EXPECT_STREQ("Hello", a1.Perform(make_tuple()));
546 Action<std::string()> a2 = Return("world");
547 EXPECT_EQ("world", a2.Perform(make_tuple()));
550 // Test struct which wraps a vector of integers. Used in
551 // 'SupportsWrapperReturnType' test.
552 struct IntegerVectorWrapper {
553 std::vector<int> * v;
554 IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT
557 // Tests that Return() works when return type is a wrapper type.
558 TEST(ReturnTest, SupportsWrapperReturnType) {
559 // Initialize vector of integers.
561 for (int i = 0; i < 5; ++i) v.push_back(i);
563 // Return() called with 'v' as argument. The Action will return the same data
564 // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
565 Action<IntegerVectorWrapper()> a = Return(v);
566 const std::vector<int>& result = *(a.Perform(make_tuple()).v);
567 EXPECT_THAT(result, ::testing::ElementsAre(0, 1, 2, 3, 4));
570 // Tests that Return(v) is covaraint.
573 bool operator==(const Base&) { return true; }
576 struct Derived : public Base {
577 bool operator==(const Derived&) { return true; }
580 TEST(ReturnTest, IsCovariant) {
583 Action<Base*()> ret = Return(&base);
584 EXPECT_EQ(&base, ret.Perform(make_tuple()));
586 ret = Return(&derived);
587 EXPECT_EQ(&derived, ret.Perform(make_tuple()));
590 // Tests that the type of the value passed into Return is converted into T
591 // when the action is cast to Action<T(...)> rather than when the action is
592 // performed. See comments on testing::internal::ReturnAction in
593 // gmock-actions.h for more information.
596 explicit FromType(bool* is_converted) : converted_(is_converted) {}
597 bool* converted() const { return converted_; }
600 bool* const converted_;
602 GTEST_DISALLOW_ASSIGN_(FromType);
607 // Must allow implicit conversion due to use in ImplicitCast_<T>.
608 ToType(const FromType& x) { *x.converted() = true; } // NOLINT
611 TEST(ReturnTest, ConvertsArgumentWhenConverted) {
612 bool converted = false;
613 FromType x(&converted);
614 Action<ToType()> action(Return(x));
615 EXPECT_TRUE(converted) << "Return must convert its argument in its own "
616 << "conversion operator.";
618 action.Perform(tuple<>());
619 EXPECT_FALSE(converted) << "Action must NOT convert its argument "
620 << "when performed.";
623 class DestinationType {};
627 // Note: a non-const typecast operator.
628 operator DestinationType() { return DestinationType(); }
631 TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
633 Action<DestinationType()> action(Return(s));
636 // Tests that ReturnNull() returns NULL in a pointer-returning function.
637 TEST(ReturnNullTest, WorksInPointerReturningFunction) {
638 const Action<int*()> a1 = ReturnNull();
639 EXPECT_TRUE(a1.Perform(make_tuple()) == NULL);
641 const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT
642 EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL);
645 #if GTEST_HAS_STD_UNIQUE_PTR_
646 // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
648 TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
649 const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
650 EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr);
652 const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
653 EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr);
655 #endif // GTEST_HAS_STD_UNIQUE_PTR_
657 // Tests that ReturnRef(v) works for reference types.
658 TEST(ReturnRefTest, WorksForReference) {
660 const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT
662 EXPECT_EQ(&n, &ret.Perform(make_tuple(true)));
665 // Tests that ReturnRef(v) is covariant.
666 TEST(ReturnRefTest, IsCovariant) {
669 Action<Base&()> a = ReturnRef(base);
670 EXPECT_EQ(&base, &a.Perform(make_tuple()));
672 a = ReturnRef(derived);
673 EXPECT_EQ(&derived, &a.Perform(make_tuple()));
676 // Tests that ReturnRefOfCopy(v) works for reference types.
677 TEST(ReturnRefOfCopyTest, WorksForReference) {
679 const Action<const int&()> ret = ReturnRefOfCopy(n);
681 EXPECT_NE(&n, &ret.Perform(make_tuple()));
682 EXPECT_EQ(42, ret.Perform(make_tuple()));
685 EXPECT_NE(&n, &ret.Perform(make_tuple()));
686 EXPECT_EQ(42, ret.Perform(make_tuple()));
689 // Tests that ReturnRefOfCopy(v) is covariant.
690 TEST(ReturnRefOfCopyTest, IsCovariant) {
693 Action<Base&()> a = ReturnRefOfCopy(base);
694 EXPECT_NE(&base, &a.Perform(make_tuple()));
696 a = ReturnRefOfCopy(derived);
697 EXPECT_NE(&derived, &a.Perform(make_tuple()));
700 // Tests that DoDefault() does the default action for the mock method.
706 MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
707 MOCK_METHOD0(Foo, MyNonDefaultConstructible());
708 #if GTEST_HAS_STD_UNIQUE_PTR_
709 MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());
710 MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());
711 MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());
712 MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));
713 MOCK_METHOD2(TakeUnique,
714 int(const std::unique_ptr<int>&, std::unique_ptr<int>));
718 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
721 // Tests that DoDefault() returns the built-in default value for the
722 // return type by default.
723 TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
725 EXPECT_CALL(mock, IntFunc(_))
726 .WillOnce(DoDefault());
727 EXPECT_EQ(0, mock.IntFunc(true));
730 // Tests that DoDefault() throws (when exceptions are enabled) or aborts
731 // the process when there is no built-in default value for the return type.
732 TEST(DoDefaultDeathTest, DiesForUnknowType) {
734 EXPECT_CALL(mock, Foo())
735 .WillRepeatedly(DoDefault());
736 #if GTEST_HAS_EXCEPTIONS
737 EXPECT_ANY_THROW(mock.Foo());
739 EXPECT_DEATH_IF_SUPPORTED({
745 // Tests that using DoDefault() inside a composite action leads to a
748 void VoidFunc(bool /* flag */) {}
750 TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
752 EXPECT_CALL(mock, IntFunc(_))
753 .WillRepeatedly(DoAll(Invoke(VoidFunc),
756 // Ideally we should verify the error message as well. Sadly,
757 // EXPECT_DEATH() can only capture stderr, while Google Mock's
758 // errors are printed on stdout. Therefore we have to settle for
759 // not verifying the message.
760 EXPECT_DEATH_IF_SUPPORTED({
765 // Tests that DoDefault() returns the default value set by
766 // DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
767 TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
768 DefaultValue<int>::Set(1);
770 EXPECT_CALL(mock, IntFunc(_))
771 .WillOnce(DoDefault());
772 EXPECT_EQ(1, mock.IntFunc(false));
773 DefaultValue<int>::Clear();
776 // Tests that DoDefault() does the action specified by ON_CALL().
777 TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
779 ON_CALL(mock, IntFunc(_))
780 .WillByDefault(Return(2));
781 EXPECT_CALL(mock, IntFunc(_))
782 .WillOnce(DoDefault());
783 EXPECT_EQ(2, mock.IntFunc(false));
786 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
787 TEST(DoDefaultTest, CannotBeUsedInOnCall) {
789 EXPECT_NONFATAL_FAILURE({ // NOLINT
790 ON_CALL(mock, IntFunc(_))
791 .WillByDefault(DoDefault());
792 }, "DoDefault() cannot be used in ON_CALL()");
795 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
796 // the N-th (0-based) argument to v.
797 TEST(SetArgPointeeTest, SetsTheNthPointee) {
798 typedef void MyFunction(bool, int*, char*);
799 Action<MyFunction> a = SetArgPointee<1>(2);
803 a.Perform(make_tuple(true, &n, &ch));
807 a = SetArgPointee<2>('a');
810 a.Perform(make_tuple(true, &n, &ch));
815 #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
816 // Tests that SetArgPointee<N>() accepts a string literal.
817 // GCC prior to v4.0 and the Symbian compiler do not support this.
818 TEST(SetArgPointeeTest, AcceptsStringLiteral) {
819 typedef void MyFunction(std::string*, const char**);
820 Action<MyFunction> a = SetArgPointee<0>("hi");
822 const char* ptr = NULL;
823 a.Perform(make_tuple(&str, &ptr));
824 EXPECT_EQ("hi", str);
825 EXPECT_TRUE(ptr == NULL);
827 a = SetArgPointee<1>("world");
829 a.Perform(make_tuple(&str, &ptr));
831 EXPECT_STREQ("world", ptr);
834 TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
835 typedef void MyFunction(const wchar_t**);
836 Action<MyFunction> a = SetArgPointee<0>(L"world");
837 const wchar_t* ptr = NULL;
838 a.Perform(make_tuple(&ptr));
839 EXPECT_STREQ(L"world", ptr);
841 # if GTEST_HAS_STD_WSTRING
843 typedef void MyStringFunction(std::wstring*);
844 Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
845 std::wstring str = L"";
846 a2.Perform(make_tuple(&str));
847 EXPECT_EQ(L"world", str);
853 // Tests that SetArgPointee<N>() accepts a char pointer.
854 TEST(SetArgPointeeTest, AcceptsCharPointer) {
855 typedef void MyFunction(bool, std::string*, const char**);
856 const char* const hi = "hi";
857 Action<MyFunction> a = SetArgPointee<1>(hi);
859 const char* ptr = NULL;
860 a.Perform(make_tuple(true, &str, &ptr));
861 EXPECT_EQ("hi", str);
862 EXPECT_TRUE(ptr == NULL);
864 char world_array[] = "world";
865 char* const world = world_array;
866 a = SetArgPointee<2>(world);
868 a.Perform(make_tuple(true, &str, &ptr));
870 EXPECT_EQ(world, ptr);
873 TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
874 typedef void MyFunction(bool, const wchar_t**);
875 const wchar_t* const hi = L"hi";
876 Action<MyFunction> a = SetArgPointee<1>(hi);
877 const wchar_t* ptr = NULL;
878 a.Perform(make_tuple(true, &ptr));
881 # if GTEST_HAS_STD_WSTRING
883 typedef void MyStringFunction(bool, std::wstring*);
884 wchar_t world_array[] = L"world";
885 wchar_t* const world = world_array;
886 Action<MyStringFunction> a2 = SetArgPointee<1>(world);
888 a2.Perform(make_tuple(true, &str));
889 EXPECT_EQ(world_array, str);
893 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
894 // the N-th (0-based) argument to v.
895 TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
896 typedef void MyFunction(bool, int*, char*);
897 Action<MyFunction> a = SetArgumentPointee<1>(2);
901 a.Perform(make_tuple(true, &n, &ch));
905 a = SetArgumentPointee<2>('a');
908 a.Perform(make_tuple(true, &n, &ch));
913 // Sample functions and functors for testing Invoke() and etc.
914 int Nullary() { return 1; }
916 class NullaryFunctor {
918 int operator()() { return 2; }
922 void VoidNullary() { g_done = true; }
924 class VoidNullaryFunctor {
926 void operator()() { g_done = true; }
931 Foo() : value_(123) {}
933 int Nullary() const { return value_; }
939 // Tests InvokeWithoutArgs(function).
940 TEST(InvokeWithoutArgsTest, Function) {
941 // As an action that takes one argument.
942 Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT
943 EXPECT_EQ(1, a.Perform(make_tuple(2)));
945 // As an action that takes two arguments.
946 Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT
947 EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5)));
949 // As an action that returns void.
950 Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT
952 a3.Perform(make_tuple(1));
956 // Tests InvokeWithoutArgs(functor).
957 TEST(InvokeWithoutArgsTest, Functor) {
958 // As an action that takes no argument.
959 Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT
960 EXPECT_EQ(2, a.Perform(make_tuple()));
962 // As an action that takes three arguments.
963 Action<int(int, double, char)> a2 = // NOLINT
964 InvokeWithoutArgs(NullaryFunctor());
965 EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a')));
967 // As an action that returns void.
968 Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
970 a3.Perform(make_tuple());
974 // Tests InvokeWithoutArgs(obj_ptr, method).
975 TEST(InvokeWithoutArgsTest, Method) {
977 Action<int(bool, char)> a = // NOLINT
978 InvokeWithoutArgs(&foo, &Foo::Nullary);
979 EXPECT_EQ(123, a.Perform(make_tuple(true, 'a')));
982 // Tests using IgnoreResult() on a polymorphic action.
983 TEST(IgnoreResultTest, PolymorphicAction) {
984 Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT
985 a.Perform(make_tuple(1));
988 // Tests using IgnoreResult() on a monomorphic action.
995 TEST(IgnoreResultTest, MonomorphicAction) {
997 Action<void()> a = IgnoreResult(Invoke(ReturnOne));
998 a.Perform(make_tuple());
1002 // Tests using IgnoreResult() on an action that returns a class type.
1004 MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1006 return MyNonDefaultConstructible(42);
1009 TEST(IgnoreResultTest, ActionReturningClass) {
1011 Action<void(int)> a =
1012 IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
1013 a.Perform(make_tuple(2));
1014 EXPECT_TRUE(g_done);
1017 TEST(AssignTest, Int) {
1019 Action<void(int)> a = Assign(&x, 5);
1020 a.Perform(make_tuple(0));
1024 TEST(AssignTest, String) {
1026 Action<void(void)> a = Assign(&x, "Hello, world");
1027 a.Perform(make_tuple());
1028 EXPECT_EQ("Hello, world", x);
1031 TEST(AssignTest, CompatibleTypes) {
1033 Action<void(int)> a = Assign(&x, 5);
1034 a.Perform(make_tuple(0));
1035 EXPECT_DOUBLE_EQ(5, x);
1038 #if !GTEST_OS_WINDOWS_MOBILE
1040 class SetErrnoAndReturnTest : public testing::Test {
1042 virtual void SetUp() { errno = 0; }
1043 virtual void TearDown() { errno = 0; }
1046 TEST_F(SetErrnoAndReturnTest, Int) {
1047 Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1048 EXPECT_EQ(-5, a.Perform(make_tuple()));
1049 EXPECT_EQ(ENOTTY, errno);
1052 TEST_F(SetErrnoAndReturnTest, Ptr) {
1054 Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1055 EXPECT_EQ(&x, a.Perform(make_tuple()));
1056 EXPECT_EQ(ENOTTY, errno);
1059 TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1060 Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1061 EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple()));
1062 EXPECT_EQ(EINVAL, errno);
1065 #endif // !GTEST_OS_WINDOWS_MOBILE
1069 // Tests that ReferenceWrapper<T> is copyable.
1070 TEST(ByRefTest, IsCopyable) {
1071 const std::string s1 = "Hi";
1072 const std::string s2 = "Hello";
1074 ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper =
1076 const std::string& r1 = ref_wrapper;
1077 EXPECT_EQ(&s1, &r1);
1079 // Assigns a new value to ref_wrapper.
1080 ref_wrapper = ByRef(s2);
1081 const std::string& r2 = ref_wrapper;
1082 EXPECT_EQ(&s2, &r2);
1084 ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 =
1086 // Copies ref_wrapper1 to ref_wrapper.
1087 ref_wrapper = ref_wrapper1;
1088 const std::string& r3 = ref_wrapper;
1089 EXPECT_EQ(&s1, &r3);
1092 // Tests using ByRef() on a const value.
1093 TEST(ByRefTest, ConstValue) {
1095 // int& ref = ByRef(n); // This shouldn't compile - we have a
1096 // negative compilation test to catch it.
1097 const int& const_ref = ByRef(n);
1098 EXPECT_EQ(&n, &const_ref);
1101 // Tests using ByRef() on a non-const value.
1102 TEST(ByRefTest, NonConstValue) {
1105 // ByRef(n) can be used as either an int&,
1106 int& ref = ByRef(n);
1107 EXPECT_EQ(&n, &ref);
1110 const int& const_ref = ByRef(n);
1111 EXPECT_EQ(&n, &const_ref);
1114 // Tests explicitly specifying the type when using ByRef().
1115 TEST(ByRefTest, ExplicitType) {
1117 const int& r1 = ByRef<const int>(n);
1120 // ByRef<char>(n); // This shouldn't compile - we have a negative
1121 // compilation test to catch it.
1124 Derived& r2 = ByRef<Derived>(d);
1127 const Derived& r3 = ByRef<const Derived>(d);
1130 Base& r4 = ByRef<Base>(d);
1133 const Base& r5 = ByRef<const Base>(d);
1136 // The following shouldn't compile - we have a negative compilation
1140 // ByRef<Derived>(b);
1143 // Tests that Google Mock prints expression ByRef(x) as a reference to x.
1144 TEST(ByRefTest, PrintsCorrectly) {
1146 ::std::stringstream expected, actual;
1147 testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
1148 testing::internal::UniversalPrint(ByRef(n), &actual);
1149 EXPECT_EQ(expected.str(), actual.str());
1152 #if GTEST_HAS_STD_UNIQUE_PTR_
1154 std::unique_ptr<int> UniquePtrSource() {
1155 return std::unique_ptr<int>(new int(19));
1158 std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
1159 std::vector<std::unique_ptr<int>> out;
1160 out.emplace_back(new int(7));
1164 TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
1166 std::unique_ptr<int> i(new int(19));
1167 EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));
1168 EXPECT_CALL(mock, MakeVectorUnique())
1169 .WillOnce(Return(ByMove(VectorUniquePtrSource())));
1170 Derived* d = new Derived;
1171 EXPECT_CALL(mock, MakeUniqueBase())
1172 .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));
1174 std::unique_ptr<int> result1 = mock.MakeUnique();
1175 EXPECT_EQ(19, *result1);
1177 std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1178 EXPECT_EQ(1u, vresult.size());
1179 EXPECT_NE(nullptr, vresult[0]);
1180 EXPECT_EQ(7, *vresult[0]);
1182 std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
1183 EXPECT_EQ(d, result2.get());
1186 TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
1187 testing::MockFunction<void()> mock_function;
1189 std::unique_ptr<int> i(new int(19));
1190 EXPECT_CALL(mock_function, Call());
1191 EXPECT_CALL(mock, MakeUnique()).WillOnce(DoAll(
1192 InvokeWithoutArgs(&mock_function, &testing::MockFunction<void()>::Call),
1193 Return(ByMove(std::move(i)))));
1195 std::unique_ptr<int> result1 = mock.MakeUnique();
1196 EXPECT_EQ(19, *result1);
1199 TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1202 // Check default value
1203 DefaultValue<std::unique_ptr<int>>::SetFactory([] {
1204 return std::unique_ptr<int>(new int(42));
1206 EXPECT_EQ(42, *mock.MakeUnique());
1208 EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));
1209 EXPECT_CALL(mock, MakeVectorUnique())
1210 .WillRepeatedly(Invoke(VectorUniquePtrSource));
1211 std::unique_ptr<int> result1 = mock.MakeUnique();
1212 EXPECT_EQ(19, *result1);
1213 std::unique_ptr<int> result2 = mock.MakeUnique();
1214 EXPECT_EQ(19, *result2);
1215 EXPECT_NE(result1, result2);
1217 std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();
1218 EXPECT_EQ(1u, vresult.size());
1219 EXPECT_NE(nullptr, vresult[0]);
1220 EXPECT_EQ(7, *vresult[0]);
1223 TEST(MockMethodTest, CanTakeMoveOnlyValue) {
1225 auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
1227 EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
1230 // DoAll() does not compile, since it would move from its arguments twice.
1231 // EXPECT_CALL(mock, TakeUnique(_, _))
1232 // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
1234 EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))
1235 .WillOnce(Return(-7))
1236 .RetiresOnSaturation();
1237 EXPECT_CALL(mock, TakeUnique(testing::IsNull()))
1238 .WillOnce(Return(-1))
1239 .RetiresOnSaturation();
1241 EXPECT_EQ(5, mock.TakeUnique(make(5)));
1242 EXPECT_EQ(-7, mock.TakeUnique(make(7)));
1243 EXPECT_EQ(7, mock.TakeUnique(make(7)));
1244 EXPECT_EQ(7, mock.TakeUnique(make(7)));
1245 EXPECT_EQ(-1, mock.TakeUnique({}));
1247 // Some arguments are moved, some passed by reference.
1248 auto lvalue = make(6);
1249 EXPECT_CALL(mock, TakeUnique(_, _))
1250 .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {
1253 EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
1255 // The unique_ptr can be saved by the action.
1256 std::unique_ptr<int> saved;
1257 EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {
1258 saved = std::move(i);
1261 EXPECT_EQ(0, mock.TakeUnique(make(42)));
1262 EXPECT_EQ(42, *saved);
1265 #endif // GTEST_HAS_STD_UNIQUE_PTR_
1267 #if GTEST_LANG_CXX11
1268 // Tests for std::function based action.
1270 int Add(int val, int& ref, int* ptr) { // NOLINT
1271 int result = val + ref + *ptr;
1277 int Deref(std::unique_ptr<int> ptr) { return *ptr; }
1280 template <typename T>
1281 T operator()(T t) { return 2 * t; }
1284 std::unique_ptr<int> UniqueInt(int i) {
1285 return std::unique_ptr<int>(new int(i));
1288 TEST(FunctorActionTest, ActionFromFunction) {
1289 Action<int(int, int&, int*)> a = &Add;
1290 int x = 1, y = 2, z = 3;
1291 EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));
1295 Action<int(std::unique_ptr<int>)> a1 = &Deref;
1296 EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
1299 TEST(FunctorActionTest, ActionFromLambda) {
1300 Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };
1301 EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
1302 EXPECT_EQ(0, a1.Perform(make_tuple(false, 5)));
1304 std::unique_ptr<int> saved;
1305 Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {
1306 saved = std::move(p);
1308 a2.Perform(make_tuple(UniqueInt(5)));
1309 EXPECT_EQ(5, *saved);
1312 TEST(FunctorActionTest, PolymorphicFunctor) {
1313 Action<int(int)> ai = Double();
1314 EXPECT_EQ(2, ai.Perform(make_tuple(1)));
1315 Action<double(double)> ad = Double(); // Double? Double double!
1316 EXPECT_EQ(3.0, ad.Perform(make_tuple(1.5)));
1319 TEST(FunctorActionTest, TypeConversion) {
1320 // Numeric promotions are allowed.
1321 const Action<bool(int)> a1 = [](int i) { return i > 1; };
1322 const Action<int(bool)> a2 = Action<int(bool)>(a1);
1323 EXPECT_EQ(1, a1.Perform(make_tuple(42)));
1324 EXPECT_EQ(0, a2.Perform(make_tuple(42)));
1326 // Implicit constructors are allowed.
1327 const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };
1328 const Action<int(const char*)> s2 = Action<int(const char*)>(s1);
1329 EXPECT_EQ(0, s2.Perform(make_tuple("")));
1330 EXPECT_EQ(1, s2.Perform(make_tuple("hello")));
1332 // Also between the lambda and the action itself.
1333 const Action<bool(std::string)> x = [](Unused) { return 42; };
1334 EXPECT_TRUE(x.Perform(make_tuple("hello")));
1337 TEST(FunctorActionTest, UnusedArguments) {
1338 // Verify that users can ignore uninteresting arguments.
1339 Action<int(int, double y, double z)> a =
1340 [](int i, Unused, Unused) { return 2 * i; };
1341 tuple<int, double, double> dummy = make_tuple(3, 7.3, 9.44);
1342 EXPECT_EQ(6, a.Perform(dummy));
1345 // Test that basic built-in actions work with move-only arguments.
1346 // FIXME: Currently, almost all ActionInterface-based actions will not
1347 // work, even if they only try to use other, copyable arguments. Implement them
1348 // if necessary (but note that DoAll cannot work on non-copyable types anyway -
1349 // so maybe it's better to make users use lambdas instead.
1350 TEST(MoveOnlyArgumentsTest, ReturningActions) {
1351 Action<int(std::unique_ptr<int>)> a = Return(1);
1352 EXPECT_EQ(1, a.Perform(make_tuple(nullptr)));
1354 a = testing::WithoutArgs([]() { return 7; });
1355 EXPECT_EQ(7, a.Perform(make_tuple(nullptr)));
1357 Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
1359 a2.Perform(make_tuple(nullptr, &x));
1363 #endif // GTEST_LANG_CXX11
1365 } // Unnamed namespace
1368 #if _MSC_VER == 1900
1369 # pragma warning(pop)