gmock-actions_test.cc 50 KB

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