1 // Copyright 2007, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
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
13 // distribution.
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.
17 //
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.
29 //
30 // Author: wan@google.com (Zhanyong Wan)
31
32 // Google Mock - a framework for writing C++ mock classes.
33 //
34 // This file tests the built-in actions.
35
36 #include "gmock/gmock-actions.h"
37 #include <algorithm>
38 #include <iterator>
39 #include <string>
40 #include "gmock/gmock.h"
41 #include "gmock/internal/gmock-port.h"
42 #include "gtest/gtest.h"
43 #include "gtest/gtest-spi.h"
44
45 namespace {
46
47 using ::std::tr1::get;
48 using ::std::tr1::make_tuple;
49 using ::std::tr1::tuple;
50 using ::std::tr1::tuple_element;
51 using testing::internal::BuiltInDefaultValue;
52 using testing::internal::Int64;
53 using testing::internal::UInt64;
54 // This list should be kept sorted.
55 using testing::_;
56 using testing::Action;
57 using testing::ActionInterface;
58 using testing::Assign;
59 using testing::ByRef;
60 using testing::DefaultValue;
61 using testing::DoDefault;
62 using testing::IgnoreResult;
63 using testing::Invoke;
64 using testing::InvokeWithoutArgs;
65 using testing::MakePolymorphicAction;
66 using testing::Ne;
67 using testing::PolymorphicAction;
68 using testing::Return;
69 using testing::ReturnNull;
70 using testing::ReturnRef;
71 using testing::ReturnRefOfCopy;
72 using testing::SetArgPointee;
73 using testing::SetArgumentPointee;
74
75 #if !GTEST_OS_WINDOWS_MOBILE
76 using testing::SetErrnoAndReturn;
77 #endif
78
79 #if GTEST_HAS_PROTOBUF_
80 using testing::internal::TestMessage;
81 #endif // GTEST_HAS_PROTOBUF_
82
83 // Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
TEST(BuiltInDefaultValueTest,IsNullForPointerTypes)84 TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
85 EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
86 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL);
87 EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL);
88 }
89
90 // Tests that BuiltInDefaultValue<T*>::Exists() return true.
TEST(BuiltInDefaultValueTest,ExistsForPointerTypes)91 TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
92 EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
93 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
94 EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
95 }
96
97 // Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
98 // built-in numeric type.
TEST(BuiltInDefaultValueTest,IsZeroForNumericTypes)99 TEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {
100 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());
101 EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());
102 EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());
103 #if GMOCK_HAS_SIGNED_WCHAR_T_
104 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned wchar_t>::Get());
105 EXPECT_EQ(0, BuiltInDefaultValue<signed wchar_t>::Get());
106 #endif
107 #if GMOCK_WCHAR_T_IS_NATIVE_
108 EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
109 #endif
110 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get()); // NOLINT
111 EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get()); // NOLINT
112 EXPECT_EQ(0, BuiltInDefaultValue<short>::Get()); // NOLINT
113 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());
114 EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());
115 EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());
116 EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get()); // NOLINT
117 EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get()); // NOLINT
118 EXPECT_EQ(0, BuiltInDefaultValue<long>::Get()); // NOLINT
119 EXPECT_EQ(0U, BuiltInDefaultValue<UInt64>::Get());
120 EXPECT_EQ(0, BuiltInDefaultValue<Int64>::Get());
121 EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());
122 EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());
123 }
124
125 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
126 // built-in numeric type.
TEST(BuiltInDefaultValueTest,ExistsForNumericTypes)127 TEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {
128 EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());
129 EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());
130 EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());
131 #if GMOCK_HAS_SIGNED_WCHAR_T_
132 EXPECT_TRUE(BuiltInDefaultValue<unsigned wchar_t>::Exists());
133 EXPECT_TRUE(BuiltInDefaultValue<signed wchar_t>::Exists());
134 #endif
135 #if GMOCK_WCHAR_T_IS_NATIVE_
136 EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
137 #endif
138 EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists()); // NOLINT
139 EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists()); // NOLINT
140 EXPECT_TRUE(BuiltInDefaultValue<short>::Exists()); // NOLINT
141 EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());
142 EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());
143 EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());
144 EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists()); // NOLINT
145 EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists()); // NOLINT
146 EXPECT_TRUE(BuiltInDefaultValue<long>::Exists()); // NOLINT
147 EXPECT_TRUE(BuiltInDefaultValue<UInt64>::Exists());
148 EXPECT_TRUE(BuiltInDefaultValue<Int64>::Exists());
149 EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());
150 EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());
151 }
152
153 // Tests that BuiltInDefaultValue<bool>::Get() returns false.
TEST(BuiltInDefaultValueTest,IsFalseForBool)154 TEST(BuiltInDefaultValueTest, IsFalseForBool) {
155 EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
156 }
157
158 // Tests that BuiltInDefaultValue<bool>::Exists() returns true.
TEST(BuiltInDefaultValueTest,BoolExists)159 TEST(BuiltInDefaultValueTest, BoolExists) {
160 EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
161 }
162
163 // Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
164 // string type.
TEST(BuiltInDefaultValueTest,IsEmptyStringForString)165 TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
166 #if GTEST_HAS_GLOBAL_STRING
167 EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
168 #endif // GTEST_HAS_GLOBAL_STRING
169
170 EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
171 }
172
173 // Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
174 // string type.
TEST(BuiltInDefaultValueTest,ExistsForString)175 TEST(BuiltInDefaultValueTest, ExistsForString) {
176 #if GTEST_HAS_GLOBAL_STRING
177 EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists());
178 #endif // GTEST_HAS_GLOBAL_STRING
179
180 EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
181 }
182
183 // Tests that BuiltInDefaultValue<const T>::Get() returns the same
184 // value as BuiltInDefaultValue<T>::Get() does.
TEST(BuiltInDefaultValueTest,WorksForConstTypes)185 TEST(BuiltInDefaultValueTest, WorksForConstTypes) {
186 EXPECT_EQ("", BuiltInDefaultValue<const std::string>::Get());
187 EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());
188 EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == NULL);
189 EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());
190 }
191
192 // Tests that BuiltInDefaultValue<T>::Get() aborts the program with
193 // the correct error message when T is a user-defined type.
194 struct UserType {
UserType__anon4e31d9990111::UserType195 UserType() : value(0) {}
196
197 int value;
198 };
199
TEST(BuiltInDefaultValueTest,UserTypeHasNoDefault)200 TEST(BuiltInDefaultValueTest, UserTypeHasNoDefault) {
201 EXPECT_FALSE(BuiltInDefaultValue<UserType>::Exists());
202 }
203
204 // Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
TEST(BuiltInDefaultValueDeathTest,IsUndefinedForReferences)205 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
206 EXPECT_DEATH_IF_SUPPORTED({
207 BuiltInDefaultValue<int&>::Get();
208 }, "");
209 EXPECT_DEATH_IF_SUPPORTED({
210 BuiltInDefaultValue<const char&>::Get();
211 }, "");
212 }
213
TEST(BuiltInDefaultValueDeathTest,IsUndefinedForUserTypes)214 TEST(BuiltInDefaultValueDeathTest, IsUndefinedForUserTypes) {
215 EXPECT_DEATH_IF_SUPPORTED({
216 BuiltInDefaultValue<UserType>::Get();
217 }, "");
218 }
219
220 // Tests that DefaultValue<T>::IsSet() is false initially.
TEST(DefaultValueTest,IsInitiallyUnset)221 TEST(DefaultValueTest, IsInitiallyUnset) {
222 EXPECT_FALSE(DefaultValue<int>::IsSet());
223 EXPECT_FALSE(DefaultValue<const UserType>::IsSet());
224 }
225
226 // Tests that DefaultValue<T> can be set and then unset.
TEST(DefaultValueTest,CanBeSetAndUnset)227 TEST(DefaultValueTest, CanBeSetAndUnset) {
228 EXPECT_TRUE(DefaultValue<int>::Exists());
229 EXPECT_FALSE(DefaultValue<const UserType>::Exists());
230
231 DefaultValue<int>::Set(1);
232 DefaultValue<const UserType>::Set(UserType());
233
234 EXPECT_EQ(1, DefaultValue<int>::Get());
235 EXPECT_EQ(0, DefaultValue<const UserType>::Get().value);
236
237 EXPECT_TRUE(DefaultValue<int>::Exists());
238 EXPECT_TRUE(DefaultValue<const UserType>::Exists());
239
240 DefaultValue<int>::Clear();
241 DefaultValue<const UserType>::Clear();
242
243 EXPECT_FALSE(DefaultValue<int>::IsSet());
244 EXPECT_FALSE(DefaultValue<const UserType>::IsSet());
245
246 EXPECT_TRUE(DefaultValue<int>::Exists());
247 EXPECT_FALSE(DefaultValue<const UserType>::Exists());
248 }
249
250 // Tests that DefaultValue<T>::Get() returns the
251 // BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
252 // false.
TEST(DefaultValueDeathTest,GetReturnsBuiltInDefaultValueWhenUnset)253 TEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
254 EXPECT_FALSE(DefaultValue<int>::IsSet());
255 EXPECT_TRUE(DefaultValue<int>::Exists());
256 EXPECT_FALSE(DefaultValue<UserType>::IsSet());
257 EXPECT_FALSE(DefaultValue<UserType>::Exists());
258
259 EXPECT_EQ(0, DefaultValue<int>::Get());
260
261 EXPECT_DEATH_IF_SUPPORTED({
262 DefaultValue<UserType>::Get();
263 }, "");
264 }
265
266 // Tests that DefaultValue<void>::Get() returns void.
TEST(DefaultValueTest,GetWorksForVoid)267 TEST(DefaultValueTest, GetWorksForVoid) {
268 return DefaultValue<void>::Get();
269 }
270
271 // Tests using DefaultValue with a reference type.
272
273 // Tests that DefaultValue<T&>::IsSet() is false initially.
TEST(DefaultValueOfReferenceTest,IsInitiallyUnset)274 TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
275 EXPECT_FALSE(DefaultValue<int&>::IsSet());
276 EXPECT_FALSE(DefaultValue<UserType&>::IsSet());
277 }
278
279 // Tests that DefaultValue<T&>::Exists is false initiallly.
TEST(DefaultValueOfReferenceTest,IsInitiallyNotExisting)280 TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
281 EXPECT_FALSE(DefaultValue<int&>::Exists());
282 EXPECT_FALSE(DefaultValue<UserType&>::Exists());
283 }
284
285 // Tests that DefaultValue<T&> can be set and then unset.
TEST(DefaultValueOfReferenceTest,CanBeSetAndUnset)286 TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
287 int n = 1;
288 DefaultValue<const int&>::Set(n);
289 UserType u;
290 DefaultValue<UserType&>::Set(u);
291
292 EXPECT_TRUE(DefaultValue<const int&>::Exists());
293 EXPECT_TRUE(DefaultValue<UserType&>::Exists());
294
295 EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
296 EXPECT_EQ(&u, &(DefaultValue<UserType&>::Get()));
297
298 DefaultValue<const int&>::Clear();
299 DefaultValue<UserType&>::Clear();
300
301 EXPECT_FALSE(DefaultValue<const int&>::Exists());
302 EXPECT_FALSE(DefaultValue<UserType&>::Exists());
303
304 EXPECT_FALSE(DefaultValue<const int&>::IsSet());
305 EXPECT_FALSE(DefaultValue<UserType&>::IsSet());
306 }
307
308 // Tests that DefaultValue<T&>::Get() returns the
309 // BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
310 // false.
TEST(DefaultValueOfReferenceDeathTest,GetReturnsBuiltInDefaultValueWhenUnset)311 TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
312 EXPECT_FALSE(DefaultValue<int&>::IsSet());
313 EXPECT_FALSE(DefaultValue<UserType&>::IsSet());
314
315 EXPECT_DEATH_IF_SUPPORTED({
316 DefaultValue<int&>::Get();
317 }, "");
318 EXPECT_DEATH_IF_SUPPORTED({
319 DefaultValue<UserType>::Get();
320 }, "");
321 }
322
323 // Tests that ActionInterface can be implemented by defining the
324 // Perform method.
325
326 typedef int MyFunction(bool, int);
327
328 class MyActionImpl : public ActionInterface<MyFunction> {
329 public:
Perform(const tuple<bool,int> & args)330 virtual int Perform(const tuple<bool, int>& args) {
331 return get<0>(args) ? get<1>(args) : 0;
332 }
333 };
334
TEST(ActionInterfaceTest,CanBeImplementedByDefiningPerform)335 TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
336 MyActionImpl my_action_impl;
337 (void)my_action_impl;
338 }
339
TEST(ActionInterfaceTest,MakeAction)340 TEST(ActionInterfaceTest, MakeAction) {
341 Action<MyFunction> action = MakeAction(new MyActionImpl);
342
343 // When exercising the Perform() method of Action<F>, we must pass
344 // it a tuple whose size and type are compatible with F's argument
345 // types. For example, if F is int(), then Perform() takes a
346 // 0-tuple; if F is void(bool, int), then Perform() takes a
347 // tuple<bool, int>, and so on.
348 EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
349 }
350
351 // Tests that Action<F> can be contructed from a pointer to
352 // ActionInterface<F>.
TEST(ActionTest,CanBeConstructedFromActionInterface)353 TEST(ActionTest, CanBeConstructedFromActionInterface) {
354 Action<MyFunction> action(new MyActionImpl);
355 }
356
357 // Tests that Action<F> delegates actual work to ActionInterface<F>.
TEST(ActionTest,DelegatesWorkToActionInterface)358 TEST(ActionTest, DelegatesWorkToActionInterface) {
359 const Action<MyFunction> action(new MyActionImpl);
360
361 EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
362 EXPECT_EQ(0, action.Perform(make_tuple(false, 1)));
363 }
364
365 // Tests that Action<F> can be copied.
TEST(ActionTest,IsCopyable)366 TEST(ActionTest, IsCopyable) {
367 Action<MyFunction> a1(new MyActionImpl);
368 Action<MyFunction> a2(a1); // Tests the copy constructor.
369
370 // a1 should continue to work after being copied from.
371 EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
372 EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
373
374 // a2 should work like the action it was copied from.
375 EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
376 EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
377
378 a2 = a1; // Tests the assignment operator.
379
380 // a1 should continue to work after being copied from.
381 EXPECT_EQ(5, a1.Perform(make_tuple(true, 5)));
382 EXPECT_EQ(0, a1.Perform(make_tuple(false, 1)));
383
384 // a2 should work like the action it was copied from.
385 EXPECT_EQ(5, a2.Perform(make_tuple(true, 5)));
386 EXPECT_EQ(0, a2.Perform(make_tuple(false, 1)));
387 }
388
389 // Tests that an Action<From> object can be converted to a
390 // compatible Action<To> object.
391
392 class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
393 public:
Perform(const tuple<int> & arg)394 virtual bool Perform(const tuple<int>& arg) {
395 return get<0>(arg) != 0;
396 }
397 };
398
399 #if !GTEST_OS_SYMBIAN
400 // Compiling this test on Nokia's Symbian compiler fails with:
401 // 'Result' is not a member of class 'testing::internal::Function<int>'
402 // (point of instantiation: '@unnamed@gmock_actions_test_cc@::
403 // ActionTest_CanBeConvertedToOtherActionType_Test::TestBody()')
404 // with no obvious fix.
TEST(ActionTest,CanBeConvertedToOtherActionType)405 TEST(ActionTest, CanBeConvertedToOtherActionType) {
406 const Action<bool(int)> a1(new IsNotZero); // NOLINT
407 const Action<int(char)> a2 = Action<int(char)>(a1); // NOLINT
408 EXPECT_EQ(1, a2.Perform(make_tuple('a')));
409 EXPECT_EQ(0, a2.Perform(make_tuple('\0')));
410 }
411 #endif // !GTEST_OS_SYMBIAN
412
413 // The following two classes are for testing MakePolymorphicAction().
414
415 // Implements a polymorphic action that returns the second of the
416 // arguments it receives.
417 class ReturnSecondArgumentAction {
418 public:
419 // We want to verify that MakePolymorphicAction() can work with a
420 // polymorphic action whose Perform() method template is either
421 // const or not. This lets us verify the non-const case.
422 template <typename Result, typename ArgumentTuple>
Perform(const ArgumentTuple & args)423 Result Perform(const ArgumentTuple& args) { return get<1>(args); }
424 };
425
426 // Implements a polymorphic action that can be used in a nullary
427 // function to return 0.
428 class ReturnZeroFromNullaryFunctionAction {
429 public:
430 // For testing that MakePolymorphicAction() works when the
431 // implementation class' Perform() method template takes only one
432 // template parameter.
433 //
434 // We want to verify that MakePolymorphicAction() can work with a
435 // polymorphic action whose Perform() method template is either
436 // const or not. This lets us verify the const case.
437 template <typename Result>
Perform(const tuple<> &) const438 Result Perform(const tuple<>&) const { return 0; }
439 };
440
441 // These functions verify that MakePolymorphicAction() returns a
442 // PolymorphicAction<T> where T is the argument's type.
443
ReturnSecondArgument()444 PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
445 return MakePolymorphicAction(ReturnSecondArgumentAction());
446 }
447
448 PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
ReturnZeroFromNullaryFunction()449 ReturnZeroFromNullaryFunction() {
450 return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
451 }
452
453 // Tests that MakePolymorphicAction() turns a polymorphic action
454 // implementation class into a polymorphic action.
TEST(MakePolymorphicActionTest,ConstructsActionFromImpl)455 TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
456 Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT
457 EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0)));
458 }
459
460 // Tests that MakePolymorphicAction() works when the implementation
461 // class' Perform() method template has only one template parameter.
TEST(MakePolymorphicActionTest,WorksWhenPerformHasOneTemplateParameter)462 TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
463 Action<int()> a1 = ReturnZeroFromNullaryFunction();
464 EXPECT_EQ(0, a1.Perform(make_tuple()));
465
466 Action<void*()> a2 = ReturnZeroFromNullaryFunction();
467 EXPECT_TRUE(a2.Perform(make_tuple()) == NULL);
468 }
469
470 // Tests that Return() works as an action for void-returning
471 // functions.
TEST(ReturnTest,WorksForVoid)472 TEST(ReturnTest, WorksForVoid) {
473 const Action<void(int)> ret = Return(); // NOLINT
474 return ret.Perform(make_tuple(1));
475 }
476
477 // Tests that Return(v) returns v.
TEST(ReturnTest,ReturnsGivenValue)478 TEST(ReturnTest, ReturnsGivenValue) {
479 Action<int()> ret = Return(1); // NOLINT
480 EXPECT_EQ(1, ret.Perform(make_tuple()));
481
482 ret = Return(-5);
483 EXPECT_EQ(-5, ret.Perform(make_tuple()));
484 }
485
486 // Tests that Return("string literal") works.
TEST(ReturnTest,AcceptsStringLiteral)487 TEST(ReturnTest, AcceptsStringLiteral) {
488 Action<const char*()> a1 = Return("Hello");
489 EXPECT_STREQ("Hello", a1.Perform(make_tuple()));
490
491 Action<std::string()> a2 = Return("world");
492 EXPECT_EQ("world", a2.Perform(make_tuple()));
493 }
494
495 // Tests that Return(v) is covaraint.
496
497 struct Base {
operator ==__anon4e31d9990111::Base498 bool operator==(const Base&) { return true; }
499 };
500
501 struct Derived : public Base {
operator ==__anon4e31d9990111::Derived502 bool operator==(const Derived&) { return true; }
503 };
504
TEST(ReturnTest,IsCovariant)505 TEST(ReturnTest, IsCovariant) {
506 Base base;
507 Derived derived;
508 Action<Base*()> ret = Return(&base);
509 EXPECT_EQ(&base, ret.Perform(make_tuple()));
510
511 ret = Return(&derived);
512 EXPECT_EQ(&derived, ret.Perform(make_tuple()));
513 }
514
515 // Tests that the type of the value passed into Return is converted into T
516 // when the action is cast to Action<T(...)> rather than when the action is
517 // performed. See comments on testing::internal::ReturnAction in
518 // gmock-actions.h for more information.
519 class FromType {
520 public:
FromType(bool * is_converted)521 explicit FromType(bool* is_converted) : converted_(is_converted) {}
converted() const522 bool* converted() const { return converted_; }
523
524 private:
525 bool* const converted_;
526
527 GTEST_DISALLOW_ASSIGN_(FromType);
528 };
529
530 class ToType {
531 public:
532 // Must allow implicit conversion due to use in ImplicitCast_<T>.
ToType(const FromType & x)533 ToType(const FromType& x) { *x.converted() = true; } // NOLINT
534 };
535
TEST(ReturnTest,ConvertsArgumentWhenConverted)536 TEST(ReturnTest, ConvertsArgumentWhenConverted) {
537 bool converted = false;
538 FromType x(&converted);
539 Action<ToType()> action(Return(x));
540 EXPECT_TRUE(converted) << "Return must convert its argument in its own "
541 << "conversion operator.";
542 converted = false;
543 action.Perform(tuple<>());
544 EXPECT_FALSE(converted) << "Action must NOT convert its argument "
545 << "when performed.";
546 }
547
548 class DestinationType {};
549
550 class SourceType {
551 public:
552 // Note: a non-const typecast operator.
operator DestinationType()553 operator DestinationType() { return DestinationType(); }
554 };
555
TEST(ReturnTest,CanConvertArgumentUsingNonConstTypeCastOperator)556 TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
557 SourceType s;
558 Action<DestinationType()> action(Return(s));
559 }
560
561 // Tests that ReturnNull() returns NULL in a pointer-returning function.
TEST(ReturnNullTest,WorksInPointerReturningFunction)562 TEST(ReturnNullTest, WorksInPointerReturningFunction) {
563 const Action<int*()> a1 = ReturnNull();
564 EXPECT_TRUE(a1.Perform(make_tuple()) == NULL);
565
566 const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT
567 EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL);
568 }
569
570 // Tests that ReturnRef(v) works for reference types.
TEST(ReturnRefTest,WorksForReference)571 TEST(ReturnRefTest, WorksForReference) {
572 const int n = 0;
573 const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT
574
575 EXPECT_EQ(&n, &ret.Perform(make_tuple(true)));
576 }
577
578 // Tests that ReturnRef(v) is covariant.
TEST(ReturnRefTest,IsCovariant)579 TEST(ReturnRefTest, IsCovariant) {
580 Base base;
581 Derived derived;
582 Action<Base&()> a = ReturnRef(base);
583 EXPECT_EQ(&base, &a.Perform(make_tuple()));
584
585 a = ReturnRef(derived);
586 EXPECT_EQ(&derived, &a.Perform(make_tuple()));
587 }
588
589 // Tests that ReturnRefOfCopy(v) works for reference types.
TEST(ReturnRefOfCopyTest,WorksForReference)590 TEST(ReturnRefOfCopyTest, WorksForReference) {
591 int n = 42;
592 const Action<const int&()> ret = ReturnRefOfCopy(n);
593
594 EXPECT_NE(&n, &ret.Perform(make_tuple()));
595 EXPECT_EQ(42, ret.Perform(make_tuple()));
596
597 n = 43;
598 EXPECT_NE(&n, &ret.Perform(make_tuple()));
599 EXPECT_EQ(42, ret.Perform(make_tuple()));
600 }
601
602 // Tests that ReturnRefOfCopy(v) is covariant.
TEST(ReturnRefOfCopyTest,IsCovariant)603 TEST(ReturnRefOfCopyTest, IsCovariant) {
604 Base base;
605 Derived derived;
606 Action<Base&()> a = ReturnRefOfCopy(base);
607 EXPECT_NE(&base, &a.Perform(make_tuple()));
608
609 a = ReturnRefOfCopy(derived);
610 EXPECT_NE(&derived, &a.Perform(make_tuple()));
611 }
612
613 // Tests that DoDefault() does the default action for the mock method.
614
615 class MyClass {};
616
617 class MockClass {
618 public:
MockClass()619 MockClass() {}
620
621 MOCK_METHOD1(IntFunc, int(bool flag)); // NOLINT
622 MOCK_METHOD0(Foo, MyClass());
623
624 private:
625 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockClass);
626 };
627
628 // Tests that DoDefault() returns the built-in default value for the
629 // return type by default.
TEST(DoDefaultTest,ReturnsBuiltInDefaultValueByDefault)630 TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
631 MockClass mock;
632 EXPECT_CALL(mock, IntFunc(_))
633 .WillOnce(DoDefault());
634 EXPECT_EQ(0, mock.IntFunc(true));
635 }
636
637 // Tests that DoDefault() aborts the process when there is no built-in
638 // default value for the return type.
TEST(DoDefaultDeathTest,DiesForUnknowType)639 TEST(DoDefaultDeathTest, DiesForUnknowType) {
640 MockClass mock;
641 EXPECT_CALL(mock, Foo())
642 .WillRepeatedly(DoDefault());
643 EXPECT_DEATH_IF_SUPPORTED({
644 mock.Foo();
645 }, "");
646 }
647
648 // Tests that using DoDefault() inside a composite action leads to a
649 // run-time error.
650
VoidFunc(bool)651 void VoidFunc(bool /* flag */) {}
652
TEST(DoDefaultDeathTest,DiesIfUsedInCompositeAction)653 TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
654 MockClass mock;
655 EXPECT_CALL(mock, IntFunc(_))
656 .WillRepeatedly(DoAll(Invoke(VoidFunc),
657 DoDefault()));
658
659 // Ideally we should verify the error message as well. Sadly,
660 // EXPECT_DEATH() can only capture stderr, while Google Mock's
661 // errors are printed on stdout. Therefore we have to settle for
662 // not verifying the message.
663 EXPECT_DEATH_IF_SUPPORTED({
664 mock.IntFunc(true);
665 }, "");
666 }
667
668 // Tests that DoDefault() returns the default value set by
669 // DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
TEST(DoDefaultTest,ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne)670 TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
671 DefaultValue<int>::Set(1);
672 MockClass mock;
673 EXPECT_CALL(mock, IntFunc(_))
674 .WillOnce(DoDefault());
675 EXPECT_EQ(1, mock.IntFunc(false));
676 DefaultValue<int>::Clear();
677 }
678
679 // Tests that DoDefault() does the action specified by ON_CALL().
TEST(DoDefaultTest,DoesWhatOnCallSpecifies)680 TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
681 MockClass mock;
682 ON_CALL(mock, IntFunc(_))
683 .WillByDefault(Return(2));
684 EXPECT_CALL(mock, IntFunc(_))
685 .WillOnce(DoDefault());
686 EXPECT_EQ(2, mock.IntFunc(false));
687 }
688
689 // Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
TEST(DoDefaultTest,CannotBeUsedInOnCall)690 TEST(DoDefaultTest, CannotBeUsedInOnCall) {
691 MockClass mock;
692 EXPECT_NONFATAL_FAILURE({ // NOLINT
693 ON_CALL(mock, IntFunc(_))
694 .WillByDefault(DoDefault());
695 }, "DoDefault() cannot be used in ON_CALL()");
696 }
697
698 // Tests that SetArgPointee<N>(v) sets the variable pointed to by
699 // the N-th (0-based) argument to v.
TEST(SetArgPointeeTest,SetsTheNthPointee)700 TEST(SetArgPointeeTest, SetsTheNthPointee) {
701 typedef void MyFunction(bool, int*, char*);
702 Action<MyFunction> a = SetArgPointee<1>(2);
703
704 int n = 0;
705 char ch = '\0';
706 a.Perform(make_tuple(true, &n, &ch));
707 EXPECT_EQ(2, n);
708 EXPECT_EQ('\0', ch);
709
710 a = SetArgPointee<2>('a');
711 n = 0;
712 ch = '\0';
713 a.Perform(make_tuple(true, &n, &ch));
714 EXPECT_EQ(0, n);
715 EXPECT_EQ('a', ch);
716 }
717
718 #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN)
719 // Tests that SetArgPointee<N>() accepts a string literal.
720 // GCC prior to v4.0 and the Symbian compiler do not support this.
TEST(SetArgPointeeTest,AcceptsStringLiteral)721 TEST(SetArgPointeeTest, AcceptsStringLiteral) {
722 typedef void MyFunction(std::string*, const char**);
723 Action<MyFunction> a = SetArgPointee<0>("hi");
724 std::string str;
725 const char* ptr = NULL;
726 a.Perform(make_tuple(&str, &ptr));
727 EXPECT_EQ("hi", str);
728 EXPECT_TRUE(ptr == NULL);
729
730 a = SetArgPointee<1>("world");
731 str = "";
732 a.Perform(make_tuple(&str, &ptr));
733 EXPECT_EQ("", str);
734 EXPECT_STREQ("world", ptr);
735 }
736
TEST(SetArgPointeeTest,AcceptsWideStringLiteral)737 TEST(SetArgPointeeTest, AcceptsWideStringLiteral) {
738 typedef void MyFunction(const wchar_t**);
739 Action<MyFunction> a = SetArgPointee<0>(L"world");
740 const wchar_t* ptr = NULL;
741 a.Perform(make_tuple(&ptr));
742 EXPECT_STREQ(L"world", ptr);
743
744 # if GTEST_HAS_STD_WSTRING
745
746 typedef void MyStringFunction(std::wstring*);
747 Action<MyStringFunction> a2 = SetArgPointee<0>(L"world");
748 std::wstring str = L"";
749 a2.Perform(make_tuple(&str));
750 EXPECT_EQ(L"world", str);
751
752 # endif
753 }
754 #endif
755
756 // Tests that SetArgPointee<N>() accepts a char pointer.
TEST(SetArgPointeeTest,AcceptsCharPointer)757 TEST(SetArgPointeeTest, AcceptsCharPointer) {
758 typedef void MyFunction(bool, std::string*, const char**);
759 const char* const hi = "hi";
760 Action<MyFunction> a = SetArgPointee<1>(hi);
761 std::string str;
762 const char* ptr = NULL;
763 a.Perform(make_tuple(true, &str, &ptr));
764 EXPECT_EQ("hi", str);
765 EXPECT_TRUE(ptr == NULL);
766
767 char world_array[] = "world";
768 char* const world = world_array;
769 a = SetArgPointee<2>(world);
770 str = "";
771 a.Perform(make_tuple(true, &str, &ptr));
772 EXPECT_EQ("", str);
773 EXPECT_EQ(world, ptr);
774 }
775
TEST(SetArgPointeeTest,AcceptsWideCharPointer)776 TEST(SetArgPointeeTest, AcceptsWideCharPointer) {
777 typedef void MyFunction(bool, const wchar_t**);
778 const wchar_t* const hi = L"hi";
779 Action<MyFunction> a = SetArgPointee<1>(hi);
780 const wchar_t* ptr = NULL;
781 a.Perform(make_tuple(true, &ptr));
782 EXPECT_EQ(hi, ptr);
783
784 # if GTEST_HAS_STD_WSTRING
785
786 typedef void MyStringFunction(bool, std::wstring*);
787 wchar_t world_array[] = L"world";
788 wchar_t* const world = world_array;
789 Action<MyStringFunction> a2 = SetArgPointee<1>(world);
790 std::wstring str;
791 a2.Perform(make_tuple(true, &str));
792 EXPECT_EQ(world_array, str);
793 # endif
794 }
795
796 #if GTEST_HAS_PROTOBUF_
797
798 // Tests that SetArgPointee<N>(proto_buffer) sets the v1 protobuf
799 // variable pointed to by the N-th (0-based) argument to proto_buffer.
TEST(SetArgPointeeTest,SetsTheNthPointeeOfProtoBufferType)800 TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
801 TestMessage* const msg = new TestMessage;
802 msg->set_member("yes");
803 TestMessage orig_msg;
804 orig_msg.CopyFrom(*msg);
805
806 Action<void(bool, TestMessage*)> a = SetArgPointee<1>(*msg);
807 // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
808 // s.t. the action works even when the original proto_buffer has
809 // died. We ensure this behavior by deleting msg before using the
810 // action.
811 delete msg;
812
813 TestMessage dest;
814 EXPECT_FALSE(orig_msg.Equals(dest));
815 a.Perform(make_tuple(true, &dest));
816 EXPECT_TRUE(orig_msg.Equals(dest));
817 }
818
819 // Tests that SetArgPointee<N>(proto_buffer) sets the
820 // ::ProtocolMessage variable pointed to by the N-th (0-based)
821 // argument to proto_buffer.
TEST(SetArgPointeeTest,SetsTheNthPointeeOfProtoBufferBaseType)822 TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
823 TestMessage* const msg = new TestMessage;
824 msg->set_member("yes");
825 TestMessage orig_msg;
826 orig_msg.CopyFrom(*msg);
827
828 Action<void(bool, ::ProtocolMessage*)> a = SetArgPointee<1>(*msg);
829 // SetArgPointee<N>(proto_buffer) makes a copy of proto_buffer
830 // s.t. the action works even when the original proto_buffer has
831 // died. We ensure this behavior by deleting msg before using the
832 // action.
833 delete msg;
834
835 TestMessage dest;
836 ::ProtocolMessage* const dest_base = &dest;
837 EXPECT_FALSE(orig_msg.Equals(dest));
838 a.Perform(make_tuple(true, dest_base));
839 EXPECT_TRUE(orig_msg.Equals(dest));
840 }
841
842 // Tests that SetArgPointee<N>(proto2_buffer) sets the v2
843 // protobuf variable pointed to by the N-th (0-based) argument to
844 // proto2_buffer.
TEST(SetArgPointeeTest,SetsTheNthPointeeOfProto2BufferType)845 TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
846 using testing::internal::FooMessage;
847 FooMessage* const msg = new FooMessage;
848 msg->set_int_field(2);
849 msg->set_string_field("hi");
850 FooMessage orig_msg;
851 orig_msg.CopyFrom(*msg);
852
853 Action<void(bool, FooMessage*)> a = SetArgPointee<1>(*msg);
854 // SetArgPointee<N>(proto2_buffer) makes a copy of
855 // proto2_buffer s.t. the action works even when the original
856 // proto2_buffer has died. We ensure this behavior by deleting msg
857 // before using the action.
858 delete msg;
859
860 FooMessage dest;
861 dest.set_int_field(0);
862 a.Perform(make_tuple(true, &dest));
863 EXPECT_EQ(2, dest.int_field());
864 EXPECT_EQ("hi", dest.string_field());
865 }
866
867 // Tests that SetArgPointee<N>(proto2_buffer) sets the
868 // proto2::Message variable pointed to by the N-th (0-based) argument
869 // to proto2_buffer.
TEST(SetArgPointeeTest,SetsTheNthPointeeOfProto2BufferBaseType)870 TEST(SetArgPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
871 using testing::internal::FooMessage;
872 FooMessage* const msg = new FooMessage;
873 msg->set_int_field(2);
874 msg->set_string_field("hi");
875 FooMessage orig_msg;
876 orig_msg.CopyFrom(*msg);
877
878 Action<void(bool, ::proto2::Message*)> a = SetArgPointee<1>(*msg);
879 // SetArgPointee<N>(proto2_buffer) makes a copy of
880 // proto2_buffer s.t. the action works even when the original
881 // proto2_buffer has died. We ensure this behavior by deleting msg
882 // before using the action.
883 delete msg;
884
885 FooMessage dest;
886 dest.set_int_field(0);
887 ::proto2::Message* const dest_base = &dest;
888 a.Perform(make_tuple(true, dest_base));
889 EXPECT_EQ(2, dest.int_field());
890 EXPECT_EQ("hi", dest.string_field());
891 }
892
893 #endif // GTEST_HAS_PROTOBUF_
894
895 // Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
896 // the N-th (0-based) argument to v.
TEST(SetArgumentPointeeTest,SetsTheNthPointee)897 TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
898 typedef void MyFunction(bool, int*, char*);
899 Action<MyFunction> a = SetArgumentPointee<1>(2);
900
901 int n = 0;
902 char ch = '\0';
903 a.Perform(make_tuple(true, &n, &ch));
904 EXPECT_EQ(2, n);
905 EXPECT_EQ('\0', ch);
906
907 a = SetArgumentPointee<2>('a');
908 n = 0;
909 ch = '\0';
910 a.Perform(make_tuple(true, &n, &ch));
911 EXPECT_EQ(0, n);
912 EXPECT_EQ('a', ch);
913 }
914
915 #if GTEST_HAS_PROTOBUF_
916
917 // Tests that SetArgumentPointee<N>(proto_buffer) sets the v1 protobuf
918 // variable pointed to by the N-th (0-based) argument to proto_buffer.
TEST(SetArgumentPointeeTest,SetsTheNthPointeeOfProtoBufferType)919 TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
920 TestMessage* const msg = new TestMessage;
921 msg->set_member("yes");
922 TestMessage orig_msg;
923 orig_msg.CopyFrom(*msg);
924
925 Action<void(bool, TestMessage*)> a = SetArgumentPointee<1>(*msg);
926 // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
927 // s.t. the action works even when the original proto_buffer has
928 // died. We ensure this behavior by deleting msg before using the
929 // action.
930 delete msg;
931
932 TestMessage dest;
933 EXPECT_FALSE(orig_msg.Equals(dest));
934 a.Perform(make_tuple(true, &dest));
935 EXPECT_TRUE(orig_msg.Equals(dest));
936 }
937
938 // Tests that SetArgumentPointee<N>(proto_buffer) sets the
939 // ::ProtocolMessage variable pointed to by the N-th (0-based)
940 // argument to proto_buffer.
TEST(SetArgumentPointeeTest,SetsTheNthPointeeOfProtoBufferBaseType)941 TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
942 TestMessage* const msg = new TestMessage;
943 msg->set_member("yes");
944 TestMessage orig_msg;
945 orig_msg.CopyFrom(*msg);
946
947 Action<void(bool, ::ProtocolMessage*)> a = SetArgumentPointee<1>(*msg);
948 // SetArgumentPointee<N>(proto_buffer) makes a copy of proto_buffer
949 // s.t. the action works even when the original proto_buffer has
950 // died. We ensure this behavior by deleting msg before using the
951 // action.
952 delete msg;
953
954 TestMessage dest;
955 ::ProtocolMessage* const dest_base = &dest;
956 EXPECT_FALSE(orig_msg.Equals(dest));
957 a.Perform(make_tuple(true, dest_base));
958 EXPECT_TRUE(orig_msg.Equals(dest));
959 }
960
961 // Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
962 // protobuf variable pointed to by the N-th (0-based) argument to
963 // proto2_buffer.
TEST(SetArgumentPointeeTest,SetsTheNthPointeeOfProto2BufferType)964 TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferType) {
965 using testing::internal::FooMessage;
966 FooMessage* const msg = new FooMessage;
967 msg->set_int_field(2);
968 msg->set_string_field("hi");
969 FooMessage orig_msg;
970 orig_msg.CopyFrom(*msg);
971
972 Action<void(bool, FooMessage*)> a = SetArgumentPointee<1>(*msg);
973 // SetArgumentPointee<N>(proto2_buffer) makes a copy of
974 // proto2_buffer s.t. the action works even when the original
975 // proto2_buffer has died. We ensure this behavior by deleting msg
976 // before using the action.
977 delete msg;
978
979 FooMessage dest;
980 dest.set_int_field(0);
981 a.Perform(make_tuple(true, &dest));
982 EXPECT_EQ(2, dest.int_field());
983 EXPECT_EQ("hi", dest.string_field());
984 }
985
986 // Tests that SetArgumentPointee<N>(proto2_buffer) sets the
987 // proto2::Message variable pointed to by the N-th (0-based) argument
988 // to proto2_buffer.
TEST(SetArgumentPointeeTest,SetsTheNthPointeeOfProto2BufferBaseType)989 TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProto2BufferBaseType) {
990 using testing::internal::FooMessage;
991 FooMessage* const msg = new FooMessage;
992 msg->set_int_field(2);
993 msg->set_string_field("hi");
994 FooMessage orig_msg;
995 orig_msg.CopyFrom(*msg);
996
997 Action<void(bool, ::proto2::Message*)> a = SetArgumentPointee<1>(*msg);
998 // SetArgumentPointee<N>(proto2_buffer) makes a copy of
999 // proto2_buffer s.t. the action works even when the original
1000 // proto2_buffer has died. We ensure this behavior by deleting msg
1001 // before using the action.
1002 delete msg;
1003
1004 FooMessage dest;
1005 dest.set_int_field(0);
1006 ::proto2::Message* const dest_base = &dest;
1007 a.Perform(make_tuple(true, dest_base));
1008 EXPECT_EQ(2, dest.int_field());
1009 EXPECT_EQ("hi", dest.string_field());
1010 }
1011
1012 #endif // GTEST_HAS_PROTOBUF_
1013
1014 // Sample functions and functors for testing Invoke() and etc.
Nullary()1015 int Nullary() { return 1; }
1016
1017 class NullaryFunctor {
1018 public:
operator ()()1019 int operator()() { return 2; }
1020 };
1021
1022 bool g_done = false;
VoidNullary()1023 void VoidNullary() { g_done = true; }
1024
1025 class VoidNullaryFunctor {
1026 public:
operator ()()1027 void operator()() { g_done = true; }
1028 };
1029
Unary(int x)1030 bool Unary(int x) { return x < 0; }
1031
Plus1(const char * s)1032 const char* Plus1(const char* s) { return s + 1; }
1033
VoidUnary(int)1034 void VoidUnary(int /* n */) { g_done = true; }
1035
ByConstRef(const std::string & s)1036 bool ByConstRef(const std::string& s) { return s == "Hi"; }
1037
1038 const double g_double = 0;
ReferencesGlobalDouble(const double & x)1039 bool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }
1040
ByNonConstRef(std::string & s)1041 std::string ByNonConstRef(std::string& s) { return s += "+"; } // NOLINT
1042
1043 struct UnaryFunctor {
operator ()__anon4e31d9990111::UnaryFunctor1044 int operator()(bool x) { return x ? 1 : -1; }
1045 };
1046
Binary(const char * input,short n)1047 const char* Binary(const char* input, short n) { return input + n; } // NOLINT
1048
VoidBinary(int,char)1049 void VoidBinary(int, char) { g_done = true; }
1050
Ternary(int x,char y,short z)1051 int Ternary(int x, char y, short z) { return x + y + z; } // NOLINT
1052
VoidTernary(int,char,bool)1053 void VoidTernary(int, char, bool) { g_done = true; }
1054
SumOf4(int a,int b,int c,int d)1055 int SumOf4(int a, int b, int c, int d) { return a + b + c + d; }
1056
VoidFunctionWithFourArguments(char,int,float,double)1057 void VoidFunctionWithFourArguments(char, int, float, double) { g_done = true; }
1058
SumOf5(int a,int b,int c,int d,int e)1059 int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
1060
1061 struct SumOf5Functor {
operator ()__anon4e31d9990111::SumOf5Functor1062 int operator()(int a, int b, int c, int d, int e) {
1063 return a + b + c + d + e;
1064 }
1065 };
1066
SumOf6(int a,int b,int c,int d,int e,int f)1067 int SumOf6(int a, int b, int c, int d, int e, int f) {
1068 return a + b + c + d + e + f;
1069 }
1070
1071 struct SumOf6Functor {
operator ()__anon4e31d9990111::SumOf6Functor1072 int operator()(int a, int b, int c, int d, int e, int f) {
1073 return a + b + c + d + e + f;
1074 }
1075 };
1076
1077 class Foo {
1078 public:
Foo()1079 Foo() : value_(123) {}
1080
Nullary() const1081 int Nullary() const { return value_; }
Unary(long x)1082 short Unary(long x) { return static_cast<short>(value_ + x); } // NOLINT
Binary(const std::string & str,char c) const1083 std::string Binary(const std::string& str, char c) const { return str + c; }
Ternary(int x,bool y,char z)1084 int Ternary(int x, bool y, char z) { return value_ + x + y*z; }
SumOf4(int a,int b,int c,int d) const1085 int SumOf4(int a, int b, int c, int d) const {
1086 return a + b + c + d + value_;
1087 }
SumOf5(int a,int b,int c,int d,int e)1088 int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }
SumOf6(int a,int b,int c,int d,int e,int f)1089 int SumOf6(int a, int b, int c, int d, int e, int f) {
1090 return a + b + c + d + e + f;
1091 }
1092 private:
1093 int value_;
1094 };
1095
1096 // Tests InvokeWithoutArgs(function).
TEST(InvokeWithoutArgsTest,Function)1097 TEST(InvokeWithoutArgsTest, Function) {
1098 // As an action that takes one argument.
1099 Action<int(int)> a = InvokeWithoutArgs(Nullary); // NOLINT
1100 EXPECT_EQ(1, a.Perform(make_tuple(2)));
1101
1102 // As an action that takes two arguments.
1103 Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary); // NOLINT
1104 EXPECT_EQ(1, a2.Perform(make_tuple(2, 3.5)));
1105
1106 // As an action that returns void.
1107 Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT
1108 g_done = false;
1109 a3.Perform(make_tuple(1));
1110 EXPECT_TRUE(g_done);
1111 }
1112
1113 // Tests InvokeWithoutArgs(functor).
TEST(InvokeWithoutArgsTest,Functor)1114 TEST(InvokeWithoutArgsTest, Functor) {
1115 // As an action that takes no argument.
1116 Action<int()> a = InvokeWithoutArgs(NullaryFunctor()); // NOLINT
1117 EXPECT_EQ(2, a.Perform(make_tuple()));
1118
1119 // As an action that takes three arguments.
1120 Action<int(int, double, char)> a2 = // NOLINT
1121 InvokeWithoutArgs(NullaryFunctor());
1122 EXPECT_EQ(2, a2.Perform(make_tuple(3, 3.5, 'a')));
1123
1124 // As an action that returns void.
1125 Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
1126 g_done = false;
1127 a3.Perform(make_tuple());
1128 EXPECT_TRUE(g_done);
1129 }
1130
1131 // Tests InvokeWithoutArgs(obj_ptr, method).
TEST(InvokeWithoutArgsTest,Method)1132 TEST(InvokeWithoutArgsTest, Method) {
1133 Foo foo;
1134 Action<int(bool, char)> a = // NOLINT
1135 InvokeWithoutArgs(&foo, &Foo::Nullary);
1136 EXPECT_EQ(123, a.Perform(make_tuple(true, 'a')));
1137 }
1138
1139 // Tests using IgnoreResult() on a polymorphic action.
TEST(IgnoreResultTest,PolymorphicAction)1140 TEST(IgnoreResultTest, PolymorphicAction) {
1141 Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT
1142 a.Perform(make_tuple(1));
1143 }
1144
1145 // Tests using IgnoreResult() on a monomorphic action.
1146
ReturnOne()1147 int ReturnOne() {
1148 g_done = true;
1149 return 1;
1150 }
1151
TEST(IgnoreResultTest,MonomorphicAction)1152 TEST(IgnoreResultTest, MonomorphicAction) {
1153 g_done = false;
1154 Action<void()> a = IgnoreResult(Invoke(ReturnOne));
1155 a.Perform(make_tuple());
1156 EXPECT_TRUE(g_done);
1157 }
1158
1159 // Tests using IgnoreResult() on an action that returns a class type.
1160
ReturnMyClass(double)1161 MyClass ReturnMyClass(double /* x */) {
1162 g_done = true;
1163 return MyClass();
1164 }
1165
TEST(IgnoreResultTest,ActionReturningClass)1166 TEST(IgnoreResultTest, ActionReturningClass) {
1167 g_done = false;
1168 Action<void(int)> a = IgnoreResult(Invoke(ReturnMyClass)); // NOLINT
1169 a.Perform(make_tuple(2));
1170 EXPECT_TRUE(g_done);
1171 }
1172
TEST(AssignTest,Int)1173 TEST(AssignTest, Int) {
1174 int x = 0;
1175 Action<void(int)> a = Assign(&x, 5);
1176 a.Perform(make_tuple(0));
1177 EXPECT_EQ(5, x);
1178 }
1179
TEST(AssignTest,String)1180 TEST(AssignTest, String) {
1181 ::std::string x;
1182 Action<void(void)> a = Assign(&x, "Hello, world");
1183 a.Perform(make_tuple());
1184 EXPECT_EQ("Hello, world", x);
1185 }
1186
TEST(AssignTest,CompatibleTypes)1187 TEST(AssignTest, CompatibleTypes) {
1188 double x = 0;
1189 Action<void(int)> a = Assign(&x, 5);
1190 a.Perform(make_tuple(0));
1191 EXPECT_DOUBLE_EQ(5, x);
1192 }
1193
1194 #if !GTEST_OS_WINDOWS_MOBILE
1195
1196 class SetErrnoAndReturnTest : public testing::Test {
1197 protected:
SetUp()1198 virtual void SetUp() { errno = 0; }
TearDown()1199 virtual void TearDown() { errno = 0; }
1200 };
1201
TEST_F(SetErrnoAndReturnTest,Int)1202 TEST_F(SetErrnoAndReturnTest, Int) {
1203 Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1204 EXPECT_EQ(-5, a.Perform(make_tuple()));
1205 EXPECT_EQ(ENOTTY, errno);
1206 }
1207
TEST_F(SetErrnoAndReturnTest,Ptr)1208 TEST_F(SetErrnoAndReturnTest, Ptr) {
1209 int x;
1210 Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1211 EXPECT_EQ(&x, a.Perform(make_tuple()));
1212 EXPECT_EQ(ENOTTY, errno);
1213 }
1214
TEST_F(SetErrnoAndReturnTest,CompatibleTypes)1215 TEST_F(SetErrnoAndReturnTest, CompatibleTypes) {
1216 Action<double()> a = SetErrnoAndReturn(EINVAL, 5);
1217 EXPECT_DOUBLE_EQ(5.0, a.Perform(make_tuple()));
1218 EXPECT_EQ(EINVAL, errno);
1219 }
1220
1221 #endif // !GTEST_OS_WINDOWS_MOBILE
1222
1223 // Tests ByRef().
1224
1225 // Tests that ReferenceWrapper<T> is copyable.
TEST(ByRefTest,IsCopyable)1226 TEST(ByRefTest, IsCopyable) {
1227 const std::string s1 = "Hi";
1228 const std::string s2 = "Hello";
1229
1230 ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper =
1231 ByRef(s1);
1232 const std::string& r1 = ref_wrapper;
1233 EXPECT_EQ(&s1, &r1);
1234
1235 // Assigns a new value to ref_wrapper.
1236 ref_wrapper = ByRef(s2);
1237 const std::string& r2 = ref_wrapper;
1238 EXPECT_EQ(&s2, &r2);
1239
1240 ::testing::internal::ReferenceWrapper<const std::string> ref_wrapper1 =
1241 ByRef(s1);
1242 // Copies ref_wrapper1 to ref_wrapper.
1243 ref_wrapper = ref_wrapper1;
1244 const std::string& r3 = ref_wrapper;
1245 EXPECT_EQ(&s1, &r3);
1246 }
1247
1248 // Tests using ByRef() on a const value.
TEST(ByRefTest,ConstValue)1249 TEST(ByRefTest, ConstValue) {
1250 const int n = 0;
1251 // int& ref = ByRef(n); // This shouldn't compile - we have a
1252 // negative compilation test to catch it.
1253 const int& const_ref = ByRef(n);
1254 EXPECT_EQ(&n, &const_ref);
1255 }
1256
1257 // Tests using ByRef() on a non-const value.
TEST(ByRefTest,NonConstValue)1258 TEST(ByRefTest, NonConstValue) {
1259 int n = 0;
1260
1261 // ByRef(n) can be used as either an int&,
1262 int& ref = ByRef(n);
1263 EXPECT_EQ(&n, &ref);
1264
1265 // or a const int&.
1266 const int& const_ref = ByRef(n);
1267 EXPECT_EQ(&n, &const_ref);
1268 }
1269
1270 // Tests explicitly specifying the type when using ByRef().
TEST(ByRefTest,ExplicitType)1271 TEST(ByRefTest, ExplicitType) {
1272 int n = 0;
1273 const int& r1 = ByRef<const int>(n);
1274 EXPECT_EQ(&n, &r1);
1275
1276 // ByRef<char>(n); // This shouldn't compile - we have a negative
1277 // compilation test to catch it.
1278
1279 Derived d;
1280 Derived& r2 = ByRef<Derived>(d);
1281 EXPECT_EQ(&d, &r2);
1282
1283 const Derived& r3 = ByRef<const Derived>(d);
1284 EXPECT_EQ(&d, &r3);
1285
1286 Base& r4 = ByRef<Base>(d);
1287 EXPECT_EQ(&d, &r4);
1288
1289 const Base& r5 = ByRef<const Base>(d);
1290 EXPECT_EQ(&d, &r5);
1291
1292 // The following shouldn't compile - we have a negative compilation
1293 // test for it.
1294 //
1295 // Base b;
1296 // ByRef<Derived>(b);
1297 }
1298
1299 // Tests that Google Mock prints expression ByRef(x) as a reference to x.
TEST(ByRefTest,PrintsCorrectly)1300 TEST(ByRefTest, PrintsCorrectly) {
1301 int n = 42;
1302 ::std::stringstream expected, actual;
1303 testing::internal::UniversalPrinter<const int&>::Print(n, &expected);
1304 testing::internal::UniversalPrint(ByRef(n), &actual);
1305 EXPECT_EQ(expected.str(), actual.str());
1306 }
1307
1308 } // Unnamed namespace
1309