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 // Author: wan@google.com (Zhanyong Wan)
32 // Google Mock - a framework for writing C++ mock classes.
34 // This file tests the built-in actions.
36 // Silence C4800 (C4800: 'int *const ': forcing value
37 // to bool 'true' or 'false') for MSVC 14,15
40 # pragma warning(push)
41 # pragma warning(disable:4800)
45 #include "gmock/gmock-actions.h"
50 #include "gmock/gmock.h"
51 #include "gmock/internal/gmock-port.h"
52 #include "gtest/gtest.h"
53 #include "gtest/gtest-spi.h"
57 // 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
;
64 using testing::DoDefault
;
65 using testing::IgnoreResult
;
66 using testing::Invoke
;
67 using testing::InvokeWithoutArgs
;
68 using testing::MakePolymorphicAction
;
70 using testing::PolymorphicAction
;
71 using testing::Return
;
72 using testing::ReturnNull
;
73 using testing::ReturnRef
;
74 using testing::ReturnRefOfCopy
;
75 using testing::SetArgPointee
;
76 using testing::SetArgumentPointee
;
77 using testing::Unused
;
80 using testing::internal::BuiltInDefaultValue
;
81 using testing::internal::Int64
;
82 using testing::internal::UInt64
;
83 using testing::make_tuple
;
85 using testing::tuple_element
;
87 #if !GTEST_OS_WINDOWS_MOBILE
88 using testing::SetErrnoAndReturn
;
91 #if GTEST_HAS_PROTOBUF_
92 using testing::internal::TestMessage
;
93 #endif // GTEST_HAS_PROTOBUF_
95 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
96 TEST(BuiltInDefaultValueTest
, IsNullForPointerTypes
) {
97 EXPECT_TRUE(BuiltInDefaultValue
<int*>::Get() == NULL
);
98 EXPECT_TRUE(BuiltInDefaultValue
<const char*>::Get() == NULL
);
99 EXPECT_TRUE(BuiltInDefaultValue
<void*>::Get() == NULL
);
102 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
103 TEST(BuiltInDefaultValueTest
, ExistsForPointerTypes
) {
104 EXPECT_TRUE(BuiltInDefaultValue
<int*>::Exists());
105 EXPECT_TRUE(BuiltInDefaultValue
<const char*>::Exists());
106 EXPECT_TRUE(BuiltInDefaultValue
<void*>::Exists());
109 // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
110 // built-in numeric type.
111 TEST(BuiltInDefaultValueTest
, IsZeroForNumericTypes
) {
112 EXPECT_EQ(0U, BuiltInDefaultValue
<unsigned char>::Get());
113 EXPECT_EQ(0, BuiltInDefaultValue
<signed char>::Get());
114 EXPECT_EQ(0, BuiltInDefaultValue
<char>::Get());
115 #if GMOCK_HAS_SIGNED_WCHAR_T_
116 EXPECT_EQ(0U, BuiltInDefaultValue
<unsigned wchar_t>::Get());
117 EXPECT_EQ(0, BuiltInDefaultValue
<signed wchar_t>::Get());
119 #if GMOCK_WCHAR_T_IS_NATIVE_
120 #if !defined(__WCHAR_UNSIGNED__)
121 EXPECT_EQ(0, BuiltInDefaultValue
<wchar_t>::Get());
123 EXPECT_EQ(0U, BuiltInDefaultValue
<wchar_t>::Get());
126 EXPECT_EQ(0U, BuiltInDefaultValue
<unsigned short>::Get()); // NOLINT
127 EXPECT_EQ(0, BuiltInDefaultValue
<signed short>::Get()); // NOLINT
128 EXPECT_EQ(0, BuiltInDefaultValue
<short>::Get()); // NOLINT
129 EXPECT_EQ(0U, BuiltInDefaultValue
<unsigned int>::Get());
130 EXPECT_EQ(0, BuiltInDefaultValue
<signed int>::Get());
131 EXPECT_EQ(0, BuiltInDefaultValue
<int>::Get());
132 EXPECT_EQ(0U, BuiltInDefaultValue
<unsigned long>::Get()); // NOLINT
133 EXPECT_EQ(0, BuiltInDefaultValue
<signed long>::Get()); // NOLINT
134 EXPECT_EQ(0, BuiltInDefaultValue
<long>::Get()); // NOLINT
135 EXPECT_EQ(0U, BuiltInDefaultValue
<UInt64
>::Get());
136 EXPECT_EQ(0, BuiltInDefaultValue
<Int64
>::Get());
137 EXPECT_EQ(0, BuiltInDefaultValue
<float>::Get());
138 EXPECT_EQ(0, BuiltInDefaultValue
<double>::Get());
141 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
142 // built-in numeric type.
143 TEST(BuiltInDefaultValueTest
, ExistsForNumericTypes
) {
144 EXPECT_TRUE(BuiltInDefaultValue
<unsigned char>::Exists());
145 EXPECT_TRUE(BuiltInDefaultValue
<signed char>::Exists());
146 EXPECT_TRUE(BuiltInDefaultValue
<char>::Exists());
147 #if GMOCK_HAS_SIGNED_WCHAR_T_
148 EXPECT_TRUE(BuiltInDefaultValue
<unsigned wchar_t>::Exists());
149 EXPECT_TRUE(BuiltInDefaultValue
<signed wchar_t>::Exists());
151 #if GMOCK_WCHAR_T_IS_NATIVE_
152 EXPECT_TRUE(BuiltInDefaultValue
<wchar_t>::Exists());
154 EXPECT_TRUE(BuiltInDefaultValue
<unsigned short>::Exists()); // NOLINT
155 EXPECT_TRUE(BuiltInDefaultValue
<signed short>::Exists()); // NOLINT
156 EXPECT_TRUE(BuiltInDefaultValue
<short>::Exists()); // NOLINT
157 EXPECT_TRUE(BuiltInDefaultValue
<unsigned int>::Exists());
158 EXPECT_TRUE(BuiltInDefaultValue
<signed int>::Exists());
159 EXPECT_TRUE(BuiltInDefaultValue
<int>::Exists());
160 EXPECT_TRUE(BuiltInDefaultValue
<unsigned long>::Exists()); // NOLINT
161 EXPECT_TRUE(BuiltInDefaultValue
<signed long>::Exists()); // NOLINT
162 EXPECT_TRUE(BuiltInDefaultValue
<long>::Exists()); // NOLINT
163 EXPECT_TRUE(BuiltInDefaultValue
<UInt64
>::Exists());
164 EXPECT_TRUE(BuiltInDefaultValue
<Int64
>::Exists());
165 EXPECT_TRUE(BuiltInDefaultValue
<float>::Exists());
166 EXPECT_TRUE(BuiltInDefaultValue
<double>::Exists());
169 // Tests that BuiltInDefaultValue<bool>::Get() returns false.
170 TEST(BuiltInDefaultValueTest
, IsFalseForBool
) {
171 EXPECT_FALSE(BuiltInDefaultValue
<bool>::Get());
174 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
175 TEST(BuiltInDefaultValueTest
, BoolExists
) {
176 EXPECT_TRUE(BuiltInDefaultValue
<bool>::Exists());
179 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
181 TEST(BuiltInDefaultValueTest
, IsEmptyStringForString
) {
182 #if GTEST_HAS_GLOBAL_STRING
183 EXPECT_EQ("", BuiltInDefaultValue
< ::string
>::Get());
184 #endif // GTEST_HAS_GLOBAL_STRING
186 EXPECT_EQ("", BuiltInDefaultValue
< ::std::string
>::Get());
189 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
191 TEST(BuiltInDefaultValueTest
, ExistsForString
) {
192 #if GTEST_HAS_GLOBAL_STRING
193 EXPECT_TRUE(BuiltInDefaultValue
< ::string
>::Exists());
194 #endif // GTEST_HAS_GLOBAL_STRING
196 EXPECT_TRUE(BuiltInDefaultValue
< ::std::string
>::Exists());
199 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
200 // value as BuiltInDefaultValue<T>::Get() does.
201 TEST(BuiltInDefaultValueTest
, WorksForConstTypes
) {
202 EXPECT_EQ("", BuiltInDefaultValue
<const std::string
>::Get());
203 EXPECT_EQ(0, BuiltInDefaultValue
<const int>::Get());
204 EXPECT_TRUE(BuiltInDefaultValue
<char* const>::Get() == NULL
);
205 EXPECT_FALSE(BuiltInDefaultValue
<const bool>::Get());
208 // A type that's default constructible.
209 class MyDefaultConstructible
{
211 MyDefaultConstructible() : value_(42) {}
213 int value() const { return value_
; }
219 // A type that's not default constructible.
220 class MyNonDefaultConstructible
{
222 // Does not have a default ctor.
223 explicit MyNonDefaultConstructible(int a_value
) : value_(a_value
) {}
225 int value() const { return value_
; }
233 TEST(BuiltInDefaultValueTest
, ExistsForDefaultConstructibleType
) {
234 EXPECT_TRUE(BuiltInDefaultValue
<MyDefaultConstructible
>::Exists());
237 TEST(BuiltInDefaultValueTest
, IsDefaultConstructedForDefaultConstructibleType
) {
238 EXPECT_EQ(42, BuiltInDefaultValue
<MyDefaultConstructible
>::Get().value());
241 #endif // GTEST_LANG_CXX11
243 TEST(BuiltInDefaultValueTest
, DoesNotExistForNonDefaultConstructibleType
) {
244 EXPECT_FALSE(BuiltInDefaultValue
<MyNonDefaultConstructible
>::Exists());
247 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
248 TEST(BuiltInDefaultValueDeathTest
, IsUndefinedForReferences
) {
249 EXPECT_DEATH_IF_SUPPORTED({
250 BuiltInDefaultValue
<int&>::Get();
252 EXPECT_DEATH_IF_SUPPORTED({
253 BuiltInDefaultValue
<const char&>::Get();
257 TEST(BuiltInDefaultValueDeathTest
, IsUndefinedForNonDefaultConstructibleType
) {
258 EXPECT_DEATH_IF_SUPPORTED({
259 BuiltInDefaultValue
<MyNonDefaultConstructible
>::Get();
263 // Tests that DefaultValue<T>::IsSet() is false initially.
264 TEST(DefaultValueTest
, IsInitiallyUnset
) {
265 EXPECT_FALSE(DefaultValue
<int>::IsSet());
266 EXPECT_FALSE(DefaultValue
<MyDefaultConstructible
>::IsSet());
267 EXPECT_FALSE(DefaultValue
<const MyNonDefaultConstructible
>::IsSet());
270 // Tests that DefaultValue<T> can be set and then unset.
271 TEST(DefaultValueTest
, CanBeSetAndUnset
) {
272 EXPECT_TRUE(DefaultValue
<int>::Exists());
273 EXPECT_FALSE(DefaultValue
<const MyNonDefaultConstructible
>::Exists());
275 DefaultValue
<int>::Set(1);
276 DefaultValue
<const MyNonDefaultConstructible
>::Set(
277 MyNonDefaultConstructible(42));
279 EXPECT_EQ(1, DefaultValue
<int>::Get());
280 EXPECT_EQ(42, DefaultValue
<const MyNonDefaultConstructible
>::Get().value());
282 EXPECT_TRUE(DefaultValue
<int>::Exists());
283 EXPECT_TRUE(DefaultValue
<const MyNonDefaultConstructible
>::Exists());
285 DefaultValue
<int>::Clear();
286 DefaultValue
<const MyNonDefaultConstructible
>::Clear();
288 EXPECT_FALSE(DefaultValue
<int>::IsSet());
289 EXPECT_FALSE(DefaultValue
<const MyNonDefaultConstructible
>::IsSet());
291 EXPECT_TRUE(DefaultValue
<int>::Exists());
292 EXPECT_FALSE(DefaultValue
<const MyNonDefaultConstructible
>::Exists());
295 // Tests that DefaultValue<T>::Get() returns the
296 // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
298 TEST(DefaultValueDeathTest
, GetReturnsBuiltInDefaultValueWhenUnset
) {
299 EXPECT_FALSE(DefaultValue
<int>::IsSet());
300 EXPECT_TRUE(DefaultValue
<int>::Exists());
301 EXPECT_FALSE(DefaultValue
<MyNonDefaultConstructible
>::IsSet());
302 EXPECT_FALSE(DefaultValue
<MyNonDefaultConstructible
>::Exists());
304 EXPECT_EQ(0, DefaultValue
<int>::Get());
306 EXPECT_DEATH_IF_SUPPORTED({
307 DefaultValue
<MyNonDefaultConstructible
>::Get();
311 #if GTEST_HAS_STD_UNIQUE_PTR_
312 TEST(DefaultValueTest
, GetWorksForMoveOnlyIfSet
) {
313 EXPECT_TRUE(DefaultValue
<std::unique_ptr
<int>>::Exists());
314 EXPECT_TRUE(DefaultValue
<std::unique_ptr
<int>>::Get() == NULL
);
315 DefaultValue
<std::unique_ptr
<int>>::SetFactory([] {
316 return std::unique_ptr
<int>(new int(42));
318 EXPECT_TRUE(DefaultValue
<std::unique_ptr
<int>>::Exists());
319 std::unique_ptr
<int> i
= DefaultValue
<std::unique_ptr
<int>>::Get();
322 #endif // GTEST_HAS_STD_UNIQUE_PTR_
324 // Tests that DefaultValue<void>::Get() returns void.
325 TEST(DefaultValueTest
, GetWorksForVoid
) {
326 return DefaultValue
<void>::Get();
329 // Tests using DefaultValue with a reference type.
331 // Tests that DefaultValue<T&>::IsSet() is false initially.
332 TEST(DefaultValueOfReferenceTest
, IsInitiallyUnset
) {
333 EXPECT_FALSE(DefaultValue
<int&>::IsSet());
334 EXPECT_FALSE(DefaultValue
<MyDefaultConstructible
&>::IsSet());
335 EXPECT_FALSE(DefaultValue
<MyNonDefaultConstructible
&>::IsSet());
338 // Tests that DefaultValue<T&>::Exists is false initiallly.
339 TEST(DefaultValueOfReferenceTest
, IsInitiallyNotExisting
) {
340 EXPECT_FALSE(DefaultValue
<int&>::Exists());
341 EXPECT_FALSE(DefaultValue
<MyDefaultConstructible
&>::Exists());
342 EXPECT_FALSE(DefaultValue
<MyNonDefaultConstructible
&>::Exists());
345 // Tests that DefaultValue<T&> can be set and then unset.
346 TEST(DefaultValueOfReferenceTest
, CanBeSetAndUnset
) {
348 DefaultValue
<const int&>::Set(n
);
349 MyNonDefaultConstructible
x(42);
350 DefaultValue
<MyNonDefaultConstructible
&>::Set(x
);
352 EXPECT_TRUE(DefaultValue
<const int&>::Exists());
353 EXPECT_TRUE(DefaultValue
<MyNonDefaultConstructible
&>::Exists());
355 EXPECT_EQ(&n
, &(DefaultValue
<const int&>::Get()));
356 EXPECT_EQ(&x
, &(DefaultValue
<MyNonDefaultConstructible
&>::Get()));
358 DefaultValue
<const int&>::Clear();
359 DefaultValue
<MyNonDefaultConstructible
&>::Clear();
361 EXPECT_FALSE(DefaultValue
<const int&>::Exists());
362 EXPECT_FALSE(DefaultValue
<MyNonDefaultConstructible
&>::Exists());
364 EXPECT_FALSE(DefaultValue
<const int&>::IsSet());
365 EXPECT_FALSE(DefaultValue
<MyNonDefaultConstructible
&>::IsSet());
368 // Tests that DefaultValue<T&>::Get() returns the
369 // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
371 TEST(DefaultValueOfReferenceDeathTest
, GetReturnsBuiltInDefaultValueWhenUnset
) {
372 EXPECT_FALSE(DefaultValue
<int&>::IsSet());
373 EXPECT_FALSE(DefaultValue
<MyNonDefaultConstructible
&>::IsSet());
375 EXPECT_DEATH_IF_SUPPORTED({
376 DefaultValue
<int&>::Get();
378 EXPECT_DEATH_IF_SUPPORTED({
379 DefaultValue
<MyNonDefaultConstructible
>::Get();
383 // Tests that ActionInterface can be implemented by defining the
386 typedef int MyGlobalFunction(bool, int);
388 class MyActionImpl
: public ActionInterface
<MyGlobalFunction
> {
390 virtual int Perform(const tuple
<bool, int>& args
) {
391 return get
<0>(args
) ? get
<1>(args
) : 0;
395 TEST(ActionInterfaceTest
, CanBeImplementedByDefiningPerform
) {
396 MyActionImpl my_action_impl
;
397 (void)my_action_impl
;
400 TEST(ActionInterfaceTest
, MakeAction
) {
401 Action
<MyGlobalFunction
> action
= MakeAction(new MyActionImpl
);
403 // When exercising the Perform() method of Action<F>, we must pass
404 // it a tuple whose size and type are compatible with F's argument
405 // types. For example, if F is int(), then Perform() takes a
406 // 0-tuple; if F is void(bool, int), then Perform() takes a
407 // tuple<bool, int>, and so on.
408 EXPECT_EQ(5, action
.Perform(make_tuple(true, 5)));
411 // Tests that Action<F> can be contructed from a pointer to
412 // ActionInterface<F>.
413 TEST(ActionTest
, CanBeConstructedFromActionInterface
) {
414 Action
<MyGlobalFunction
> action(new MyActionImpl
);
417 // Tests that Action<F> delegates actual work to ActionInterface<F>.
418 TEST(ActionTest
, DelegatesWorkToActionInterface
) {
419 const Action
<MyGlobalFunction
> action(new MyActionImpl
);
421 EXPECT_EQ(5, action
.Perform(make_tuple(true, 5)));
422 EXPECT_EQ(0, action
.Perform(make_tuple(false, 1)));
425 // Tests that Action<F> can be copied.
426 TEST(ActionTest
, IsCopyable
) {
427 Action
<MyGlobalFunction
> a1(new MyActionImpl
);
428 Action
<MyGlobalFunction
> a2(a1
); // Tests the copy constructor.
430 // a1 should continue to work after being copied from.
431 EXPECT_EQ(5, a1
.Perform(make_tuple(true, 5)));
432 EXPECT_EQ(0, a1
.Perform(make_tuple(false, 1)));
434 // a2 should work like the action it was copied from.
435 EXPECT_EQ(5, a2
.Perform(make_tuple(true, 5)));
436 EXPECT_EQ(0, a2
.Perform(make_tuple(false, 1)));
438 a2
= a1
; // Tests the assignment operator.
440 // a1 should continue to work after being copied from.
441 EXPECT_EQ(5, a1
.Perform(make_tuple(true, 5)));
442 EXPECT_EQ(0, a1
.Perform(make_tuple(false, 1)));
444 // a2 should work like the action it was copied from.
445 EXPECT_EQ(5, a2
.Perform(make_tuple(true, 5)));
446 EXPECT_EQ(0, a2
.Perform(make_tuple(false, 1)));
449 // Tests that an Action<From> object can be converted to a
450 // compatible Action<To> object.
452 class IsNotZero
: public ActionInterface
<bool(int)> { // NOLINT
454 virtual bool Perform(const tuple
<int>& arg
) {
455 return get
<0>(arg
) != 0;
459 #if !GTEST_OS_SYMBIAN
460 // Compiling this test on Nokia's Symbian compiler fails with:
461 // 'Result' is not a member of class 'testing::internal::Function<int>'
462 // (point of instantiation: '@unnamed@gmock_actions_test_cc@::
463 // ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')
464 // with no obvious fix.
465 TEST(ActionTest
, CanBeConvertedToOtherActionType
) {
466 const Action
<bool(int)> a1(new IsNotZero
); // NOLINT
467 const Action
<int(char)> a2
= Action
<int(char)>(a1
); // NOLINT
468 EXPECT_EQ(1, a2
.Perform(make_tuple('a')));
469 EXPECT_EQ(0, a2
.Perform(make_tuple('\0')));
471 #endif // !GTEST_OS_SYMBIAN
473 // The following two classes are for testing MakePolymorphicAction().
475 // Implements a polymorphic action that returns the second of the
476 // arguments it receives.
477 class ReturnSecondArgumentAction
{
479 // We want to verify that MakePolymorphicAction() can work with a
480 // polymorphic action whose Perform() method template is either
481 // const or not. This lets us verify the non-const case.
482 template <typename Result
, typename ArgumentTuple
>
483 Result
Perform(const ArgumentTuple
& args
) { return get
<1>(args
); }
486 // Implements a polymorphic action that can be used in a nullary
487 // function to return 0.
488 class ReturnZeroFromNullaryFunctionAction
{
490 // For testing that MakePolymorphicAction() works when the
491 // implementation class' Perform() method template takes only one
492 // template parameter.
494 // We want to verify that MakePolymorphicAction() can work with a
495 // polymorphic action whose Perform() method template is either
496 // const or not. This lets us verify the const case.
497 template <typename Result
>
498 Result
Perform(const tuple
<>&) const { return 0; }
501 // These functions verify that MakePolymorphicAction() returns a
502 // PolymorphicAction<T> where T is the argument's type.
504 PolymorphicAction
<ReturnSecondArgumentAction
> ReturnSecondArgument() {
505 return MakePolymorphicAction(ReturnSecondArgumentAction());
508 PolymorphicAction
<ReturnZeroFromNullaryFunctionAction
>
509 ReturnZeroFromNullaryFunction() {
510 return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
513 // Tests that MakePolymorphicAction() turns a polymorphic action
514 // implementation class into a polymorphic action.
515 TEST(MakePolymorphicActionTest
, ConstructsActionFromImpl
) {
516 Action
<int(bool, int, double)> a1
= ReturnSecondArgument(); // NOLINT
517 EXPECT_EQ(5, a1
.Perform(make_tuple(false, 5, 2.0)));
520 // Tests that MakePolymorphicAction() works when the implementation
521 // class' Perform() method template has only one template parameter.
522 TEST(MakePolymorphicActionTest
, WorksWhenPerformHasOneTemplateParameter
) {
523 Action
<int()> a1
= ReturnZeroFromNullaryFunction();
524 EXPECT_EQ(0, a1
.Perform(make_tuple()));
526 Action
<void*()> a2
= ReturnZeroFromNullaryFunction();
527 EXPECT_TRUE(a2
.Perform(make_tuple()) == NULL
);
530 // Tests that Return() works as an action for void-returning
532 TEST(ReturnTest
, WorksForVoid
) {
533 const Action
<void(int)> ret
= Return(); // NOLINT
534 return ret
.Perform(make_tuple(1));
537 // Tests that Return(v) returns v.
538 TEST(ReturnTest
, ReturnsGivenValue
) {
539 Action
<int()> ret
= Return(1); // NOLINT
540 EXPECT_EQ(1, ret
.Perform(make_tuple()));
543 EXPECT_EQ(-5, ret
.Perform(make_tuple()));
546 // Tests that Return("string literal") works.
547 TEST(ReturnTest
, AcceptsStringLiteral
) {
548 Action
<const char*()> a1
= Return("Hello");
549 EXPECT_STREQ("Hello", a1
.Perform(make_tuple()));
551 Action
<std::string()> a2
= Return("world");
552 EXPECT_EQ("world", a2
.Perform(make_tuple()));
555 // Test struct which wraps a vector of integers. Used in
556 // 'SupportsWrapperReturnType' test.
557 struct IntegerVectorWrapper
{
558 std::vector
<int> * v
;
559 IntegerVectorWrapper(std::vector
<int>& _v
) : v(&_v
) {} // NOLINT
562 // Tests that Return() works when return type is a wrapper type.
563 TEST(ReturnTest
, SupportsWrapperReturnType
) {
564 // Initialize vector of integers.
566 for (int i
= 0; i
< 5; ++i
) v
.push_back(i
);
568 // Return() called with 'v' as argument. The Action will return the same data
569 // as 'v' (copy) but it will be wrapped in an IntegerVectorWrapper.
570 Action
<IntegerVectorWrapper()> a
= Return(v
);
571 const std::vector
<int>& result
= *(a
.Perform(make_tuple()).v
);
572 EXPECT_THAT(result
, ::testing::ElementsAre(0, 1, 2, 3, 4));
575 // Tests that Return(v) is covaraint.
578 bool operator==(const Base
&) { return true; }
581 struct Derived
: public Base
{
582 bool operator==(const Derived
&) { return true; }
585 TEST(ReturnTest
, IsCovariant
) {
588 Action
<Base
*()> ret
= Return(&base
);
589 EXPECT_EQ(&base
, ret
.Perform(make_tuple()));
591 ret
= Return(&derived
);
592 EXPECT_EQ(&derived
, ret
.Perform(make_tuple()));
595 // Tests that the type of the value passed into Return is converted into T
596 // when the action is cast to Action<T(...)> rather than when the action is
597 // performed. See comments on testing::internal::ReturnAction in
598 // gmock-actions.h for more information.
601 explicit FromType(bool* is_converted
) : converted_(is_converted
) {}
602 bool* converted() const { return converted_
; }
605 bool* const converted_
;
607 GTEST_DISALLOW_ASSIGN_(FromType
);
612 // Must allow implicit conversion due to use in ImplicitCast_<T>.
613 ToType(const FromType
& x
) { *x
.converted() = true; } // NOLINT
616 TEST(ReturnTest
, ConvertsArgumentWhenConverted
) {
617 bool converted
= false;
618 FromType
x(&converted
);
619 Action
<ToType()> action(Return(x
));
620 EXPECT_TRUE(converted
) << "Return must convert its argument in its own "
621 << "conversion operator.";
623 action
.Perform(tuple
<>());
624 EXPECT_FALSE(converted
) << "Action must NOT convert its argument "
625 << "when performed.";
628 class DestinationType
{};
632 // Note: a non-const typecast operator.
633 operator DestinationType() { return DestinationType(); }
636 TEST(ReturnTest
, CanConvertArgumentUsingNonConstTypeCastOperator
) {
638 Action
<DestinationType()> action(Return(s
));
641 // Tests that ReturnNull() returns NULL in a pointer-returning function.
642 TEST(ReturnNullTest
, WorksInPointerReturningFunction
) {
643 const Action
<int*()> a1
= ReturnNull();
644 EXPECT_TRUE(a1
.Perform(make_tuple()) == NULL
);
646 const Action
<const char*(bool)> a2
= ReturnNull(); // NOLINT
647 EXPECT_TRUE(a2
.Perform(make_tuple(true)) == NULL
);
650 #if GTEST_HAS_STD_UNIQUE_PTR_
651 // Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
653 TEST(ReturnNullTest
, WorksInSmartPointerReturningFunction
) {
654 const Action
<std::unique_ptr
<const int>()> a1
= ReturnNull();
655 EXPECT_TRUE(a1
.Perform(make_tuple()) == nullptr);
657 const Action
<std::shared_ptr
<int>(std::string
)> a2
= ReturnNull();
658 EXPECT_TRUE(a2
.Perform(make_tuple("foo")) == nullptr);
660 #endif // GTEST_HAS_STD_UNIQUE_PTR_
662 // Tests that ReturnRef(v) works for reference types.
663 TEST(ReturnRefTest
, WorksForReference
) {
665 const Action
<const int&(bool)> ret
= ReturnRef(n
); // NOLINT
667 EXPECT_EQ(&n
, &ret
.Perform(make_tuple(true)));
670 // Tests that ReturnRef(v) is covariant.
671 TEST(ReturnRefTest
, IsCovariant
) {
674 Action
<Base
&()> a
= ReturnRef(base
);
675 EXPECT_EQ(&base
, &a
.Perform(make_tuple()));
677 a
= ReturnRef(derived
);
678 EXPECT_EQ(&derived
, &a
.Perform(make_tuple()));
681 // Tests that ReturnRefOfCopy(v) works for reference types.
682 TEST(ReturnRefOfCopyTest
, WorksForReference
) {
684 const Action
<const int&()> ret
= ReturnRefOfCopy(n
);
686 EXPECT_NE(&n
, &ret
.Perform(make_tuple()));
687 EXPECT_EQ(42, ret
.Perform(make_tuple()));
690 EXPECT_NE(&n
, &ret
.Perform(make_tuple()));
691 EXPECT_EQ(42, ret
.Perform(make_tuple()));
694 // Tests that ReturnRefOfCopy(v) is covariant.
695 TEST(ReturnRefOfCopyTest
, IsCovariant
) {
698 Action
<Base
&()> a
= ReturnRefOfCopy(base
);
699 EXPECT_NE(&base
, &a
.Perform(make_tuple()));
701 a
= ReturnRefOfCopy(derived
);
702 EXPECT_NE(&derived
, &a
.Perform(make_tuple()));
705 // Tests that DoDefault() does the default action for the mock method.
711 MOCK_METHOD1(IntFunc
, int(bool flag
)); // NOLINT
712 MOCK_METHOD0(Foo
, MyNonDefaultConstructible());
713 #if GTEST_HAS_STD_UNIQUE_PTR_
714 MOCK_METHOD0(MakeUnique
, std::unique_ptr
<int>());
715 MOCK_METHOD0(MakeUniqueBase
, std::unique_ptr
<Base
>());
716 MOCK_METHOD0(MakeVectorUnique
, std::vector
<std::unique_ptr
<int>>());
717 MOCK_METHOD1(TakeUnique
, int(std::unique_ptr
<int>));
718 MOCK_METHOD2(TakeUnique
,
719 int(const std::unique_ptr
<int>&, std::unique_ptr
<int>));
723 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass
);
726 // Tests that DoDefault() returns the built-in default value for the
727 // return type by default.
728 TEST(DoDefaultTest
, ReturnsBuiltInDefaultValueByDefault
) {
730 EXPECT_CALL(mock
, IntFunc(_
))
731 .WillOnce(DoDefault());
732 EXPECT_EQ(0, mock
.IntFunc(true));
735 // Tests that DoDefault() throws (when exceptions are enabled) or aborts
736 // the process when there is no built-in default value for the return type.
737 TEST(DoDefaultDeathTest
, DiesForUnknowType
) {
739 EXPECT_CALL(mock
, Foo())
740 .WillRepeatedly(DoDefault());
741 #if GTEST_HAS_EXCEPTIONS
742 EXPECT_ANY_THROW(mock
.Foo());
744 EXPECT_DEATH_IF_SUPPORTED({
750 // Tests that using DoDefault() inside a composite action leads to a
753 void VoidFunc(bool /* flag */) {}
755 TEST(DoDefaultDeathTest
, DiesIfUsedInCompositeAction
) {
757 EXPECT_CALL(mock
, IntFunc(_
))
758 .WillRepeatedly(DoAll(Invoke(VoidFunc
),
761 // Ideally we should verify the error message as well. Sadly,
762 // EXPECT_DEATH() can only capture stderr, while Google Mock's
763 // errors are printed on stdout. Therefore we have to settle for
764 // not verifying the message.
765 EXPECT_DEATH_IF_SUPPORTED({
770 // Tests that DoDefault() returns the default value set by
771 // DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
772 TEST(DoDefaultTest
, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne
) {
773 DefaultValue
<int>::Set(1);
775 EXPECT_CALL(mock
, IntFunc(_
))
776 .WillOnce(DoDefault());
777 EXPECT_EQ(1, mock
.IntFunc(false));
778 DefaultValue
<int>::Clear();
781 // Tests that DoDefault() does the action specified by ON_CALL().
782 TEST(DoDefaultTest
, DoesWhatOnCallSpecifies
) {
784 ON_CALL(mock
, IntFunc(_
))
785 .WillByDefault(Return(2));
786 EXPECT_CALL(mock
, IntFunc(_
))
787 .WillOnce(DoDefault());
788 EXPECT_EQ(2, mock
.IntFunc(false));
791 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
792 TEST(DoDefaultTest
, CannotBeUsedInOnCall
) {
794 EXPECT_NONFATAL_FAILURE({ // NOLINT
795 ON_CALL(mock
, IntFunc(_
))
796 .WillByDefault(DoDefault());
797 }, "DoDefault() cannot be used in ON_CALL()");
800 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
801 // the N-th (0-based) argument to v.
802 TEST(SetArgPointeeTest
, SetsTheNthPointee
) {
803 typedef void MyFunction(bool, int*, char*);
804 Action
<MyFunction
> a
= SetArgPointee
<1>(2);
808 a
.Perform(make_tuple(true, &n
, &ch
));
812 a
= SetArgPointee
<2>('a');
815 a
.Perform(make_tuple(true, &n
, &ch
));
820 #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
821 // Tests that SetArgPointee<N>() accepts a string literal.
822 // GCC prior to v4.0 and the Symbian compiler do not support this.
823 TEST(SetArgPointeeTest
, AcceptsStringLiteral
) {
824 typedef void MyFunction(std::string
*, const char**);
825 Action
<MyFunction
> a
= SetArgPointee
<0>("hi");
827 const char* ptr
= NULL
;
828 a
.Perform(make_tuple(&str
, &ptr
));
829 EXPECT_EQ("hi", str
);
830 EXPECT_TRUE(ptr
== NULL
);
832 a
= SetArgPointee
<1>("world");
834 a
.Perform(make_tuple(&str
, &ptr
));
836 EXPECT_STREQ("world", ptr
);
839 TEST(SetArgPointeeTest
, AcceptsWideStringLiteral
) {
840 typedef void MyFunction(const wchar_t**);
841 Action
<MyFunction
> a
= SetArgPointee
<0>(L
"world");
842 const wchar_t* ptr
= NULL
;
843 a
.Perform(make_tuple(&ptr
));
844 EXPECT_STREQ(L
"world", ptr
);
846 # if GTEST_HAS_STD_WSTRING
848 typedef void MyStringFunction(std::wstring
*);
849 Action
<MyStringFunction
> a2
= SetArgPointee
<0>(L
"world");
850 std::wstring str
= L
"";
851 a2
.Perform(make_tuple(&str
));
852 EXPECT_EQ(L
"world", str
);
858 // Tests that SetArgPointee<N>() accepts a char pointer.
859 TEST(SetArgPointeeTest
, AcceptsCharPointer
) {
860 typedef void MyFunction(bool, std::string
*, const char**);
861 const char* const hi
= "hi";
862 Action
<MyFunction
> a
= SetArgPointee
<1>(hi
);
864 const char* ptr
= NULL
;
865 a
.Perform(make_tuple(true, &str
, &ptr
));
866 EXPECT_EQ("hi", str
);
867 EXPECT_TRUE(ptr
== NULL
);
869 char world_array
[] = "world";
870 char* const world
= world_array
;
871 a
= SetArgPointee
<2>(world
);
873 a
.Perform(make_tuple(true, &str
, &ptr
));
875 EXPECT_EQ(world
, ptr
);
878 TEST(SetArgPointeeTest
, AcceptsWideCharPointer
) {
879 typedef void MyFunction(bool, const wchar_t**);
880 const wchar_t* const hi
= L
"hi";
881 Action
<MyFunction
> a
= SetArgPointee
<1>(hi
);
882 const wchar_t* ptr
= NULL
;
883 a
.Perform(make_tuple(true, &ptr
));
886 # if GTEST_HAS_STD_WSTRING
888 typedef void MyStringFunction(bool, std::wstring
*);
889 wchar_t world_array
[] = L
"world";
890 wchar_t* const world
= world_array
;
891 Action
<MyStringFunction
> a2
= SetArgPointee
<1>(world
);
893 a2
.Perform(make_tuple(true, &str
));
894 EXPECT_EQ(world_array
, str
);
898 #if GTEST_HAS_PROTOBUF_
900 // Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf
901 // variable pointed to by the N-th (0-based) argument to proto_buffer.
902 TEST(SetArgPointeeTest
, SetsTheNthPointeeOfProtoBufferType
) {
903 TestMessage
* const msg
= new TestMessage
;
904 msg
->set_member("yes");
905 TestMessage orig_msg
;
906 orig_msg
.CopyFrom(*msg
);
908 Action
<void(bool, TestMessage
*)> a
= SetArgPointee
<1>(*msg
);
909 // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
910 // s.t. the action works even when the original proto_buffer has
911 // died. We ensure this behavior by deleting msg before using the
916 EXPECT_FALSE(orig_msg
.Equals(dest
));
917 a
.Perform(make_tuple(true, &dest
));
918 EXPECT_TRUE(orig_msg
.Equals(dest
));
921 // Tests that SetArgPointee<N>(proto_buffer) sets the
922 // ::ProtocolMessage variable pointed to by the N-th (0-based)
923 // argument to proto_buffer.
924 TEST(SetArgPointeeTest
, SetsTheNthPointeeOfProtoBufferBaseType
) {
925 TestMessage
* const msg
= new TestMessage
;
926 msg
->set_member("yes");
927 TestMessage orig_msg
;
928 orig_msg
.CopyFrom(*msg
);
930 Action
<void(bool, ::ProtocolMessage
*)> a
= SetArgPointee
<1>(*msg
);
931 // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
932 // s.t. the action works even when the original proto_buffer has
933 // died. We ensure this behavior by deleting msg before using the
938 ::ProtocolMessage
* const dest_base
= &dest
;
939 EXPECT_FALSE(orig_msg
.Equals(dest
));
940 a
.Perform(make_tuple(true, dest_base
));
941 EXPECT_TRUE(orig_msg
.Equals(dest
));
944 // Tests that SetArgPointee<N>(proto2_buffer) sets the v2
945 // protobuf variable pointed to by the N-th (0-based) argument to
947 TEST(SetArgPointeeTest
, SetsTheNthPointeeOfProto2BufferType
) {
948 using testing::internal::FooMessage
;
949 FooMessage
* const msg
= new FooMessage
;
950 msg
->set_int_field(2);
951 msg
->set_string_field("hi");
953 orig_msg
.CopyFrom(*msg
);
955 Action
<void(bool, FooMessage
*)> a
= SetArgPointee
<1>(*msg
);
956 // SetArgPointee<N>(proto2_buffer) makes a copy of
957 // proto2_buffer s.t. the action works even when the original
958 // proto2_buffer has died. We ensure this behavior by deleting msg
959 // before using the action.
963 dest
.set_int_field(0);
964 a
.Perform(make_tuple(true, &dest
));
965 EXPECT_EQ(2, dest
.int_field());
966 EXPECT_EQ("hi", dest
.string_field());
969 // Tests that SetArgPointee<N>(proto2_buffer) sets the
970 // proto2::Message variable pointed to by the N-th (0-based) argument
972 TEST(SetArgPointeeTest
, SetsTheNthPointeeOfProto2BufferBaseType
) {
973 using testing::internal::FooMessage
;
974 FooMessage
* const msg
= new FooMessage
;
975 msg
->set_int_field(2);
976 msg
->set_string_field("hi");
978 orig_msg
.CopyFrom(*msg
);
980 Action
<void(bool, ::proto2::Message
*)> a
= SetArgPointee
<1>(*msg
);
981 // SetArgPointee<N>(proto2_buffer) makes a copy of
982 // proto2_buffer s.t. the action works even when the original
983 // proto2_buffer has died. We ensure this behavior by deleting msg
984 // before using the action.
988 dest
.set_int_field(0);
989 ::proto2::Message
* const dest_base
= &dest
;
990 a
.Perform(make_tuple(true, dest_base
));
991 EXPECT_EQ(2, dest
.int_field());
992 EXPECT_EQ("hi", dest
.string_field());
995 #endif // GTEST_HAS_PROTOBUF_
997 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
998 // the N-th (0-based) argument to v.
999 TEST(SetArgumentPointeeTest
, SetsTheNthPointee
) {
1000 typedef void MyFunction(bool, int*, char*);
1001 Action
<MyFunction
> a
= SetArgumentPointee
<1>(2);
1005 a
.Perform(make_tuple(true, &n
, &ch
));
1007 EXPECT_EQ('\0', ch
);
1009 a
= SetArgumentPointee
<2>('a');
1012 a
.Perform(make_tuple(true, &n
, &ch
));
1017 #if GTEST_HAS_PROTOBUF_
1019 // Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf
1020 // variable pointed to by the N-th (0-based) argument to proto_buffer.
1021 TEST(SetArgumentPointeeTest
, SetsTheNthPointeeOfProtoBufferType
) {
1022 TestMessage
* const msg
= new TestMessage
;
1023 msg
->set_member("yes");
1024 TestMessage orig_msg
;
1025 orig_msg
.CopyFrom(*msg
);
1027 Action
<void(bool, TestMessage
*)> a
= SetArgumentPointee
<1>(*msg
);
1028 // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
1029 // s.t. the action works even when the original proto_buffer has
1030 // died. We ensure this behavior by deleting msg before using the
1035 EXPECT_FALSE(orig_msg
.Equals(dest
));
1036 a
.Perform(make_tuple(true, &dest
));
1037 EXPECT_TRUE(orig_msg
.Equals(dest
));
1040 // Tests that SetArgumentPointee<N>(proto_buffer) sets the
1041 // ::ProtocolMessage variable pointed to by the N-th (0-based)
1042 // argument to proto_buffer.
1043 TEST(SetArgumentPointeeTest
, SetsTheNthPointeeOfProtoBufferBaseType
) {
1044 TestMessage
* const msg
= new TestMessage
;
1045 msg
->set_member("yes");
1046 TestMessage orig_msg
;
1047 orig_msg
.CopyFrom(*msg
);
1049 Action
<void(bool, ::ProtocolMessage
*)> a
= SetArgumentPointee
<1>(*msg
);
1050 // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
1051 // s.t. the action works even when the original proto_buffer has
1052 // died. We ensure this behavior by deleting msg before using the
1057 ::ProtocolMessage
* const dest_base
= &dest
;
1058 EXPECT_FALSE(orig_msg
.Equals(dest
));
1059 a
.Perform(make_tuple(true, dest_base
));
1060 EXPECT_TRUE(orig_msg
.Equals(dest
));
1063 // Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
1064 // protobuf variable pointed to by the N-th (0-based) argument to
1066 TEST(SetArgumentPointeeTest
, SetsTheNthPointeeOfProto2BufferType
) {
1067 using testing::internal::FooMessage
;
1068 FooMessage
* const msg
= new FooMessage
;
1069 msg
->set_int_field(2);
1070 msg
->set_string_field("hi");
1071 FooMessage orig_msg
;
1072 orig_msg
.CopyFrom(*msg
);
1074 Action
<void(bool, FooMessage
*)> a
= SetArgumentPointee
<1>(*msg
);
1075 // SetArgumentPointee<N>(proto2_buffer) makes a copy of
1076 // proto2_buffer s.t. the action works even when the original
1077 // proto2_buffer has died. We ensure this behavior by deleting msg
1078 // before using the action.
1082 dest
.set_int_field(0);
1083 a
.Perform(make_tuple(true, &dest
));
1084 EXPECT_EQ(2, dest
.int_field());
1085 EXPECT_EQ("hi", dest
.string_field());
1088 // Tests that SetArgumentPointee<N>(proto2_buffer) sets the
1089 // proto2::Message variable pointed to by the N-th (0-based) argument
1090 // to proto2_buffer.
1091 TEST(SetArgumentPointeeTest
, SetsTheNthPointeeOfProto2BufferBaseType
) {
1092 using testing::internal::FooMessage
;
1093 FooMessage
* const msg
= new FooMessage
;
1094 msg
->set_int_field(2);
1095 msg
->set_string_field("hi");
1096 FooMessage orig_msg
;
1097 orig_msg
.CopyFrom(*msg
);
1099 Action
<void(bool, ::proto2::Message
*)> a
= SetArgumentPointee
<1>(*msg
);
1100 // SetArgumentPointee<N>(proto2_buffer) makes a copy of
1101 // proto2_buffer s.t. the action works even when the original
1102 // proto2_buffer has died. We ensure this behavior by deleting msg
1103 // before using the action.
1107 dest
.set_int_field(0);
1108 ::proto2::Message
* const dest_base
= &dest
;
1109 a
.Perform(make_tuple(true, dest_base
));
1110 EXPECT_EQ(2, dest
.int_field());
1111 EXPECT_EQ("hi", dest
.string_field());
1114 #endif // GTEST_HAS_PROTOBUF_
1116 // Sample functions and functors for testing Invoke() and etc.
1117 int Nullary() { return 1; }
1119 class NullaryFunctor
{
1121 int operator()() { return 2; }
1124 bool g_done
= false;
1125 void VoidNullary() { g_done
= true; }
1127 class VoidNullaryFunctor
{
1129 void operator()() { g_done
= true; }
1134 Foo() : value_(123) {}
1136 int Nullary() const { return value_
; }
1142 // Tests InvokeWithoutArgs(function).
1143 TEST(InvokeWithoutArgsTest
, Function
) {
1144 // As an action that takes one argument.
1145 Action
<int(int)> a
= InvokeWithoutArgs(Nullary
); // NOLINT
1146 EXPECT_EQ(1, a
.Perform(make_tuple(2)));
1148 // As an action that takes two arguments.
1149 Action
<int(int, double)> a2
= InvokeWithoutArgs(Nullary
); // NOLINT
1150 EXPECT_EQ(1, a2
.Perform(make_tuple(2, 3.5)));
1152 // As an action that returns void.
1153 Action
<void(int)> a3
= InvokeWithoutArgs(VoidNullary
); // NOLINT
1155 a3
.Perform(make_tuple(1));
1156 EXPECT_TRUE(g_done
);
1159 // Tests InvokeWithoutArgs(functor).
1160 TEST(InvokeWithoutArgsTest
, Functor
) {
1161 // As an action that takes no argument.
1162 Action
<int()> a
= InvokeWithoutArgs(NullaryFunctor()); // NOLINT
1163 EXPECT_EQ(2, a
.Perform(make_tuple()));
1165 // As an action that takes three arguments.
1166 Action
<int(int, double, char)> a2
= // NOLINT
1167 InvokeWithoutArgs(NullaryFunctor());
1168 EXPECT_EQ(2, a2
.Perform(make_tuple(3, 3.5, 'a')));
1170 // As an action that returns void.
1171 Action
<void()> a3
= InvokeWithoutArgs(VoidNullaryFunctor());
1173 a3
.Perform(make_tuple());
1174 EXPECT_TRUE(g_done
);
1177 // Tests InvokeWithoutArgs(obj_ptr, method).
1178 TEST(InvokeWithoutArgsTest
, Method
) {
1180 Action
<int(bool, char)> a
= // NOLINT
1181 InvokeWithoutArgs(&foo
, &Foo::Nullary
);
1182 EXPECT_EQ(123, a
.Perform(make_tuple(true, 'a')));
1185 // Tests using IgnoreResult() on a polymorphic action.
1186 TEST(IgnoreResultTest
, PolymorphicAction
) {
1187 Action
<void(int)> a
= IgnoreResult(Return(5)); // NOLINT
1188 a
.Perform(make_tuple(1));
1191 // Tests using IgnoreResult() on a monomorphic action.
1198 TEST(IgnoreResultTest
, MonomorphicAction
) {
1200 Action
<void()> a
= IgnoreResult(Invoke(ReturnOne
));
1201 a
.Perform(make_tuple());
1202 EXPECT_TRUE(g_done
);
1205 // Tests using IgnoreResult() on an action that returns a class type.
1207 MyNonDefaultConstructible
ReturnMyNonDefaultConstructible(double /* x */) {
1209 return MyNonDefaultConstructible(42);
1212 TEST(IgnoreResultTest
, ActionReturningClass
) {
1214 Action
<void(int)> a
=
1215 IgnoreResult(Invoke(ReturnMyNonDefaultConstructible
)); // NOLINT
1216 a
.Perform(make_tuple(2));
1217 EXPECT_TRUE(g_done
);
1220 TEST(AssignTest
, Int
) {
1222 Action
<void(int)> a
= Assign(&x
, 5);
1223 a
.Perform(make_tuple(0));
1227 TEST(AssignTest
, String
) {
1229 Action
<void(void)> a
= Assign(&x
, "Hello, world");
1230 a
.Perform(make_tuple());
1231 EXPECT_EQ("Hello, world", x
);
1234 TEST(AssignTest
, CompatibleTypes
) {
1236 Action
<void(int)> a
= Assign(&x
, 5);
1237 a
.Perform(make_tuple(0));
1238 EXPECT_DOUBLE_EQ(5, x
);
1241 #if !GTEST_OS_WINDOWS_MOBILE
1243 class SetErrnoAndReturnTest
: public testing::Test
{
1245 virtual void SetUp() { errno
= 0; }
1246 virtual void TearDown() { errno
= 0; }
1249 TEST_F(SetErrnoAndReturnTest
, Int
) {
1250 Action
<int(void)> a
= SetErrnoAndReturn(ENOTTY
, -5);
1251 EXPECT_EQ(-5, a
.Perform(make_tuple()));
1252 EXPECT_EQ(ENOTTY
, errno
);
1255 TEST_F(SetErrnoAndReturnTest
, Ptr
) {
1257 Action
<int*(void)> a
= SetErrnoAndReturn(ENOTTY
, &x
);
1258 EXPECT_EQ(&x
, a
.Perform(make_tuple()));
1259 EXPECT_EQ(ENOTTY
, errno
);
1262 TEST_F(SetErrnoAndReturnTest
, CompatibleTypes
) {
1263 Action
<double()> a
= SetErrnoAndReturn(EINVAL
, 5);
1264 EXPECT_DOUBLE_EQ(5.0, a
.Perform(make_tuple()));
1265 EXPECT_EQ(EINVAL
, errno
);
1268 #endif // !GTEST_OS_WINDOWS_MOBILE
1272 // Tests that ReferenceWrapper<T> is copyable.
1273 TEST(ByRefTest
, IsCopyable
) {
1274 const std::string s1
= "Hi";
1275 const std::string s2
= "Hello";
1277 ::testing::internal::ReferenceWrapper
<const std::string
> ref_wrapper
=
1279 const std::string
& r1
= ref_wrapper
;
1280 EXPECT_EQ(&s1
, &r1
);
1282 // Assigns a new value to ref_wrapper.
1283 ref_wrapper
= ByRef(s2
);
1284 const std::string
& r2
= ref_wrapper
;
1285 EXPECT_EQ(&s2
, &r2
);
1287 ::testing::internal::ReferenceWrapper
<const std::string
> ref_wrapper1
=
1289 // Copies ref_wrapper1 to ref_wrapper.
1290 ref_wrapper
= ref_wrapper1
;
1291 const std::string
& r3
= ref_wrapper
;
1292 EXPECT_EQ(&s1
, &r3
);
1295 // Tests using ByRef() on a const value.
1296 TEST(ByRefTest
, ConstValue
) {
1298 // int& ref = ByRef(n); // This shouldn't compile - we have a
1299 // negative compilation test to catch it.
1300 const int& const_ref
= ByRef(n
);
1301 EXPECT_EQ(&n
, &const_ref
);
1304 // Tests using ByRef() on a non-const value.
1305 TEST(ByRefTest
, NonConstValue
) {
1308 // ByRef(n) can be used as either an int&,
1309 int& ref
= ByRef(n
);
1310 EXPECT_EQ(&n
, &ref
);
1313 const int& const_ref
= ByRef(n
);
1314 EXPECT_EQ(&n
, &const_ref
);
1317 // Tests explicitly specifying the type when using ByRef().
1318 TEST(ByRefTest
, ExplicitType
) {
1320 const int& r1
= ByRef
<const int>(n
);
1323 // ByRef<char>(n); // This shouldn't compile - we have a negative
1324 // compilation test to catch it.
1327 Derived
& r2
= ByRef
<Derived
>(d
);
1330 const Derived
& r3
= ByRef
<const Derived
>(d
);
1333 Base
& r4
= ByRef
<Base
>(d
);
1336 const Base
& r5
= ByRef
<const Base
>(d
);
1339 // The following shouldn't compile - we have a negative compilation
1343 // ByRef<Derived>(b);
1346 // Tests that Google Mock prints expression ByRef(x) as a reference to x.
1347 TEST(ByRefTest
, PrintsCorrectly
) {
1349 ::std::stringstream expected
, actual
;
1350 testing::internal::UniversalPrinter
<const int&>::Print(n
, &expected
);
1351 testing::internal::UniversalPrint(ByRef(n
), &actual
);
1352 EXPECT_EQ(expected
.str(), actual
.str());
1355 #if GTEST_HAS_STD_UNIQUE_PTR_
1357 std::unique_ptr
<int> UniquePtrSource() {
1358 return std::unique_ptr
<int>(new int(19));
1361 std::vector
<std::unique_ptr
<int>> VectorUniquePtrSource() {
1362 std::vector
<std::unique_ptr
<int>> out
;
1363 out
.emplace_back(new int(7));
1367 TEST(MockMethodTest
, CanReturnMoveOnlyValue_Return
) {
1369 std::unique_ptr
<int> i(new int(19));
1370 EXPECT_CALL(mock
, MakeUnique()).WillOnce(Return(ByMove(std::move(i
))));
1371 EXPECT_CALL(mock
, MakeVectorUnique())
1372 .WillOnce(Return(ByMove(VectorUniquePtrSource())));
1373 Derived
* d
= new Derived
;
1374 EXPECT_CALL(mock
, MakeUniqueBase())
1375 .WillOnce(Return(ByMove(std::unique_ptr
<Derived
>(d
))));
1377 std::unique_ptr
<int> result1
= mock
.MakeUnique();
1378 EXPECT_EQ(19, *result1
);
1380 std::vector
<std::unique_ptr
<int>> vresult
= mock
.MakeVectorUnique();
1381 EXPECT_EQ(1u, vresult
.size());
1382 EXPECT_NE(nullptr, vresult
[0]);
1383 EXPECT_EQ(7, *vresult
[0]);
1385 std::unique_ptr
<Base
> result2
= mock
.MakeUniqueBase();
1386 EXPECT_EQ(d
, result2
.get());
1389 TEST(MockMethodTest
, CanReturnMoveOnlyValue_DoAllReturn
) {
1390 testing::MockFunction
<void()> mock_function
;
1392 std::unique_ptr
<int> i(new int(19));
1393 EXPECT_CALL(mock_function
, Call());
1394 EXPECT_CALL(mock
, MakeUnique()).WillOnce(DoAll(
1395 InvokeWithoutArgs(&mock_function
, &testing::MockFunction
<void()>::Call
),
1396 Return(ByMove(std::move(i
)))));
1398 std::unique_ptr
<int> result1
= mock
.MakeUnique();
1399 EXPECT_EQ(19, *result1
);
1402 TEST(MockMethodTest
, CanReturnMoveOnlyValue_Invoke
) {
1405 // Check default value
1406 DefaultValue
<std::unique_ptr
<int>>::SetFactory([] {
1407 return std::unique_ptr
<int>(new int(42));
1409 EXPECT_EQ(42, *mock
.MakeUnique());
1411 EXPECT_CALL(mock
, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource
));
1412 EXPECT_CALL(mock
, MakeVectorUnique())
1413 .WillRepeatedly(Invoke(VectorUniquePtrSource
));
1414 std::unique_ptr
<int> result1
= mock
.MakeUnique();
1415 EXPECT_EQ(19, *result1
);
1416 std::unique_ptr
<int> result2
= mock
.MakeUnique();
1417 EXPECT_EQ(19, *result2
);
1418 EXPECT_NE(result1
, result2
);
1420 std::vector
<std::unique_ptr
<int>> vresult
= mock
.MakeVectorUnique();
1421 EXPECT_EQ(1u, vresult
.size());
1422 EXPECT_NE(nullptr, vresult
[0]);
1423 EXPECT_EQ(7, *vresult
[0]);
1426 TEST(MockMethodTest
, CanTakeMoveOnlyValue
) {
1428 auto make
= [](int i
) { return std::unique_ptr
<int>(new int(i
)); };
1430 EXPECT_CALL(mock
, TakeUnique(_
)).WillRepeatedly([](std::unique_ptr
<int> i
) {
1433 // DoAll() does not compile, since it would move from its arguments twice.
1434 // EXPECT_CALL(mock, TakeUnique(_, _))
1435 // .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),
1437 EXPECT_CALL(mock
, TakeUnique(testing::Pointee(7)))
1438 .WillOnce(Return(-7))
1439 .RetiresOnSaturation();
1440 EXPECT_CALL(mock
, TakeUnique(testing::IsNull()))
1441 .WillOnce(Return(-1))
1442 .RetiresOnSaturation();
1444 EXPECT_EQ(5, mock
.TakeUnique(make(5)));
1445 EXPECT_EQ(-7, mock
.TakeUnique(make(7)));
1446 EXPECT_EQ(7, mock
.TakeUnique(make(7)));
1447 EXPECT_EQ(7, mock
.TakeUnique(make(7)));
1448 EXPECT_EQ(-1, mock
.TakeUnique({}));
1450 // Some arguments are moved, some passed by reference.
1451 auto lvalue
= make(6);
1452 EXPECT_CALL(mock
, TakeUnique(_
, _
))
1453 .WillOnce([](const std::unique_ptr
<int>& i
, std::unique_ptr
<int> j
) {
1456 EXPECT_EQ(42, mock
.TakeUnique(lvalue
, make(7)));
1458 // The unique_ptr can be saved by the action.
1459 std::unique_ptr
<int> saved
;
1460 EXPECT_CALL(mock
, TakeUnique(_
)).WillOnce([&saved
](std::unique_ptr
<int> i
) {
1461 saved
= std::move(i
);
1464 EXPECT_EQ(0, mock
.TakeUnique(make(42)));
1465 EXPECT_EQ(42, *saved
);
1468 #endif // GTEST_HAS_STD_UNIQUE_PTR_
1470 #if GTEST_LANG_CXX11
1471 // Tests for std::function based action.
1473 int Add(int val
, int& ref
, int* ptr
) { // NOLINT
1474 int result
= val
+ ref
+ *ptr
;
1480 int Deref(std::unique_ptr
<int> ptr
) { return *ptr
; }
1483 template <typename T
>
1484 T
operator()(T t
) { return 2 * t
; }
1487 std::unique_ptr
<int> UniqueInt(int i
) {
1488 return std::unique_ptr
<int>(new int(i
));
1491 TEST(FunctorActionTest
, ActionFromFunction
) {
1492 Action
<int(int, int&, int*)> a
= &Add
;
1493 int x
= 1, y
= 2, z
= 3;
1494 EXPECT_EQ(6, a
.Perform(std::forward_as_tuple(x
, y
, &z
)));
1498 Action
<int(std::unique_ptr
<int>)> a1
= &Deref
;
1499 EXPECT_EQ(7, a1
.Perform(std::make_tuple(UniqueInt(7))));
1502 TEST(FunctorActionTest
, ActionFromLambda
) {
1503 Action
<int(bool, int)> a1
= [](bool b
, int i
) { return b
? i
: 0; };
1504 EXPECT_EQ(5, a1
.Perform(make_tuple(true, 5)));
1505 EXPECT_EQ(0, a1
.Perform(make_tuple(false, 5)));
1507 std::unique_ptr
<int> saved
;
1508 Action
<void(std::unique_ptr
<int>)> a2
= [&saved
](std::unique_ptr
<int> p
) {
1509 saved
= std::move(p
);
1511 a2
.Perform(make_tuple(UniqueInt(5)));
1512 EXPECT_EQ(5, *saved
);
1515 TEST(FunctorActionTest
, PolymorphicFunctor
) {
1516 Action
<int(int)> ai
= Double();
1517 EXPECT_EQ(2, ai
.Perform(make_tuple(1)));
1518 Action
<double(double)> ad
= Double(); // Double? Double double!
1519 EXPECT_EQ(3.0, ad
.Perform(make_tuple(1.5)));
1522 TEST(FunctorActionTest
, TypeConversion
) {
1523 // Numeric promotions are allowed.
1524 const Action
<bool(int)> a1
= [](int i
) { return i
> 1; };
1525 const Action
<int(bool)> a2
= Action
<int(bool)>(a1
);
1526 EXPECT_EQ(1, a1
.Perform(make_tuple(42)));
1527 EXPECT_EQ(0, a2
.Perform(make_tuple(42)));
1529 // Implicit constructors are allowed.
1530 const Action
<bool(std::string
)> s1
= [](std::string s
) { return !s
.empty(); };
1531 const Action
<int(const char*)> s2
= Action
<int(const char*)>(s1
);
1532 EXPECT_EQ(0, s2
.Perform(make_tuple("")));
1533 EXPECT_EQ(1, s2
.Perform(make_tuple("hello")));
1535 // Also between the lambda and the action itself.
1536 const Action
<bool(std::string
)> x
= [](Unused
) { return 42; };
1537 EXPECT_TRUE(x
.Perform(make_tuple("hello")));
1540 TEST(FunctorActionTest
, UnusedArguments
) {
1541 // Verify that users can ignore uninteresting arguments.
1542 Action
<int(int, double y
, double z
)> a
=
1543 [](int i
, Unused
, Unused
) { return 2 * i
; };
1544 tuple
<int, double, double> dummy
= make_tuple(3, 7.3, 9.44);
1545 EXPECT_EQ(6, a
.Perform(dummy
));
1548 // Test that basic built-in actions work with move-only arguments.
1549 // TODO(rburny): Currently, almost all ActionInterface-based actions will not
1550 // work, even if they only try to use other, copyable arguments. Implement them
1551 // if necessary (but note that DoAll cannot work on non-copyable types anyway -
1552 // so maybe it's better to make users use lambdas instead.
1553 TEST(MoveOnlyArgumentsTest
, ReturningActions
) {
1554 Action
<int(std::unique_ptr
<int>)> a
= Return(1);
1555 EXPECT_EQ(1, a
.Perform(make_tuple(nullptr)));
1557 a
= testing::WithoutArgs([]() { return 7; });
1558 EXPECT_EQ(7, a
.Perform(make_tuple(nullptr)));
1560 Action
<void(std::unique_ptr
<int>, int*)> a2
= testing::SetArgPointee
<1>(3);
1562 a2
.Perform(make_tuple(nullptr, &x
));
1566 #endif // GTEST_LANG_CXX11
1568 } // Unnamed namespace
1571 #if _MSC_VER == 1900
1572 # pragma warning(pop)