gmock-actions_test.cc 44 KB

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