gmock-actions_test.cc 42 KB

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