Wire Sysio Wire Sysion 1.0.0
Loading...
Searching...
No Matches
gmock-actions_test.cc
Go to the documentation of this file.
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// Silence C4800 (C4800: 'int *const ': forcing value
37// to bool 'true' or 'false') for MSVC 14,15
38#ifdef _MSC_VER
39#if _MSC_VER <= 1900
40# pragma warning(push)
41# pragma warning(disable:4800)
42#endif
43#endif
44
45#include "gmock/gmock-actions.h"
46#include <algorithm>
47#include <iterator>
48#include <memory>
49#include <string>
50#include "gmock/gmock.h"
52#include "gtest/gtest.h"
53#include "gtest/gtest-spi.h"
54
55namespace {
56
57// This list should be kept sorted.
58using testing::Action;
60using testing::Assign;
61using testing::ByMove;
62using testing::ByRef;
66using testing::Invoke;
69using testing::Ne;
71using testing::Return;
77using testing::Unused;
78using testing::_;
79using testing::get;
83using testing::make_tuple;
84using testing::tuple;
85using testing::tuple_element;
86
87#if !GTEST_OS_WINDOWS_MOBILE
89#endif
90
91#if GTEST_HAS_PROTOBUF_
92using testing::internal::TestMessage;
93#endif // GTEST_HAS_PROTOBUF_
94
95// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.
96TEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {
97 EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == NULL);
98 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == NULL);
99 EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == NULL);
100}
101
102// Tests that BuiltInDefaultValue<T*>::Exists() return true.
103TEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {
104 EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());
105 EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());
106 EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());
107}
108
109// Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a
110// built-in numeric type.
111TEST(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());
118#endif
119#if GMOCK_WCHAR_T_IS_NATIVE_
120#if !defined(__WCHAR_UNSIGNED__)
121 EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());
122#else
123 EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());
124#endif
125#endif
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());
139}
140
141// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
142// built-in numeric type.
143TEST(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());
150#endif
151#if GMOCK_WCHAR_T_IS_NATIVE_
152 EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());
153#endif
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());
167}
168
169// Tests that BuiltInDefaultValue<bool>::Get() returns false.
170TEST(BuiltInDefaultValueTest, IsFalseForBool) {
171 EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());
172}
173
174// Tests that BuiltInDefaultValue<bool>::Exists() returns true.
175TEST(BuiltInDefaultValueTest, BoolExists) {
176 EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());
177}
178
179// Tests that BuiltInDefaultValue<T>::Get() returns "" when T is a
180// string type.
181TEST(BuiltInDefaultValueTest, IsEmptyStringForString) {
182#if GTEST_HAS_GLOBAL_STRING
183 EXPECT_EQ("", BuiltInDefaultValue< ::string>::Get());
184#endif // GTEST_HAS_GLOBAL_STRING
185
186 EXPECT_EQ("", BuiltInDefaultValue< ::std::string>::Get());
187}
188
189// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a
190// string type.
191TEST(BuiltInDefaultValueTest, ExistsForString) {
192#if GTEST_HAS_GLOBAL_STRING
193 EXPECT_TRUE(BuiltInDefaultValue< ::string>::Exists());
194#endif // GTEST_HAS_GLOBAL_STRING
195
196 EXPECT_TRUE(BuiltInDefaultValue< ::std::string>::Exists());
197}
198
199// Tests that BuiltInDefaultValue<const T>::Get() returns the same
200// value as BuiltInDefaultValue<T>::Get() does.
201TEST(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());
206}
207
208// A type that's default constructible.
209class MyDefaultConstructible {
210 public:
211 MyDefaultConstructible() : value_(42) {}
212
213 int value() const { return value_; }
214
215 private:
216 int value_;
217};
218
219// A type that's not default constructible.
220class MyNonDefaultConstructible {
221 public:
222 // Does not have a default ctor.
223 explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}
224
225 int value() const { return value_; }
226
227 private:
228 int value_;
229};
230
231#if GTEST_LANG_CXX11
232
233TEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {
234 EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());
235}
236
237TEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {
238 EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());
239}
240
241#endif // GTEST_LANG_CXX11
242
243TEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {
244 EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());
245}
246
247// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.
248TEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {
250 BuiltInDefaultValue<int&>::Get();
251 }, "");
253 BuiltInDefaultValue<const char&>::Get();
254 }, "");
255}
256
257TEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {
259 BuiltInDefaultValue<MyNonDefaultConstructible>::Get();
260 }, "");
261}
262
263// Tests that DefaultValue<T>::IsSet() is false initially.
264TEST(DefaultValueTest, IsInitiallyUnset) {
265 EXPECT_FALSE(DefaultValue<int>::IsSet());
266 EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());
267 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
268}
269
270// Tests that DefaultValue<T> can be set and then unset.
271TEST(DefaultValueTest, CanBeSetAndUnset) {
272 EXPECT_TRUE(DefaultValue<int>::Exists());
273 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
274
275 DefaultValue<int>::Set(1);
276 DefaultValue<const MyNonDefaultConstructible>::Set(
277 MyNonDefaultConstructible(42));
278
279 EXPECT_EQ(1, DefaultValue<int>::Get());
280 EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());
281
282 EXPECT_TRUE(DefaultValue<int>::Exists());
283 EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());
284
285 DefaultValue<int>::Clear();
286 DefaultValue<const MyNonDefaultConstructible>::Clear();
287
288 EXPECT_FALSE(DefaultValue<int>::IsSet());
289 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());
290
291 EXPECT_TRUE(DefaultValue<int>::Exists());
292 EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());
293}
294
295// Tests that DefaultValue<T>::Get() returns the
296// BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is
297// false.
298TEST(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());
303
304 EXPECT_EQ(0, DefaultValue<int>::Get());
305
307 DefaultValue<MyNonDefaultConstructible>::Get();
308 }, "");
309}
310
311#if GTEST_HAS_STD_UNIQUE_PTR_
312TEST(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));
317 });
318 EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());
319 std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();
320 EXPECT_EQ(42, *i);
321}
322#endif // GTEST_HAS_STD_UNIQUE_PTR_
323
324// Tests that DefaultValue<void>::Get() returns void.
325TEST(DefaultValueTest, GetWorksForVoid) {
326 return DefaultValue<void>::Get();
327}
328
329// Tests using DefaultValue with a reference type.
330
331// Tests that DefaultValue<T&>::IsSet() is false initially.
332TEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {
333 EXPECT_FALSE(DefaultValue<int&>::IsSet());
334 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());
335 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
336}
337
338// Tests that DefaultValue<T&>::Exists is false initiallly.
339TEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {
340 EXPECT_FALSE(DefaultValue<int&>::Exists());
341 EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());
342 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
343}
344
345// Tests that DefaultValue<T&> can be set and then unset.
346TEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {
347 int n = 1;
348 DefaultValue<const int&>::Set(n);
349 MyNonDefaultConstructible x(42);
350 DefaultValue<MyNonDefaultConstructible&>::Set(x);
351
352 EXPECT_TRUE(DefaultValue<const int&>::Exists());
353 EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());
354
355 EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));
356 EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));
357
358 DefaultValue<const int&>::Clear();
359 DefaultValue<MyNonDefaultConstructible&>::Clear();
360
361 EXPECT_FALSE(DefaultValue<const int&>::Exists());
362 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());
363
364 EXPECT_FALSE(DefaultValue<const int&>::IsSet());
365 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
366}
367
368// Tests that DefaultValue<T&>::Get() returns the
369// BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is
370// false.
371TEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {
372 EXPECT_FALSE(DefaultValue<int&>::IsSet());
373 EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());
374
376 DefaultValue<int&>::Get();
377 }, "");
379 DefaultValue<MyNonDefaultConstructible>::Get();
380 }, "");
381}
382
383// Tests that ActionInterface can be implemented by defining the
384// Perform method.
385
386typedef int MyGlobalFunction(bool, int);
387
388class MyActionImpl : public ActionInterface<MyGlobalFunction> {
389 public:
390 virtual int Perform(const tuple<bool, int>& args) {
391 return get<0>(args) ? get<1>(args) : 0;
392 }
393};
394
395TEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {
396 MyActionImpl my_action_impl;
397 (void)my_action_impl;
398}
399
400TEST(ActionInterfaceTest, MakeAction) {
401 Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);
402
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)));
409}
410
411// Tests that Action<F> can be contructed from a pointer to
412// ActionInterface<F>.
413TEST(ActionTest, CanBeConstructedFromActionInterface) {
414 Action<MyGlobalFunction> action(new MyActionImpl);
415}
416
417// Tests that Action<F> delegates actual work to ActionInterface<F>.
418TEST(ActionTest, DelegatesWorkToActionInterface) {
419 const Action<MyGlobalFunction> action(new MyActionImpl);
420
421 EXPECT_EQ(5, action.Perform(make_tuple(true, 5)));
422 EXPECT_EQ(0, action.Perform(make_tuple(false, 1)));
423}
424
425// Tests that Action<F> can be copied.
426TEST(ActionTest, IsCopyable) {
427 Action<MyGlobalFunction> a1(new MyActionImpl);
428 Action<MyGlobalFunction> a2(a1); // Tests the copy constructor.
429
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)));
433
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)));
437
438 a2 = a1; // Tests the assignment operator.
439
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)));
443
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)));
447}
448
449// Tests that an Action<From> object can be converted to a
450// compatible Action<To> object.
451
452class IsNotZero : public ActionInterface<bool(int)> { // NOLINT
453 public:
454 virtual bool Perform(const tuple<int>& arg) {
455 return get<0>(arg) != 0;
456 }
457};
458
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.
465TEST(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')));
470}
471#endif // !GTEST_OS_SYMBIAN
472
473// The following two classes are for testing MakePolymorphicAction().
474
475// Implements a polymorphic action that returns the second of the
476// arguments it receives.
477class ReturnSecondArgumentAction {
478 public:
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); }
484};
485
486// Implements a polymorphic action that can be used in a nullary
487// function to return 0.
488class ReturnZeroFromNullaryFunctionAction {
489 public:
490 // For testing that MakePolymorphicAction() works when the
491 // implementation class' Perform() method template takes only one
492 // template parameter.
493 //
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; }
499};
500
501// These functions verify that MakePolymorphicAction() returns a
502// PolymorphicAction<T> where T is the argument's type.
503
504PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
505 return MakePolymorphicAction(ReturnSecondArgumentAction());
506}
507
508PolymorphicAction<ReturnZeroFromNullaryFunctionAction>
509ReturnZeroFromNullaryFunction() {
510 return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());
511}
512
513// Tests that MakePolymorphicAction() turns a polymorphic action
514// implementation class into a polymorphic action.
515TEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {
516 Action<int(bool, int, double)> a1 = ReturnSecondArgument(); // NOLINT
517 EXPECT_EQ(5, a1.Perform(make_tuple(false, 5, 2.0)));
518}
519
520// Tests that MakePolymorphicAction() works when the implementation
521// class' Perform() method template has only one template parameter.
522TEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {
523 Action<int()> a1 = ReturnZeroFromNullaryFunction();
524 EXPECT_EQ(0, a1.Perform(make_tuple()));
525
526 Action<void*()> a2 = ReturnZeroFromNullaryFunction();
527 EXPECT_TRUE(a2.Perform(make_tuple()) == NULL);
528}
529
530// Tests that Return() works as an action for void-returning
531// functions.
532TEST(ReturnTest, WorksForVoid) {
533 const Action<void(int)> ret = Return(); // NOLINT
534 return ret.Perform(make_tuple(1));
535}
536
537// Tests that Return(v) returns v.
538TEST(ReturnTest, ReturnsGivenValue) {
539 Action<int()> ret = Return(1); // NOLINT
540 EXPECT_EQ(1, ret.Perform(make_tuple()));
541
542 ret = Return(-5);
543 EXPECT_EQ(-5, ret.Perform(make_tuple()));
544}
545
546// Tests that Return("string literal") works.
547TEST(ReturnTest, AcceptsStringLiteral) {
548 Action<const char*()> a1 = Return("Hello");
549 EXPECT_STREQ("Hello", a1.Perform(make_tuple()));
550
551 Action<std::string()> a2 = Return("world");
552 EXPECT_EQ("world", a2.Perform(make_tuple()));
553}
554
555// Test struct which wraps a vector of integers. Used in
556// 'SupportsWrapperReturnType' test.
557struct IntegerVectorWrapper {
558 std::vector<int> * v;
559 IntegerVectorWrapper(std::vector<int>& _v) : v(&_v) {} // NOLINT
560};
561
562// Tests that Return() works when return type is a wrapper type.
563TEST(ReturnTest, SupportsWrapperReturnType) {
564 // Initialize vector of integers.
565 std::vector<int> v;
566 for (int i = 0; i < 5; ++i) v.push_back(i);
567
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));
573}
574
575// Tests that Return(v) is covaraint.
576
577struct Base {
578 bool operator==(const Base&) { return true; }
579};
580
581struct Derived : public Base {
582 bool operator==(const Derived&) { return true; }
583};
584
585TEST(ReturnTest, IsCovariant) {
586 Base base;
587 Derived derived;
588 Action<Base*()> ret = Return(&base);
589 EXPECT_EQ(&base, ret.Perform(make_tuple()));
590
591 ret = Return(&derived);
592 EXPECT_EQ(&derived, ret.Perform(make_tuple()));
593}
594
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.
599class FromType {
600 public:
601 explicit FromType(bool* is_converted) : converted_(is_converted) {}
602 bool* converted() const { return converted_; }
603
604 private:
605 bool* const converted_;
606
607 GTEST_DISALLOW_ASSIGN_(FromType);
608};
609
610class ToType {
611 public:
612 // Must allow implicit conversion due to use in ImplicitCast_<T>.
613 ToType(const FromType& x) { *x.converted() = true; } // NOLINT
614};
615
616TEST(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.";
622 converted = false;
623 action.Perform(tuple<>());
624 EXPECT_FALSE(converted) << "Action must NOT convert its argument "
625 << "when performed.";
626}
627
628class DestinationType {};
629
630class SourceType {
631 public:
632 // Note: a non-const typecast operator.
633 operator DestinationType() { return DestinationType(); }
634};
635
636TEST(ReturnTest, CanConvertArgumentUsingNonConstTypeCastOperator) {
637 SourceType s;
638 Action<DestinationType()> action(Return(s));
639}
640
641// Tests that ReturnNull() returns NULL in a pointer-returning function.
642TEST(ReturnNullTest, WorksInPointerReturningFunction) {
643 const Action<int*()> a1 = ReturnNull();
644 EXPECT_TRUE(a1.Perform(make_tuple()) == NULL);
645
646 const Action<const char*(bool)> a2 = ReturnNull(); // NOLINT
647 EXPECT_TRUE(a2.Perform(make_tuple(true)) == NULL);
648}
649
650#if GTEST_HAS_STD_UNIQUE_PTR_
651// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning
652// functions.
653TEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {
654 const Action<std::unique_ptr<const int>()> a1 = ReturnNull();
655 EXPECT_TRUE(a1.Perform(make_tuple()) == nullptr);
656
657 const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();
658 EXPECT_TRUE(a2.Perform(make_tuple("foo")) == nullptr);
659}
660#endif // GTEST_HAS_STD_UNIQUE_PTR_
661
662// Tests that ReturnRef(v) works for reference types.
663TEST(ReturnRefTest, WorksForReference) {
664 const int n = 0;
665 const Action<const int&(bool)> ret = ReturnRef(n); // NOLINT
666
667 EXPECT_EQ(&n, &ret.Perform(make_tuple(true)));
668}
669
670// Tests that ReturnRef(v) is covariant.
671TEST(ReturnRefTest, IsCovariant) {
672 Base base;
673 Derived derived;
674 Action<Base&()> a = ReturnRef(base);
675 EXPECT_EQ(&base, &a.Perform(make_tuple()));
676
677 a = ReturnRef(derived);
678 EXPECT_EQ(&derived, &a.Perform(make_tuple()));
679}
680
681// Tests that ReturnRefOfCopy(v) works for reference types.
682TEST(ReturnRefOfCopyTest, WorksForReference) {
683 int n = 42;
684 const Action<const int&()> ret = ReturnRefOfCopy(n);
685
686 EXPECT_NE(&n, &ret.Perform(make_tuple()));
687 EXPECT_EQ(42, ret.Perform(make_tuple()));
688
689 n = 43;
690 EXPECT_NE(&n, &ret.Perform(make_tuple()));
691 EXPECT_EQ(42, ret.Perform(make_tuple()));
692}
693
694// Tests that ReturnRefOfCopy(v) is covariant.
695TEST(ReturnRefOfCopyTest, IsCovariant) {
696 Base base;
697 Derived derived;
698 Action<Base&()> a = ReturnRefOfCopy(base);
699 EXPECT_NE(&base, &a.Perform(make_tuple()));
700
701 a = ReturnRefOfCopy(derived);
702 EXPECT_NE(&derived, &a.Perform(make_tuple()));
703}
704
705// Tests that DoDefault() does the default action for the mock method.
706
707class MockClass {
708 public:
709 MockClass() {}
710
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>));
720#endif
721
722 private:
724};
725
726// Tests that DoDefault() returns the built-in default value for the
727// return type by default.
728TEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {
729 MockClass mock;
730 EXPECT_CALL(mock, IntFunc(_))
731 .WillOnce(DoDefault());
732 EXPECT_EQ(0, mock.IntFunc(true));
733}
734
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.
737TEST(DoDefaultDeathTest, DiesForUnknowType) {
738 MockClass mock;
739 EXPECT_CALL(mock, Foo())
740 .WillRepeatedly(DoDefault());
741#if GTEST_HAS_EXCEPTIONS
742 EXPECT_ANY_THROW(mock.Foo());
743#else
745 mock.Foo();
746 }, "");
747#endif
748}
749
750// Tests that using DoDefault() inside a composite action leads to a
751// run-time error.
752
753void VoidFunc(bool /* flag */) {}
754
755TEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {
756 MockClass mock;
757 EXPECT_CALL(mock, IntFunc(_))
758 .WillRepeatedly(DoAll(Invoke(VoidFunc),
759 DoDefault()));
760
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.
766 mock.IntFunc(true);
767 }, "");
768}
769
770// Tests that DoDefault() returns the default value set by
771// DefaultValue<T>::Set() when it's not overriden by an ON_CALL().
772TEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {
773 DefaultValue<int>::Set(1);
774 MockClass mock;
775 EXPECT_CALL(mock, IntFunc(_))
776 .WillOnce(DoDefault());
777 EXPECT_EQ(1, mock.IntFunc(false));
778 DefaultValue<int>::Clear();
779}
780
781// Tests that DoDefault() does the action specified by ON_CALL().
782TEST(DoDefaultTest, DoesWhatOnCallSpecifies) {
783 MockClass mock;
784 ON_CALL(mock, IntFunc(_))
785 .WillByDefault(Return(2));
786 EXPECT_CALL(mock, IntFunc(_))
787 .WillOnce(DoDefault());
788 EXPECT_EQ(2, mock.IntFunc(false));
789}
790
791// Tests that using DoDefault() in ON_CALL() leads to a run-time failure.
792TEST(DoDefaultTest, CannotBeUsedInOnCall) {
793 MockClass mock;
794 EXPECT_NONFATAL_FAILURE({ // NOLINT
795 ON_CALL(mock, IntFunc(_))
796 .WillByDefault(DoDefault());
797 }, "DoDefault() cannot be used in ON_CALL()");
798}
799
800// Tests that SetArgPointee<N>(v) sets the variable pointed to by
801// the N-th (0-based) argument to v.
802TEST(SetArgPointeeTest, SetsTheNthPointee) {
803 typedef void MyFunction(bool, int*, char*);
804 Action<MyFunction> a = SetArgPointee<1>(2);
805
806 int n = 0;
807 char ch = '\0';
808 a.Perform(make_tuple(true, &n, &ch));
809 EXPECT_EQ(2, n);
810 EXPECT_EQ('\0', ch);
811
812 a = SetArgPointee<2>('a');
813 n = 0;
814 ch = '\0';
815 a.Perform(make_tuple(true, &n, &ch));
816 EXPECT_EQ(0, n);
817 EXPECT_EQ('a', ch);
818}
819
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.
823TEST(SetArgPointeeTest, AcceptsStringLiteral) {
824 typedef void MyFunction(std::string*, const char**);
825 Action<MyFunction> a = SetArgPointee<0>("hi");
826 std::string str;
827 const char* ptr = NULL;
828 a.Perform(make_tuple(&str, &ptr));
829 EXPECT_EQ("hi", str);
830 EXPECT_TRUE(ptr == NULL);
831
832 a = SetArgPointee<1>("world");
833 str = "";
834 a.Perform(make_tuple(&str, &ptr));
835 EXPECT_EQ("", str);
836 EXPECT_STREQ("world", ptr);
837}
838
839TEST(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);
845
846# if GTEST_HAS_STD_WSTRING
847
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);
853
854# endif
855}
856#endif
857
858// Tests that SetArgPointee<N>() accepts a char pointer.
859TEST(SetArgPointeeTest, AcceptsCharPointer) {
860 typedef void MyFunction(bool, std::string*, const char**);
861 const char* const hi = "hi";
862 Action<MyFunction> a = SetArgPointee<1>(hi);
863 std::string str;
864 const char* ptr = NULL;
865 a.Perform(make_tuple(true, &str, &ptr));
866 EXPECT_EQ("hi", str);
867 EXPECT_TRUE(ptr == NULL);
868
869 char world_array[] = "world";
870 char* const world = world_array;
871 a = SetArgPointee<2>(world);
872 str = "";
873 a.Perform(make_tuple(true, &str, &ptr));
874 EXPECT_EQ("", str);
875 EXPECT_EQ(world, ptr);
876}
877
878TEST(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));
884 EXPECT_EQ(hi, ptr);
885
886# if GTEST_HAS_STD_WSTRING
887
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);
892 std::wstring str;
893 a2.Perform(make_tuple(true, &str));
894 EXPECT_EQ(world_array, str);
895# endif
896}
897
898#if GTEST_HAS_PROTOBUF_
899
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.
902TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
903 TestMessage* const msg = new TestMessage;
904 msg->set_member("yes");
905 TestMessage orig_msg;
906 orig_msg.CopyFrom(*msg);
907
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
912 // action.
913 delete msg;
914
915 TestMessage dest;
916 EXPECT_FALSE(orig_msg.Equals(dest));
917 a.Perform(make_tuple(true, &dest));
918 EXPECT_TRUE(orig_msg.Equals(dest));
919}
920
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.
924TEST(SetArgPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
925 TestMessage* const msg = new TestMessage;
926 msg->set_member("yes");
927 TestMessage orig_msg;
928 orig_msg.CopyFrom(*msg);
929
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
934 // action.
935 delete msg;
936
937 TestMessage dest;
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));
942}
943
944// Tests that SetArgPointee<N>(proto2_buffer) sets the v2
945// protobuf variable pointed to by the N-th (0-based) argument to
946// proto2_buffer.
947TEST(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");
952 FooMessage orig_msg;
953 orig_msg.CopyFrom(*msg);
954
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.
960 delete msg;
961
962 FooMessage dest;
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());
967}
968
969// Tests that SetArgPointee<N>(proto2_buffer) sets the
970// proto2::Message variable pointed to by the N-th (0-based) argument
971// to proto2_buffer.
972TEST(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");
977 FooMessage orig_msg;
978 orig_msg.CopyFrom(*msg);
979
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.
985 delete msg;
986
987 FooMessage dest;
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());
993}
994
995#endif // GTEST_HAS_PROTOBUF_
996
997// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by
998// the N-th (0-based) argument to v.
999TEST(SetArgumentPointeeTest, SetsTheNthPointee) {
1000 typedef void MyFunction(bool, int*, char*);
1001 Action<MyFunction> a = SetArgumentPointee<1>(2);
1002
1003 int n = 0;
1004 char ch = '\0';
1005 a.Perform(make_tuple(true, &n, &ch));
1006 EXPECT_EQ(2, n);
1007 EXPECT_EQ('\0', ch);
1008
1009 a = SetArgumentPointee<2>('a');
1010 n = 0;
1011 ch = '\0';
1012 a.Perform(make_tuple(true, &n, &ch));
1013 EXPECT_EQ(0, n);
1014 EXPECT_EQ('a', ch);
1015}
1016
1017#if GTEST_HAS_PROTOBUF_
1018
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.
1021TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferType) {
1022 TestMessage* const msg = new TestMessage;
1023 msg->set_member("yes");
1024 TestMessage orig_msg;
1025 orig_msg.CopyFrom(*msg);
1026
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
1031 // action.
1032 delete msg;
1033
1034 TestMessage dest;
1035 EXPECT_FALSE(orig_msg.Equals(dest));
1036 a.Perform(make_tuple(true, &dest));
1037 EXPECT_TRUE(orig_msg.Equals(dest));
1038}
1039
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.
1043TEST(SetArgumentPointeeTest, SetsTheNthPointeeOfProtoBufferBaseType) {
1044 TestMessage* const msg = new TestMessage;
1045 msg->set_member("yes");
1046 TestMessage orig_msg;
1047 orig_msg.CopyFrom(*msg);
1048
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
1053 // action.
1054 delete msg;
1055
1056 TestMessage dest;
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));
1061}
1062
1063// Tests that SetArgumentPointee<N>(proto2_buffer) sets the v2
1064// protobuf variable pointed to by the N-th (0-based) argument to
1065// proto2_buffer.
1066TEST(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);
1073
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.
1079 delete msg;
1080
1081 FooMessage dest;
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());
1086}
1087
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.
1091TEST(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);
1098
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.
1104 delete msg;
1105
1106 FooMessage dest;
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());
1112}
1113
1114#endif // GTEST_HAS_PROTOBUF_
1115
1116// Sample functions and functors for testing Invoke() and etc.
1117int Nullary() { return 1; }
1118
1119class NullaryFunctor {
1120 public:
1121 int operator()() { return 2; }
1122};
1123
1124bool g_done = false;
1125void VoidNullary() { g_done = true; }
1126
1127class VoidNullaryFunctor {
1128 public:
1129 void operator()() { g_done = true; }
1130};
1131
1132class Foo {
1133 public:
1134 Foo() : value_(123) {}
1135
1136 int Nullary() const { return value_; }
1137
1138 private:
1139 int value_;
1140};
1141
1142// Tests InvokeWithoutArgs(function).
1143TEST(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)));
1147
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)));
1151
1152 // As an action that returns void.
1153 Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary); // NOLINT
1154 g_done = false;
1155 a3.Perform(make_tuple(1));
1156 EXPECT_TRUE(g_done);
1157}
1158
1159// Tests InvokeWithoutArgs(functor).
1160TEST(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()));
1164
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')));
1169
1170 // As an action that returns void.
1171 Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());
1172 g_done = false;
1173 a3.Perform(make_tuple());
1174 EXPECT_TRUE(g_done);
1175}
1176
1177// Tests InvokeWithoutArgs(obj_ptr, method).
1178TEST(InvokeWithoutArgsTest, Method) {
1179 Foo foo;
1180 Action<int(bool, char)> a = // NOLINT
1181 InvokeWithoutArgs(&foo, &Foo::Nullary);
1182 EXPECT_EQ(123, a.Perform(make_tuple(true, 'a')));
1183}
1184
1185// Tests using IgnoreResult() on a polymorphic action.
1186TEST(IgnoreResultTest, PolymorphicAction) {
1187 Action<void(int)> a = IgnoreResult(Return(5)); // NOLINT
1188 a.Perform(make_tuple(1));
1189}
1190
1191// Tests using IgnoreResult() on a monomorphic action.
1192
1193int ReturnOne() {
1194 g_done = true;
1195 return 1;
1196}
1197
1198TEST(IgnoreResultTest, MonomorphicAction) {
1199 g_done = false;
1200 Action<void()> a = IgnoreResult(Invoke(ReturnOne));
1201 a.Perform(make_tuple());
1202 EXPECT_TRUE(g_done);
1203}
1204
1205// Tests using IgnoreResult() on an action that returns a class type.
1206
1207MyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {
1208 g_done = true;
1209 return MyNonDefaultConstructible(42);
1210}
1211
1212TEST(IgnoreResultTest, ActionReturningClass) {
1213 g_done = false;
1214 Action<void(int)> a =
1215 IgnoreResult(Invoke(ReturnMyNonDefaultConstructible)); // NOLINT
1216 a.Perform(make_tuple(2));
1217 EXPECT_TRUE(g_done);
1218}
1219
1220TEST(AssignTest, Int) {
1221 int x = 0;
1222 Action<void(int)> a = Assign(&x, 5);
1223 a.Perform(make_tuple(0));
1224 EXPECT_EQ(5, x);
1225}
1226
1227TEST(AssignTest, String) {
1228 ::std::string x;
1229 Action<void(void)> a = Assign(&x, "Hello, world");
1230 a.Perform(make_tuple());
1231 EXPECT_EQ("Hello, world", x);
1232}
1233
1234TEST(AssignTest, CompatibleTypes) {
1235 double x = 0;
1236 Action<void(int)> a = Assign(&x, 5);
1237 a.Perform(make_tuple(0));
1238 EXPECT_DOUBLE_EQ(5, x);
1239}
1240
1241#if !GTEST_OS_WINDOWS_MOBILE
1242
1243class SetErrnoAndReturnTest : public testing::Test {
1244 protected:
1245 virtual void SetUp() { errno = 0; }
1246 virtual void TearDown() { errno = 0; }
1247};
1248
1249TEST_F(SetErrnoAndReturnTest, Int) {
1250 Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);
1251 EXPECT_EQ(-5, a.Perform(make_tuple()));
1252 EXPECT_EQ(ENOTTY, errno);
1253}
1254
1255TEST_F(SetErrnoAndReturnTest, Ptr) {
1256 int x;
1257 Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);
1258 EXPECT_EQ(&x, a.Perform(make_tuple()));
1259 EXPECT_EQ(ENOTTY, errno);
1260}
1261
1262TEST_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);
1266}
1267
1268#endif // !GTEST_OS_WINDOWS_MOBILE
1269
1270// Tests ByRef().
1271
1272// Tests that ReferenceWrapper<T> is copyable.
1273TEST(ByRefTest, IsCopyable) {
1274 const std::string s1 = "Hi";
1275 const std::string s2 = "Hello";
1276
1278 ByRef(s1);
1279 const std::string& r1 = ref_wrapper;
1280 EXPECT_EQ(&s1, &r1);
1281
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);
1286
1288 ByRef(s1);
1289 // Copies ref_wrapper1 to ref_wrapper.
1290 ref_wrapper = ref_wrapper1;
1291 const std::string& r3 = ref_wrapper;
1292 EXPECT_EQ(&s1, &r3);
1293}
1294
1295// Tests using ByRef() on a const value.
1296TEST(ByRefTest, ConstValue) {
1297 const int n = 0;
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);
1302}
1303
1304// Tests using ByRef() on a non-const value.
1305TEST(ByRefTest, NonConstValue) {
1306 int n = 0;
1307
1308 // ByRef(n) can be used as either an int&,
1309 int& ref = ByRef(n);
1310 EXPECT_EQ(&n, &ref);
1311
1312 // or a const int&.
1313 const int& const_ref = ByRef(n);
1314 EXPECT_EQ(&n, &const_ref);
1315}
1316
1317// Tests explicitly specifying the type when using ByRef().
1318TEST(ByRefTest, ExplicitType) {
1319 int n = 0;
1320 const int& r1 = ByRef<const int>(n);
1321 EXPECT_EQ(&n, &r1);
1322
1323 // ByRef<char>(n); // This shouldn't compile - we have a negative
1324 // compilation test to catch it.
1325
1326 Derived d;
1327 Derived& r2 = ByRef<Derived>(d);
1328 EXPECT_EQ(&d, &r2);
1329
1330 const Derived& r3 = ByRef<const Derived>(d);
1331 EXPECT_EQ(&d, &r3);
1332
1333 Base& r4 = ByRef<Base>(d);
1334 EXPECT_EQ(&d, &r4);
1335
1336 const Base& r5 = ByRef<const Base>(d);
1337 EXPECT_EQ(&d, &r5);
1338
1339 // The following shouldn't compile - we have a negative compilation
1340 // test for it.
1341 //
1342 // Base b;
1343 // ByRef<Derived>(b);
1344}
1345
1346// Tests that Google Mock prints expression ByRef(x) as a reference to x.
1347TEST(ByRefTest, PrintsCorrectly) {
1348 int n = 42;
1349 ::std::stringstream expected, actual;
1351 testing::internal::UniversalPrint(ByRef(n), &actual);
1352 EXPECT_EQ(expected.str(), actual.str());
1353}
1354
1355#if GTEST_HAS_STD_UNIQUE_PTR_
1356
1357std::unique_ptr<int> UniquePtrSource() {
1358 return std::unique_ptr<int>(new int(19));
1359}
1360
1361std::vector<std::unique_ptr<int>> VectorUniquePtrSource() {
1362 std::vector<std::unique_ptr<int>> out;
1363 out.emplace_back(new int(7));
1364 return out;
1365}
1366
1367TEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {
1368 MockClass mock;
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))));
1376
1377 std::unique_ptr<int> result1 = mock.MakeUnique();
1378 EXPECT_EQ(19, *result1);
1379
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]);
1384
1385 std::unique_ptr<Base> result2 = mock.MakeUniqueBase();
1386 EXPECT_EQ(d, result2.get());
1387}
1388
1389TEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {
1390 testing::MockFunction<void()> mock_function;
1391 MockClass mock;
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)))));
1397
1398 std::unique_ptr<int> result1 = mock.MakeUnique();
1399 EXPECT_EQ(19, *result1);
1400}
1401
1402TEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {
1403 MockClass mock;
1404
1405 // Check default value
1406 DefaultValue<std::unique_ptr<int>>::SetFactory([] {
1407 return std::unique_ptr<int>(new int(42));
1408 });
1409 EXPECT_EQ(42, *mock.MakeUnique());
1410
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);
1419
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]);
1424}
1425
1426TEST(MockMethodTest, CanTakeMoveOnlyValue) {
1427 MockClass mock;
1428 auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };
1429
1430 EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {
1431 return *i;
1432 });
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) {}),
1436 // Return(1)));
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();
1443
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({}));
1449
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) {
1454 return *i * *j;
1455 });
1456 EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));
1457
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);
1462 return 0;
1463 });
1464 EXPECT_EQ(0, mock.TakeUnique(make(42)));
1465 EXPECT_EQ(42, *saved);
1466}
1467
1468#endif // GTEST_HAS_STD_UNIQUE_PTR_
1469
1470#if GTEST_LANG_CXX11
1471// Tests for std::function based action.
1472
1473int Add(int val, int& ref, int* ptr) { // NOLINT
1474 int result = val + ref + *ptr;
1475 ref = 42;
1476 *ptr = 43;
1477 return result;
1478}
1479
1480int Deref(std::unique_ptr<int> ptr) { return *ptr; }
1481
1482struct Double {
1483 template <typename T>
1484 T operator()(T t) { return 2 * t; }
1485};
1486
1487std::unique_ptr<int> UniqueInt(int i) {
1488 return std::unique_ptr<int>(new int(i));
1489}
1490
1491TEST(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)));
1495 EXPECT_EQ(42, y);
1496 EXPECT_EQ(43, z);
1497
1498 Action<int(std::unique_ptr<int>)> a1 = &Deref;
1499 EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));
1500}
1501
1502TEST(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)));
1506
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);
1510 };
1511 a2.Perform(make_tuple(UniqueInt(5)));
1512 EXPECT_EQ(5, *saved);
1513}
1514
1515TEST(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)));
1520}
1521
1522TEST(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)));
1528
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")));
1534
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")));
1538}
1539
1540TEST(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));
1546}
1547
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.
1553TEST(MoveOnlyArgumentsTest, ReturningActions) {
1554 Action<int(std::unique_ptr<int>)> a = Return(1);
1555 EXPECT_EQ(1, a.Perform(make_tuple(nullptr)));
1556
1557 a = testing::WithoutArgs([]() { return 7; });
1558 EXPECT_EQ(7, a.Perform(make_tuple(nullptr)));
1559
1560 Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);
1561 int x = 0;
1562 a2.Perform(make_tuple(nullptr, &x));
1563 EXPECT_EQ(x, 3);
1564}
1565
1566#endif // GTEST_LANG_CXX11
1567
1568} // Unnamed namespace
1569
1570#ifdef _MSC_VER
1571#if _MSC_VER == 1900
1572# pragma warning(pop)
1573#endif
1574#endif
1575
const mie::Vuint & p
Definition bn.cpp:27
static void Print(const T &value, ::std::ostream *os)
bool operator==(const environment &other)
#define MOCK_METHOD0(m,...)
#define MOCK_METHOD2(m,...)
#define MOCK_METHOD1(m,...)
#define EXPECT_THAT(value, matcher)
#define EXPECT_CALL(obj, call)
#define ON_CALL(obj, call)
#define Method
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
#define GTEST_DISALLOW_ASSIGN_(type)
Definition gtest-port.h:912
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
Definition gtest-port.h:917
#define EXPECT_NONFATAL_FAILURE(statement, substr)
Definition gtest-spi.h:203
#define TEST_F(test_fixture, test_name)
Definition gtest.h:2304
#define EXPECT_EQ(val1, val2)
Definition gtest.h:1954
#define EXPECT_NE(val1, val2)
Definition gtest.h:1958
#define EXPECT_ANY_THROW(statement)
Definition gtest.h:1883
#define EXPECT_DOUBLE_EQ(val1, val2)
Definition gtest.h:2063
#define EXPECT_TRUE(condition)
Definition gtest.h:1895
#define EXPECT_STREQ(s1, s2)
Definition gtest.h:2027
#define TEST(test_case_name, test_name)
Definition gtest.h:2275
#define EXPECT_FALSE(condition)
Definition gtest.h:1898
constexpr enabler dummy
An instance to use in EnableIf.
Definition CLI11.hpp:856
return str
Definition CLI11.hpp:1359
static const Reg8 ch(Operand::CH)
uint64_t y
Definition sha3.cpp:34
TypeWithSize< 8 >::Int Int64
void UniversalPrint(const T &value, ::std::ostream *os)
FloatingPoint< double > Double
TypeWithSize< 8 >::UInt UInt64
internal::Ne2Matcher Ne()
internal::IgnoreResultAction< A > IgnoreResult(const A &an_action)
PolymorphicAction< internal::InvokeWithoutArgsAction< FunctionImpl > > InvokeWithoutArgs(FunctionImpl function_impl)
PolymorphicMatcher< internal::IsNullMatcher > IsNull()
internal::ByMoveWrapper< R > ByMove(R x)
PolymorphicAction< Impl > MakePolymorphicAction(const Impl &impl)
PolymorphicAction< internal::ReturnVoidAction > Return()
const internal::AnythingMatcher _
internal::IgnoredValue Unused
PolymorphicAction< internal::AssignAction< T1, T2 > > Assign(T1 *ptr, T2 val)
PolymorphicAction< internal::SetErrnoAndReturnAction< T > > SetErrnoAndReturn(int errval, T result)
internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre()
Action< F > MakeAction(ActionInterface< F > *impl)
PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage< T >::value > > SetArgumentPointee(const T &x)
internal::ReturnRefOfCopyAction< R > ReturnRefOfCopy(const R &x)
internal::ReferenceWrapper< T > ByRef(T &l_value)
internal::WithArgsAction< InnerAction > WithoutArgs(const InnerAction &action)
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
internal::ReturnRefAction< R > ReturnRef(R &x)
PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage< T >::value > > SetArgPointee(const T &x)
internal::DoDefaultAction DoDefault()
PolymorphicAction< internal::ReturnNullAction > ReturnNull()
internal::PointeeMatcher< InnerMatcher > Pointee(const InnerMatcher &inner_matcher)
#define value
Definition pkcs11.h:157
const GenericPointer< typename T::ValueType > T2 T::AllocatorType & a
Definition pointer.h:1181
#define T(meth, val, expected)
Foo()
Definition fwdtest.cpp:106
Definition dtoa.c:306
CK_ULONG d
CK_RV ret
char * s
uint16_t j