gmock-spec-builders_test.cc 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774
  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 spec builder syntax.
  32. #include "gmock/gmock-spec-builders.h"
  33. #include <memory>
  34. #include <ostream> // NOLINT
  35. #include <sstream>
  36. #include <string>
  37. #include "gmock/gmock.h"
  38. #include "gmock/internal/gmock-port.h"
  39. #include "gtest/gtest.h"
  40. #include "gtest/gtest-spi.h"
  41. #include "gtest/internal/gtest-port.h"
  42. namespace testing {
  43. namespace internal {
  44. // Helper class for testing the Expectation class template.
  45. class ExpectationTester {
  46. public:
  47. // Sets the call count of the given expectation to the given number.
  48. void SetCallCount(int n, ExpectationBase* exp) {
  49. exp->call_count_ = n;
  50. }
  51. };
  52. } // namespace internal
  53. } // namespace testing
  54. namespace {
  55. using testing::_;
  56. using testing::AnyNumber;
  57. using testing::AtLeast;
  58. using testing::AtMost;
  59. using testing::Between;
  60. using testing::Cardinality;
  61. using testing::CardinalityInterface;
  62. using testing::Const;
  63. using testing::ContainsRegex;
  64. using testing::DoAll;
  65. using testing::DoDefault;
  66. using testing::Eq;
  67. using testing::Expectation;
  68. using testing::ExpectationSet;
  69. using testing::Gt;
  70. using testing::IgnoreResult;
  71. using testing::InSequence;
  72. using testing::Invoke;
  73. using testing::InvokeWithoutArgs;
  74. using testing::IsNotSubstring;
  75. using testing::IsSubstring;
  76. using testing::Lt;
  77. using testing::Message;
  78. using testing::Mock;
  79. using testing::NaggyMock;
  80. using testing::Ne;
  81. using testing::Return;
  82. using testing::SaveArg;
  83. using testing::Sequence;
  84. using testing::SetArgPointee;
  85. using testing::internal::ExpectationTester;
  86. using testing::internal::FormatFileLocation;
  87. using testing::internal::kAllow;
  88. using testing::internal::kErrorVerbosity;
  89. using testing::internal::kFail;
  90. using testing::internal::kInfoVerbosity;
  91. using testing::internal::kWarn;
  92. using testing::internal::kWarningVerbosity;
  93. #if GTEST_HAS_STREAM_REDIRECTION
  94. using testing::HasSubstr;
  95. using testing::internal::CaptureStdout;
  96. using testing::internal::GetCapturedStdout;
  97. #endif
  98. class Incomplete;
  99. class MockIncomplete {
  100. public:
  101. // This line verifies that a mock method can take a by-reference
  102. // argument of an incomplete type.
  103. MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
  104. };
  105. // Tells Google Mock how to print a value of type Incomplete.
  106. void PrintTo(const Incomplete& x, ::std::ostream* os);
  107. TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
  108. // Even though this mock class contains a mock method that takes
  109. // by-reference an argument whose type is incomplete, we can still
  110. // use the mock, as long as Google Mock knows how to print the
  111. // argument.
  112. MockIncomplete incomplete;
  113. EXPECT_CALL(incomplete, ByRefFunc(_))
  114. .Times(AnyNumber());
  115. }
  116. // The definition of the printer for the argument type doesn't have to
  117. // be visible where the mock is used.
  118. void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
  119. *os << "incomplete";
  120. }
  121. class Result {};
  122. // A type that's not default constructible.
  123. class NonDefaultConstructible {
  124. public:
  125. explicit NonDefaultConstructible(int /* dummy */) {}
  126. };
  127. class MockA {
  128. public:
  129. MockA() {}
  130. MOCK_METHOD1(DoA, void(int n));
  131. MOCK_METHOD1(ReturnResult, Result(int n));
  132. MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
  133. MOCK_METHOD2(Binary, bool(int x, int y));
  134. MOCK_METHOD2(ReturnInt, int(int x, int y));
  135. private:
  136. GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
  137. };
  138. class MockB {
  139. public:
  140. MockB() {}
  141. MOCK_CONST_METHOD0(DoB, int()); // NOLINT
  142. MOCK_METHOD1(DoB, int(int n)); // NOLINT
  143. private:
  144. GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
  145. };
  146. class ReferenceHoldingMock {
  147. public:
  148. ReferenceHoldingMock() {}
  149. MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
  150. private:
  151. GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
  152. };
  153. // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
  154. // redefining a mock method name. This could happen, for example, when
  155. // the tested code #includes Win32 API headers which define many APIs
  156. // as macros, e.g. #define TextOut TextOutW.
  157. #define Method MethodW
  158. class CC {
  159. public:
  160. virtual ~CC() {}
  161. virtual int Method() = 0;
  162. };
  163. class MockCC : public CC {
  164. public:
  165. MockCC() {}
  166. MOCK_METHOD0(Method, int());
  167. private:
  168. GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
  169. };
  170. // Tests that a method with expanded name compiles.
  171. TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
  172. MockCC cc;
  173. ON_CALL(cc, Method());
  174. }
  175. // Tests that the method with expanded name not only compiles but runs
  176. // and returns a correct value, too.
  177. TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
  178. MockCC cc;
  179. ON_CALL(cc, Method()).WillByDefault(Return(42));
  180. EXPECT_EQ(42, cc.Method());
  181. }
  182. // Tests that a method with expanded name compiles.
  183. TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
  184. MockCC cc;
  185. EXPECT_CALL(cc, Method());
  186. cc.Method();
  187. }
  188. // Tests that it works, too.
  189. TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
  190. MockCC cc;
  191. EXPECT_CALL(cc, Method()).WillOnce(Return(42));
  192. EXPECT_EQ(42, cc.Method());
  193. }
  194. #undef Method // Done with macro redefinition tests.
  195. // Tests that ON_CALL evaluates its arguments exactly once as promised
  196. // by Google Mock.
  197. TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
  198. MockA a;
  199. MockA* pa = &a;
  200. ON_CALL(*pa++, DoA(_));
  201. EXPECT_EQ(&a + 1, pa);
  202. }
  203. TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
  204. MockA a;
  205. int n = 0;
  206. ON_CALL(a, DoA(n++));
  207. EXPECT_EQ(1, n);
  208. }
  209. // Tests that the syntax of ON_CALL() is enforced at run time.
  210. TEST(OnCallSyntaxTest, WithIsOptional) {
  211. MockA a;
  212. ON_CALL(a, DoA(5))
  213. .WillByDefault(Return());
  214. ON_CALL(a, DoA(_))
  215. .With(_)
  216. .WillByDefault(Return());
  217. }
  218. TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
  219. MockA a;
  220. EXPECT_NONFATAL_FAILURE({ // NOLINT
  221. ON_CALL(a, ReturnResult(_))
  222. .With(_)
  223. .With(_)
  224. .WillByDefault(Return(Result()));
  225. }, ".With() cannot appear more than once in an ON_CALL()");
  226. }
  227. TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
  228. MockA a;
  229. EXPECT_DEATH_IF_SUPPORTED({
  230. ON_CALL(a, DoA(5));
  231. a.DoA(5);
  232. }, "");
  233. }
  234. TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
  235. MockA a;
  236. EXPECT_NONFATAL_FAILURE({ // NOLINT
  237. ON_CALL(a, DoA(5))
  238. .WillByDefault(Return())
  239. .WillByDefault(Return());
  240. }, ".WillByDefault() must appear exactly once in an ON_CALL()");
  241. }
  242. // Tests that EXPECT_CALL evaluates its arguments exactly once as
  243. // promised by Google Mock.
  244. TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
  245. MockA a;
  246. MockA* pa = &a;
  247. EXPECT_CALL(*pa++, DoA(_));
  248. a.DoA(0);
  249. EXPECT_EQ(&a + 1, pa);
  250. }
  251. TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
  252. MockA a;
  253. int n = 0;
  254. EXPECT_CALL(a, DoA(n++));
  255. a.DoA(0);
  256. EXPECT_EQ(1, n);
  257. }
  258. // Tests that the syntax of EXPECT_CALL() is enforced at run time.
  259. TEST(ExpectCallSyntaxTest, WithIsOptional) {
  260. MockA a;
  261. EXPECT_CALL(a, DoA(5))
  262. .Times(0);
  263. EXPECT_CALL(a, DoA(6))
  264. .With(_)
  265. .Times(0);
  266. }
  267. TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
  268. MockA a;
  269. EXPECT_NONFATAL_FAILURE({ // NOLINT
  270. EXPECT_CALL(a, DoA(6))
  271. .With(_)
  272. .With(_);
  273. }, ".With() cannot appear more than once in an EXPECT_CALL()");
  274. a.DoA(6);
  275. }
  276. TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
  277. MockA a;
  278. EXPECT_NONFATAL_FAILURE({ // NOLINT
  279. EXPECT_CALL(a, DoA(1))
  280. .Times(1)
  281. .With(_);
  282. }, ".With() must be the first clause in an EXPECT_CALL()");
  283. a.DoA(1);
  284. EXPECT_NONFATAL_FAILURE({ // NOLINT
  285. EXPECT_CALL(a, DoA(2))
  286. .WillOnce(Return())
  287. .With(_);
  288. }, ".With() must be the first clause in an EXPECT_CALL()");
  289. a.DoA(2);
  290. }
  291. TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
  292. MockA a;
  293. EXPECT_CALL(a, DoA(1))
  294. .WillOnce(Return());
  295. EXPECT_CALL(a, DoA(2))
  296. .WillOnce(Return())
  297. .WillRepeatedly(Return());
  298. a.DoA(1);
  299. a.DoA(2);
  300. a.DoA(2);
  301. }
  302. TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
  303. MockA a;
  304. EXPECT_NONFATAL_FAILURE({ // NOLINT
  305. EXPECT_CALL(a, DoA(1))
  306. .Times(1)
  307. .Times(2);
  308. }, ".Times() cannot appear more than once in an EXPECT_CALL()");
  309. a.DoA(1);
  310. a.DoA(1);
  311. }
  312. TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
  313. MockA a;
  314. Sequence s;
  315. EXPECT_NONFATAL_FAILURE({ // NOLINT
  316. EXPECT_CALL(a, DoA(1))
  317. .InSequence(s)
  318. .Times(1);
  319. }, ".Times() may only appear *before* ");
  320. a.DoA(1);
  321. }
  322. TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
  323. MockA a;
  324. Sequence s;
  325. EXPECT_CALL(a, DoA(1));
  326. EXPECT_CALL(a, DoA(2))
  327. .InSequence(s);
  328. a.DoA(1);
  329. a.DoA(2);
  330. }
  331. TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
  332. MockA a;
  333. Sequence s1, s2;
  334. EXPECT_CALL(a, DoA(1))
  335. .InSequence(s1, s2)
  336. .InSequence(s1);
  337. a.DoA(1);
  338. }
  339. TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
  340. MockA a;
  341. Sequence s;
  342. Expectation e = EXPECT_CALL(a, DoA(1))
  343. .Times(AnyNumber());
  344. EXPECT_NONFATAL_FAILURE({ // NOLINT
  345. EXPECT_CALL(a, DoA(2))
  346. .After(e)
  347. .InSequence(s);
  348. }, ".InSequence() cannot appear after ");
  349. a.DoA(2);
  350. }
  351. TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
  352. MockA a;
  353. Sequence s;
  354. EXPECT_NONFATAL_FAILURE({ // NOLINT
  355. EXPECT_CALL(a, DoA(1))
  356. .WillOnce(Return())
  357. .InSequence(s);
  358. }, ".InSequence() cannot appear after ");
  359. a.DoA(1);
  360. }
  361. TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
  362. MockA a;
  363. Expectation e = EXPECT_CALL(a, DoA(1));
  364. EXPECT_NONFATAL_FAILURE({
  365. EXPECT_CALL(a, DoA(2))
  366. .WillOnce(Return())
  367. .After(e);
  368. }, ".After() cannot appear after ");
  369. a.DoA(1);
  370. a.DoA(2);
  371. }
  372. TEST(ExpectCallSyntaxTest, WillIsOptional) {
  373. MockA a;
  374. EXPECT_CALL(a, DoA(1));
  375. EXPECT_CALL(a, DoA(2))
  376. .WillOnce(Return());
  377. a.DoA(1);
  378. a.DoA(2);
  379. }
  380. TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
  381. MockA a;
  382. EXPECT_CALL(a, DoA(1))
  383. .Times(AnyNumber())
  384. .WillOnce(Return())
  385. .WillOnce(Return())
  386. .WillOnce(Return());
  387. }
  388. TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
  389. MockA a;
  390. EXPECT_NONFATAL_FAILURE({ // NOLINT
  391. EXPECT_CALL(a, DoA(1))
  392. .WillRepeatedly(Return())
  393. .WillOnce(Return());
  394. }, ".WillOnce() cannot appear after ");
  395. a.DoA(1);
  396. }
  397. TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
  398. MockA a;
  399. EXPECT_CALL(a, DoA(1))
  400. .WillOnce(Return());
  401. EXPECT_CALL(a, DoA(2))
  402. .WillOnce(Return())
  403. .WillRepeatedly(Return());
  404. a.DoA(1);
  405. a.DoA(2);
  406. a.DoA(2);
  407. }
  408. TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
  409. MockA a;
  410. EXPECT_NONFATAL_FAILURE({ // NOLINT
  411. EXPECT_CALL(a, DoA(1))
  412. .WillRepeatedly(Return())
  413. .WillRepeatedly(Return());
  414. }, ".WillRepeatedly() cannot appear more than once in an "
  415. "EXPECT_CALL()");
  416. }
  417. TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
  418. MockA a;
  419. EXPECT_NONFATAL_FAILURE({ // NOLINT
  420. EXPECT_CALL(a, DoA(1))
  421. .RetiresOnSaturation()
  422. .WillRepeatedly(Return());
  423. }, ".WillRepeatedly() cannot appear after ");
  424. }
  425. TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
  426. MockA a;
  427. EXPECT_CALL(a, DoA(1));
  428. EXPECT_CALL(a, DoA(1))
  429. .RetiresOnSaturation();
  430. a.DoA(1);
  431. a.DoA(1);
  432. }
  433. TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
  434. MockA a;
  435. EXPECT_NONFATAL_FAILURE({ // NOLINT
  436. EXPECT_CALL(a, DoA(1))
  437. .RetiresOnSaturation()
  438. .RetiresOnSaturation();
  439. }, ".RetiresOnSaturation() cannot appear more than once");
  440. a.DoA(1);
  441. }
  442. TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
  443. {
  444. MockA a;
  445. EXPECT_CALL(a, DoA(1));
  446. a.DoA(1);
  447. }
  448. EXPECT_NONFATAL_FAILURE({ // NOLINT
  449. MockA a;
  450. EXPECT_CALL(a, DoA(1));
  451. }, "to be called once");
  452. EXPECT_NONFATAL_FAILURE({ // NOLINT
  453. MockA a;
  454. EXPECT_CALL(a, DoA(1));
  455. a.DoA(1);
  456. a.DoA(1);
  457. }, "to be called once");
  458. }
  459. #if GTEST_HAS_STREAM_REDIRECTION
  460. // Tests that Google Mock doesn't print a warning when the number of
  461. // WillOnce() is adequate.
  462. TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
  463. CaptureStdout();
  464. {
  465. MockB b;
  466. // It's always fine to omit WillOnce() entirely.
  467. EXPECT_CALL(b, DoB())
  468. .Times(0);
  469. EXPECT_CALL(b, DoB(1))
  470. .Times(AtMost(1));
  471. EXPECT_CALL(b, DoB(2))
  472. .Times(1)
  473. .WillRepeatedly(Return(1));
  474. // It's fine for the number of WillOnce()s to equal the upper bound.
  475. EXPECT_CALL(b, DoB(3))
  476. .Times(Between(1, 2))
  477. .WillOnce(Return(1))
  478. .WillOnce(Return(2));
  479. // It's fine for the number of WillOnce()s to be smaller than the
  480. // upper bound when there is a WillRepeatedly().
  481. EXPECT_CALL(b, DoB(4))
  482. .Times(AtMost(3))
  483. .WillOnce(Return(1))
  484. .WillRepeatedly(Return(2));
  485. // Satisfies the above expectations.
  486. b.DoB(2);
  487. b.DoB(3);
  488. }
  489. EXPECT_STREQ("", GetCapturedStdout().c_str());
  490. }
  491. // Tests that Google Mock warns on having too many actions in an
  492. // expectation compared to its cardinality.
  493. TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
  494. CaptureStdout();
  495. {
  496. MockB b;
  497. // Warns when the number of WillOnce()s is larger than the upper bound.
  498. EXPECT_CALL(b, DoB())
  499. .Times(0)
  500. .WillOnce(Return(1)); // #1
  501. EXPECT_CALL(b, DoB())
  502. .Times(AtMost(1))
  503. .WillOnce(Return(1))
  504. .WillOnce(Return(2)); // #2
  505. EXPECT_CALL(b, DoB(1))
  506. .Times(1)
  507. .WillOnce(Return(1))
  508. .WillOnce(Return(2))
  509. .RetiresOnSaturation(); // #3
  510. // Warns when the number of WillOnce()s equals the upper bound and
  511. // there is a WillRepeatedly().
  512. EXPECT_CALL(b, DoB())
  513. .Times(0)
  514. .WillRepeatedly(Return(1)); // #4
  515. EXPECT_CALL(b, DoB(2))
  516. .Times(1)
  517. .WillOnce(Return(1))
  518. .WillRepeatedly(Return(2)); // #5
  519. // Satisfies the above expectations.
  520. b.DoB(1);
  521. b.DoB(2);
  522. }
  523. const std::string output = GetCapturedStdout();
  524. EXPECT_PRED_FORMAT2(
  525. IsSubstring,
  526. "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
  527. "Expected to be never called, but has 1 WillOnce().",
  528. output); // #1
  529. EXPECT_PRED_FORMAT2(
  530. IsSubstring,
  531. "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
  532. "Expected to be called at most once, "
  533. "but has 2 WillOnce()s.",
  534. output); // #2
  535. EXPECT_PRED_FORMAT2(
  536. IsSubstring,
  537. "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
  538. "Expected to be called once, but has 2 WillOnce()s.",
  539. output); // #3
  540. EXPECT_PRED_FORMAT2(
  541. IsSubstring,
  542. "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
  543. "Expected to be never called, but has 0 WillOnce()s "
  544. "and a WillRepeatedly().",
  545. output); // #4
  546. EXPECT_PRED_FORMAT2(
  547. IsSubstring,
  548. "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
  549. "Expected to be called once, but has 1 WillOnce() "
  550. "and a WillRepeatedly().",
  551. output); // #5
  552. }
  553. // Tests that Google Mock warns on having too few actions in an
  554. // expectation compared to its cardinality.
  555. TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
  556. MockB b;
  557. EXPECT_CALL(b, DoB())
  558. .Times(Between(2, 3))
  559. .WillOnce(Return(1));
  560. CaptureStdout();
  561. b.DoB();
  562. const std::string output = GetCapturedStdout();
  563. EXPECT_PRED_FORMAT2(
  564. IsSubstring,
  565. "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
  566. "Expected to be called between 2 and 3 times, "
  567. "but has only 1 WillOnce().",
  568. output);
  569. b.DoB();
  570. }
  571. TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
  572. int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);
  573. GMOCK_FLAG_SET(default_mock_behavior, kAllow);
  574. CaptureStdout();
  575. {
  576. MockA a;
  577. a.DoA(0);
  578. }
  579. std::string output = GetCapturedStdout();
  580. EXPECT_TRUE(output.empty()) << output;
  581. GMOCK_FLAG_SET(default_mock_behavior, kWarn);
  582. CaptureStdout();
  583. {
  584. MockA a;
  585. a.DoA(0);
  586. }
  587. std::string warning_output = GetCapturedStdout();
  588. EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
  589. EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
  590. warning_output);
  591. GMOCK_FLAG_SET(default_mock_behavior, kFail);
  592. EXPECT_NONFATAL_FAILURE({
  593. MockA a;
  594. a.DoA(0);
  595. }, "Uninteresting mock function call");
  596. // Out of bounds values are converted to kWarn
  597. GMOCK_FLAG_SET(default_mock_behavior, -1);
  598. CaptureStdout();
  599. {
  600. MockA a;
  601. a.DoA(0);
  602. }
  603. warning_output = GetCapturedStdout();
  604. EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
  605. EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
  606. warning_output);
  607. GMOCK_FLAG_SET(default_mock_behavior, 3);
  608. CaptureStdout();
  609. {
  610. MockA a;
  611. a.DoA(0);
  612. }
  613. warning_output = GetCapturedStdout();
  614. EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
  615. EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
  616. warning_output);
  617. GMOCK_FLAG_SET(default_mock_behavior, original_behavior);
  618. }
  619. #endif // GTEST_HAS_STREAM_REDIRECTION
  620. // Tests the semantics of ON_CALL().
  621. // Tests that the built-in default action is taken when no ON_CALL()
  622. // is specified.
  623. TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
  624. MockB b;
  625. EXPECT_CALL(b, DoB());
  626. EXPECT_EQ(0, b.DoB());
  627. }
  628. // Tests that the built-in default action is taken when no ON_CALL()
  629. // matches the invocation.
  630. TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
  631. MockB b;
  632. ON_CALL(b, DoB(1))
  633. .WillByDefault(Return(1));
  634. EXPECT_CALL(b, DoB(_));
  635. EXPECT_EQ(0, b.DoB(2));
  636. }
  637. // Tests that the last matching ON_CALL() action is taken.
  638. TEST(OnCallTest, PicksLastMatchingOnCall) {
  639. MockB b;
  640. ON_CALL(b, DoB(_))
  641. .WillByDefault(Return(3));
  642. ON_CALL(b, DoB(2))
  643. .WillByDefault(Return(2));
  644. ON_CALL(b, DoB(1))
  645. .WillByDefault(Return(1));
  646. EXPECT_CALL(b, DoB(_));
  647. EXPECT_EQ(2, b.DoB(2));
  648. }
  649. // Tests the semantics of EXPECT_CALL().
  650. // Tests that any call is allowed when no EXPECT_CALL() is specified.
  651. TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
  652. MockB b;
  653. EXPECT_CALL(b, DoB());
  654. // There is no expectation on DoB(int).
  655. b.DoB();
  656. // DoB(int) can be called any number of times.
  657. b.DoB(1);
  658. b.DoB(2);
  659. }
  660. // Tests that the last matching EXPECT_CALL() fires.
  661. TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
  662. MockB b;
  663. EXPECT_CALL(b, DoB(_))
  664. .WillRepeatedly(Return(2));
  665. EXPECT_CALL(b, DoB(1))
  666. .WillRepeatedly(Return(1));
  667. EXPECT_EQ(1, b.DoB(1));
  668. }
  669. // Tests lower-bound violation.
  670. TEST(ExpectCallTest, CatchesTooFewCalls) {
  671. EXPECT_NONFATAL_FAILURE({ // NOLINT
  672. MockB b;
  673. EXPECT_CALL(b, DoB(5))
  674. .Times(AtLeast(2));
  675. b.DoB(5);
  676. }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
  677. " Expected: to be called at least twice\n"
  678. " Actual: called once - unsatisfied and active");
  679. }
  680. // Tests that the cardinality can be inferred when no Times(...) is
  681. // specified.
  682. TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
  683. {
  684. MockB b;
  685. EXPECT_CALL(b, DoB())
  686. .WillOnce(Return(1))
  687. .WillOnce(Return(2));
  688. EXPECT_EQ(1, b.DoB());
  689. EXPECT_EQ(2, b.DoB());
  690. }
  691. EXPECT_NONFATAL_FAILURE({ // NOLINT
  692. MockB b;
  693. EXPECT_CALL(b, DoB())
  694. .WillOnce(Return(1))
  695. .WillOnce(Return(2));
  696. EXPECT_EQ(1, b.DoB());
  697. }, "to be called twice");
  698. { // NOLINT
  699. MockB b;
  700. EXPECT_CALL(b, DoB())
  701. .WillOnce(Return(1))
  702. .WillOnce(Return(2));
  703. EXPECT_EQ(1, b.DoB());
  704. EXPECT_EQ(2, b.DoB());
  705. EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
  706. }
  707. }
  708. TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
  709. {
  710. MockB b;
  711. EXPECT_CALL(b, DoB())
  712. .WillOnce(Return(1))
  713. .WillRepeatedly(Return(2));
  714. EXPECT_EQ(1, b.DoB());
  715. }
  716. { // NOLINT
  717. MockB b;
  718. EXPECT_CALL(b, DoB())
  719. .WillOnce(Return(1))
  720. .WillRepeatedly(Return(2));
  721. EXPECT_EQ(1, b.DoB());
  722. EXPECT_EQ(2, b.DoB());
  723. EXPECT_EQ(2, b.DoB());
  724. }
  725. EXPECT_NONFATAL_FAILURE({ // NOLINT
  726. MockB b;
  727. EXPECT_CALL(b, DoB())
  728. .WillOnce(Return(1))
  729. .WillRepeatedly(Return(2));
  730. }, "to be called at least once");
  731. }
  732. // Tests that the n-th action is taken for the n-th matching
  733. // invocation.
  734. TEST(ExpectCallTest, NthMatchTakesNthAction) {
  735. MockB b;
  736. EXPECT_CALL(b, DoB())
  737. .WillOnce(Return(1))
  738. .WillOnce(Return(2))
  739. .WillOnce(Return(3));
  740. EXPECT_EQ(1, b.DoB());
  741. EXPECT_EQ(2, b.DoB());
  742. EXPECT_EQ(3, b.DoB());
  743. }
  744. // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
  745. // list is exhausted.
  746. TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
  747. MockB b;
  748. EXPECT_CALL(b, DoB())
  749. .WillOnce(Return(1))
  750. .WillRepeatedly(Return(2));
  751. EXPECT_EQ(1, b.DoB());
  752. EXPECT_EQ(2, b.DoB());
  753. EXPECT_EQ(2, b.DoB());
  754. }
  755. #if GTEST_HAS_STREAM_REDIRECTION
  756. // Tests that the default action is taken when the WillOnce(...) list is
  757. // exhausted and there is no WillRepeatedly().
  758. TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
  759. MockB b;
  760. EXPECT_CALL(b, DoB(_))
  761. .Times(1);
  762. EXPECT_CALL(b, DoB())
  763. .Times(AnyNumber())
  764. .WillOnce(Return(1))
  765. .WillOnce(Return(2));
  766. CaptureStdout();
  767. EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
  768. // expectation has no action clause at all.
  769. EXPECT_EQ(1, b.DoB());
  770. EXPECT_EQ(2, b.DoB());
  771. const std::string output1 = GetCapturedStdout();
  772. EXPECT_STREQ("", output1.c_str());
  773. CaptureStdout();
  774. EXPECT_EQ(0, b.DoB());
  775. EXPECT_EQ(0, b.DoB());
  776. const std::string output2 = GetCapturedStdout();
  777. EXPECT_THAT(output2.c_str(),
  778. HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
  779. "Called 3 times, but only 2 WillOnce()s are specified"
  780. " - returning default value."));
  781. EXPECT_THAT(output2.c_str(),
  782. HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
  783. "Called 4 times, but only 2 WillOnce()s are specified"
  784. " - returning default value."));
  785. }
  786. TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
  787. MockB b;
  788. std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
  789. EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
  790. EXPECT_EQ(1, b.DoB());
  791. CaptureStdout();
  792. EXPECT_EQ(0, b.DoB());
  793. const std::string output = GetCapturedStdout();
  794. // The warning message should contain the call location.
  795. EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
  796. }
  797. TEST(FunctionMockerMessageTest,
  798. ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
  799. std::string on_call_location;
  800. CaptureStdout();
  801. {
  802. NaggyMock<MockB> b;
  803. on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
  804. ON_CALL(b, DoB(_)).WillByDefault(Return(0));
  805. b.DoB(0);
  806. }
  807. EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
  808. }
  809. #endif // GTEST_HAS_STREAM_REDIRECTION
  810. // Tests that an uninteresting call performs the default action.
  811. TEST(UninterestingCallTest, DoesDefaultAction) {
  812. // When there is an ON_CALL() statement, the action specified by it
  813. // should be taken.
  814. MockA a;
  815. ON_CALL(a, Binary(_, _))
  816. .WillByDefault(Return(true));
  817. EXPECT_TRUE(a.Binary(1, 2));
  818. // When there is no ON_CALL(), the default value for the return type
  819. // should be returned.
  820. MockB b;
  821. EXPECT_EQ(0, b.DoB());
  822. }
  823. // Tests that an unexpected call performs the default action.
  824. TEST(UnexpectedCallTest, DoesDefaultAction) {
  825. // When there is an ON_CALL() statement, the action specified by it
  826. // should be taken.
  827. MockA a;
  828. ON_CALL(a, Binary(_, _))
  829. .WillByDefault(Return(true));
  830. EXPECT_CALL(a, Binary(0, 0));
  831. a.Binary(0, 0);
  832. bool result = false;
  833. EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
  834. "Unexpected mock function call");
  835. EXPECT_TRUE(result);
  836. // When there is no ON_CALL(), the default value for the return type
  837. // should be returned.
  838. MockB b;
  839. EXPECT_CALL(b, DoB(0))
  840. .Times(0);
  841. int n = -1;
  842. EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
  843. "Unexpected mock function call");
  844. EXPECT_EQ(0, n);
  845. }
  846. // Tests that when an unexpected void function generates the right
  847. // failure message.
  848. TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
  849. // First, tests the message when there is only one EXPECT_CALL().
  850. MockA a1;
  851. EXPECT_CALL(a1, DoA(1));
  852. a1.DoA(1);
  853. // Ideally we should match the failure message against a regex, but
  854. // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
  855. // multiple sub-strings instead.
  856. EXPECT_NONFATAL_FAILURE(
  857. a1.DoA(9),
  858. "Unexpected mock function call - returning directly.\n"
  859. " Function call: DoA(9)\n"
  860. "Google Mock tried the following 1 expectation, but it didn't match:");
  861. EXPECT_NONFATAL_FAILURE(
  862. a1.DoA(9),
  863. " Expected arg #0: is equal to 1\n"
  864. " Actual: 9\n"
  865. " Expected: to be called once\n"
  866. " Actual: called once - saturated and active");
  867. // Next, tests the message when there are more than one EXPECT_CALL().
  868. MockA a2;
  869. EXPECT_CALL(a2, DoA(1));
  870. EXPECT_CALL(a2, DoA(3));
  871. a2.DoA(1);
  872. EXPECT_NONFATAL_FAILURE(
  873. a2.DoA(2),
  874. "Unexpected mock function call - returning directly.\n"
  875. " Function call: DoA(2)\n"
  876. "Google Mock tried the following 2 expectations, but none matched:");
  877. EXPECT_NONFATAL_FAILURE(
  878. a2.DoA(2),
  879. "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
  880. " Expected arg #0: is equal to 1\n"
  881. " Actual: 2\n"
  882. " Expected: to be called once\n"
  883. " Actual: called once - saturated and active");
  884. EXPECT_NONFATAL_FAILURE(
  885. a2.DoA(2),
  886. "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
  887. " Expected arg #0: is equal to 3\n"
  888. " Actual: 2\n"
  889. " Expected: to be called once\n"
  890. " Actual: never called - unsatisfied and active");
  891. a2.DoA(3);
  892. }
  893. // Tests that an unexpected non-void function generates the right
  894. // failure message.
  895. TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
  896. MockB b1;
  897. EXPECT_CALL(b1, DoB(1));
  898. b1.DoB(1);
  899. EXPECT_NONFATAL_FAILURE(
  900. b1.DoB(2),
  901. "Unexpected mock function call - returning default value.\n"
  902. " Function call: DoB(2)\n"
  903. " Returns: 0\n"
  904. "Google Mock tried the following 1 expectation, but it didn't match:");
  905. EXPECT_NONFATAL_FAILURE(
  906. b1.DoB(2),
  907. " Expected arg #0: is equal to 1\n"
  908. " Actual: 2\n"
  909. " Expected: to be called once\n"
  910. " Actual: called once - saturated and active");
  911. }
  912. // Tests that Google Mock explains that an retired expectation doesn't
  913. // match the call.
  914. TEST(UnexpectedCallTest, RetiredExpectation) {
  915. MockB b;
  916. EXPECT_CALL(b, DoB(1))
  917. .RetiresOnSaturation();
  918. b.DoB(1);
  919. EXPECT_NONFATAL_FAILURE(
  920. b.DoB(1),
  921. " Expected: the expectation is active\n"
  922. " Actual: it is retired");
  923. }
  924. // Tests that Google Mock explains that an expectation that doesn't
  925. // match the arguments doesn't match the call.
  926. TEST(UnexpectedCallTest, UnmatchedArguments) {
  927. MockB b;
  928. EXPECT_CALL(b, DoB(1));
  929. EXPECT_NONFATAL_FAILURE(
  930. b.DoB(2),
  931. " Expected arg #0: is equal to 1\n"
  932. " Actual: 2\n");
  933. b.DoB(1);
  934. }
  935. // Tests that Google Mock explains that an expectation with
  936. // unsatisfied pre-requisites doesn't match the call.
  937. TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
  938. Sequence s1, s2;
  939. MockB b;
  940. EXPECT_CALL(b, DoB(1))
  941. .InSequence(s1);
  942. EXPECT_CALL(b, DoB(2))
  943. .Times(AnyNumber())
  944. .InSequence(s1);
  945. EXPECT_CALL(b, DoB(3))
  946. .InSequence(s2);
  947. EXPECT_CALL(b, DoB(4))
  948. .InSequence(s1, s2);
  949. ::testing::TestPartResultArray failures;
  950. {
  951. ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
  952. b.DoB(4);
  953. // Now 'failures' contains the Google Test failures generated by
  954. // the above statement.
  955. }
  956. // There should be one non-fatal failure.
  957. ASSERT_EQ(1, failures.size());
  958. const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
  959. EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
  960. // Verifies that the failure message contains the two unsatisfied
  961. // pre-requisites but not the satisfied one.
  962. #if GTEST_USES_PCRE
  963. EXPECT_THAT(r.message(), ContainsRegex(
  964. // PCRE has trouble using (.|\n) to match any character, but
  965. // supports the (?s) prefix for using . to match any character.
  966. "(?s)the following immediate pre-requisites are not satisfied:\n"
  967. ".*: pre-requisite #0\n"
  968. ".*: pre-requisite #1"));
  969. #elif GTEST_USES_POSIX_RE
  970. EXPECT_THAT(r.message(), ContainsRegex(
  971. // POSIX RE doesn't understand the (?s) prefix, but has no trouble
  972. // with (.|\n).
  973. "the following immediate pre-requisites are not satisfied:\n"
  974. "(.|\n)*: pre-requisite #0\n"
  975. "(.|\n)*: pre-requisite #1"));
  976. #else
  977. // We can only use Google Test's own simple regex.
  978. EXPECT_THAT(r.message(), ContainsRegex(
  979. "the following immediate pre-requisites are not satisfied:"));
  980. EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
  981. EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
  982. #endif // GTEST_USES_PCRE
  983. b.DoB(1);
  984. b.DoB(3);
  985. b.DoB(4);
  986. }
  987. TEST(UndefinedReturnValueTest,
  988. ReturnValueIsMandatoryWhenNotDefaultConstructible) {
  989. MockA a;
  990. // FIXME: We should really verify the output message,
  991. // but we cannot yet due to that EXPECT_DEATH only captures stderr
  992. // while Google Mock logs to stdout.
  993. #if GTEST_HAS_EXCEPTIONS
  994. EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
  995. #else
  996. EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
  997. #endif
  998. }
  999. // Tests that an excessive call (one whose arguments match the
  1000. // matchers but is called too many times) performs the default action.
  1001. TEST(ExcessiveCallTest, DoesDefaultAction) {
  1002. // When there is an ON_CALL() statement, the action specified by it
  1003. // should be taken.
  1004. MockA a;
  1005. ON_CALL(a, Binary(_, _))
  1006. .WillByDefault(Return(true));
  1007. EXPECT_CALL(a, Binary(0, 0));
  1008. a.Binary(0, 0);
  1009. bool result = false;
  1010. EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
  1011. "Mock function called more times than expected");
  1012. EXPECT_TRUE(result);
  1013. // When there is no ON_CALL(), the default value for the return type
  1014. // should be returned.
  1015. MockB b;
  1016. EXPECT_CALL(b, DoB(0))
  1017. .Times(0);
  1018. int n = -1;
  1019. EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
  1020. "Mock function called more times than expected");
  1021. EXPECT_EQ(0, n);
  1022. }
  1023. // Tests that when a void function is called too many times,
  1024. // the failure message contains the argument values.
  1025. TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
  1026. MockA a;
  1027. EXPECT_CALL(a, DoA(_))
  1028. .Times(0);
  1029. EXPECT_NONFATAL_FAILURE(
  1030. a.DoA(9),
  1031. "Mock function called more times than expected - returning directly.\n"
  1032. " Function call: DoA(9)\n"
  1033. " Expected: to be never called\n"
  1034. " Actual: called once - over-saturated and active");
  1035. }
  1036. // Tests that when a non-void function is called too many times, the
  1037. // failure message contains the argument values and the return value.
  1038. TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
  1039. MockB b;
  1040. EXPECT_CALL(b, DoB(_));
  1041. b.DoB(1);
  1042. EXPECT_NONFATAL_FAILURE(
  1043. b.DoB(2),
  1044. "Mock function called more times than expected - "
  1045. "returning default value.\n"
  1046. " Function call: DoB(2)\n"
  1047. " Returns: 0\n"
  1048. " Expected: to be called once\n"
  1049. " Actual: called twice - over-saturated and active");
  1050. }
  1051. // Tests using sequences.
  1052. TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
  1053. MockA a;
  1054. {
  1055. InSequence dummy;
  1056. EXPECT_CALL(a, DoA(1));
  1057. EXPECT_CALL(a, DoA(2));
  1058. }
  1059. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1060. a.DoA(2);
  1061. }, "Unexpected mock function call");
  1062. a.DoA(1);
  1063. a.DoA(2);
  1064. }
  1065. TEST(InSequenceTest, NestedInSequence) {
  1066. MockA a;
  1067. {
  1068. InSequence dummy;
  1069. EXPECT_CALL(a, DoA(1));
  1070. {
  1071. InSequence dummy2;
  1072. EXPECT_CALL(a, DoA(2));
  1073. EXPECT_CALL(a, DoA(3));
  1074. }
  1075. }
  1076. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1077. a.DoA(1);
  1078. a.DoA(3);
  1079. }, "Unexpected mock function call");
  1080. a.DoA(2);
  1081. a.DoA(3);
  1082. }
  1083. TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
  1084. MockA a;
  1085. {
  1086. InSequence dummy;
  1087. EXPECT_CALL(a, DoA(1));
  1088. EXPECT_CALL(a, DoA(2));
  1089. }
  1090. EXPECT_CALL(a, DoA(3));
  1091. EXPECT_NONFATAL_FAILURE({ // NOLINT
  1092. a.DoA(2);
  1093. }, "Unexpected mock function call");
  1094. a.DoA(3);
  1095. a.DoA(1);
  1096. a.DoA(2);
  1097. }
  1098. // Tests that any order is allowed when no sequence is used.
  1099. TEST(SequenceTest, AnyOrderIsOkByDefault) {
  1100. {
  1101. MockA a;
  1102. MockB b;
  1103. EXPECT_CALL(a, DoA(1));
  1104. EXPECT_CALL(b, DoB())
  1105. .Times(AnyNumber());
  1106. a.DoA(1);
  1107. b.DoB();
  1108. }
  1109. { // NOLINT
  1110. MockA a;
  1111. MockB b;
  1112. EXPECT_CALL(a, DoA(1));
  1113. EXPECT_CALL(b, DoB())
  1114. .Times(AnyNumber());
  1115. b.DoB();
  1116. a.DoA(1);
  1117. }
  1118. }
  1119. // Tests that the calls must be in strict order when a complete order
  1120. // is specified.
  1121. TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
  1122. MockA a;
  1123. ON_CALL(a, ReturnResult(_))
  1124. .WillByDefault(Return(Result()));
  1125. Sequence s;
  1126. EXPECT_CALL(a, ReturnResult(1))
  1127. .InSequence(s);
  1128. EXPECT_CALL(a, ReturnResult(2))
  1129. .InSequence(s);
  1130. EXPECT_CALL(a, ReturnResult(3))
  1131. .InSequence(s);
  1132. a.ReturnResult(1);
  1133. // May only be called after a.ReturnResult(2).
  1134. EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
  1135. a.ReturnResult(2);
  1136. a.ReturnResult(3);
  1137. }
  1138. // Tests that the calls must be in strict order when a complete order
  1139. // is specified.
  1140. TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
  1141. MockA a;
  1142. ON_CALL(a, ReturnResult(_))
  1143. .WillByDefault(Return(Result()));
  1144. Sequence s;
  1145. EXPECT_CALL(a, ReturnResult(1))
  1146. .InSequence(s);
  1147. EXPECT_CALL(a, ReturnResult(2))
  1148. .InSequence(s);
  1149. // May only be called after a.ReturnResult(1).
  1150. EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
  1151. a.ReturnResult(1);
  1152. a.ReturnResult(2);
  1153. }
  1154. // Tests specifying a DAG using multiple sequences.
  1155. class PartialOrderTest : public testing::Test {
  1156. protected:
  1157. PartialOrderTest() {
  1158. ON_CALL(a_, ReturnResult(_))
  1159. .WillByDefault(Return(Result()));
  1160. // Specifies this partial ordering:
  1161. //
  1162. // a.ReturnResult(1) ==>
  1163. // a.ReturnResult(2) * n ==> a.ReturnResult(3)
  1164. // b.DoB() * 2 ==>
  1165. Sequence x, y;
  1166. EXPECT_CALL(a_, ReturnResult(1))
  1167. .InSequence(x);
  1168. EXPECT_CALL(b_, DoB())
  1169. .Times(2)
  1170. .InSequence(y);
  1171. EXPECT_CALL(a_, ReturnResult(2))
  1172. .Times(AnyNumber())
  1173. .InSequence(x, y);
  1174. EXPECT_CALL(a_, ReturnResult(3))
  1175. .InSequence(x);
  1176. }
  1177. MockA a_;
  1178. MockB b_;
  1179. };
  1180. TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
  1181. a_.ReturnResult(1);
  1182. b_.DoB();
  1183. // May only be called after the second DoB().
  1184. EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
  1185. b_.DoB();
  1186. a_.ReturnResult(3);
  1187. }
  1188. TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
  1189. // May only be called after ReturnResult(1).
  1190. EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
  1191. a_.ReturnResult(1);
  1192. b_.DoB();
  1193. b_.DoB();
  1194. a_.ReturnResult(3);
  1195. }
  1196. TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
  1197. // May only be called last.
  1198. EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
  1199. a_.ReturnResult(1);
  1200. b_.DoB();
  1201. b_.DoB();
  1202. a_.ReturnResult(3);
  1203. }
  1204. TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
  1205. a_.ReturnResult(1);
  1206. b_.DoB();
  1207. b_.DoB();
  1208. a_.ReturnResult(3);
  1209. // May only be called before ReturnResult(3).
  1210. EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
  1211. }
  1212. TEST(SequenceTest, Retirement) {
  1213. MockA a;
  1214. Sequence s;
  1215. EXPECT_CALL(a, DoA(1))
  1216. .InSequence(s);
  1217. EXPECT_CALL(a, DoA(_))
  1218. .InSequence(s)
  1219. .RetiresOnSaturation();
  1220. EXPECT_CALL(a, DoA(1))
  1221. .InSequence(s);
  1222. a.DoA(1);
  1223. a.DoA(2);
  1224. a.DoA(1);
  1225. }
  1226. // Tests Expectation.
  1227. TEST(ExpectationTest, ConstrutorsWork) {
  1228. MockA a;
  1229. Expectation e1; // Default ctor.
  1230. // Ctor from various forms of EXPECT_CALL.
  1231. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1232. Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
  1233. {
  1234. Sequence s;
  1235. Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
  1236. Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
  1237. }
  1238. Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
  1239. Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
  1240. Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
  1241. Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
  1242. Expectation e10 = e2; // Copy ctor.
  1243. EXPECT_THAT(e1, Ne(e2));
  1244. EXPECT_THAT(e2, Eq(e10));
  1245. a.DoA(2);
  1246. a.DoA(3);
  1247. a.DoA(4);
  1248. a.DoA(5);
  1249. a.DoA(6);
  1250. a.DoA(7);
  1251. a.DoA(8);
  1252. a.DoA(9);
  1253. }
  1254. TEST(ExpectationTest, AssignmentWorks) {
  1255. MockA a;
  1256. Expectation e1;
  1257. Expectation e2 = EXPECT_CALL(a, DoA(1));
  1258. EXPECT_THAT(e1, Ne(e2));
  1259. e1 = e2;
  1260. EXPECT_THAT(e1, Eq(e2));
  1261. a.DoA(1);
  1262. }
  1263. // Tests ExpectationSet.
  1264. TEST(ExpectationSetTest, MemberTypesAreCorrect) {
  1265. ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
  1266. }
  1267. TEST(ExpectationSetTest, ConstructorsWork) {
  1268. MockA a;
  1269. Expectation e1;
  1270. const Expectation e2;
  1271. ExpectationSet es1; // Default ctor.
  1272. ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
  1273. ExpectationSet es3 = e1; // Ctor from Expectation.
  1274. ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
  1275. ExpectationSet es5 = e2; // Ctor from const Expectation.
  1276. ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
  1277. ExpectationSet es7 = es2; // Copy ctor.
  1278. EXPECT_EQ(0, es1.size());
  1279. EXPECT_EQ(1, es2.size());
  1280. EXPECT_EQ(1, es3.size());
  1281. EXPECT_EQ(1, es4.size());
  1282. EXPECT_EQ(1, es5.size());
  1283. EXPECT_EQ(1, es6.size());
  1284. EXPECT_EQ(1, es7.size());
  1285. EXPECT_THAT(es3, Ne(es2));
  1286. EXPECT_THAT(es4, Eq(es3));
  1287. EXPECT_THAT(es5, Eq(es4));
  1288. EXPECT_THAT(es6, Eq(es5));
  1289. EXPECT_THAT(es7, Eq(es2));
  1290. a.DoA(1);
  1291. }
  1292. TEST(ExpectationSetTest, AssignmentWorks) {
  1293. ExpectationSet es1;
  1294. ExpectationSet es2 = Expectation();
  1295. es1 = es2;
  1296. EXPECT_EQ(1, es1.size());
  1297. EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
  1298. EXPECT_THAT(es1, Eq(es2));
  1299. }
  1300. TEST(ExpectationSetTest, InsertionWorks) {
  1301. ExpectationSet es1;
  1302. Expectation e1;
  1303. es1 += e1;
  1304. EXPECT_EQ(1, es1.size());
  1305. EXPECT_THAT(*(es1.begin()), Eq(e1));
  1306. MockA a;
  1307. Expectation e2 = EXPECT_CALL(a, DoA(1));
  1308. es1 += e2;
  1309. EXPECT_EQ(2, es1.size());
  1310. ExpectationSet::const_iterator it1 = es1.begin();
  1311. ExpectationSet::const_iterator it2 = it1;
  1312. ++it2;
  1313. EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
  1314. EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
  1315. a.DoA(1);
  1316. }
  1317. TEST(ExpectationSetTest, SizeWorks) {
  1318. ExpectationSet es;
  1319. EXPECT_EQ(0, es.size());
  1320. es += Expectation();
  1321. EXPECT_EQ(1, es.size());
  1322. MockA a;
  1323. es += EXPECT_CALL(a, DoA(1));
  1324. EXPECT_EQ(2, es.size());
  1325. a.DoA(1);
  1326. }
  1327. TEST(ExpectationSetTest, IsEnumerable) {
  1328. ExpectationSet es;
  1329. EXPECT_TRUE(es.begin() == es.end());
  1330. es += Expectation();
  1331. ExpectationSet::const_iterator it = es.begin();
  1332. EXPECT_TRUE(it != es.end());
  1333. EXPECT_THAT(*it, Eq(Expectation()));
  1334. ++it;
  1335. EXPECT_TRUE(it== es.end());
  1336. }
  1337. // Tests the .After() clause.
  1338. TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
  1339. MockA a;
  1340. ExpectationSet es;
  1341. es += EXPECT_CALL(a, DoA(1));
  1342. es += EXPECT_CALL(a, DoA(2));
  1343. EXPECT_CALL(a, DoA(3))
  1344. .After(es);
  1345. a.DoA(1);
  1346. a.DoA(2);
  1347. a.DoA(3);
  1348. }
  1349. TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
  1350. MockA a;
  1351. MockB b;
  1352. // The following also verifies that const Expectation objects work
  1353. // too. Do not remove the const modifiers.
  1354. const Expectation e1 = EXPECT_CALL(a, DoA(1));
  1355. const Expectation e2 = EXPECT_CALL(b, DoB())
  1356. .Times(2)
  1357. .After(e1);
  1358. EXPECT_CALL(a, DoA(2)).After(e2);
  1359. a.DoA(1);
  1360. b.DoB();
  1361. b.DoB();
  1362. a.DoA(2);
  1363. }
  1364. // Calls must be in strict order when specified so using .After().
  1365. TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
  1366. MockA a;
  1367. MockB b;
  1368. // Define ordering:
  1369. // a.DoA(1) ==> b.DoB() ==> a.DoA(2)
  1370. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1371. Expectation e2 = EXPECT_CALL(b, DoB())
  1372. .After(e1);
  1373. EXPECT_CALL(a, DoA(2))
  1374. .After(e2);
  1375. a.DoA(1);
  1376. // May only be called after DoB().
  1377. EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
  1378. b.DoB();
  1379. a.DoA(2);
  1380. }
  1381. // Calls must be in strict order when specified so using .After().
  1382. TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
  1383. MockA a;
  1384. MockB b;
  1385. // Define ordering:
  1386. // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
  1387. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1388. Expectation e2 = EXPECT_CALL(b, DoB())
  1389. .Times(2)
  1390. .After(e1);
  1391. EXPECT_CALL(a, DoA(2))
  1392. .After(e2);
  1393. a.DoA(1);
  1394. b.DoB();
  1395. // May only be called after the second DoB().
  1396. EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
  1397. b.DoB();
  1398. a.DoA(2);
  1399. }
  1400. // Calls must satisfy the partial order when specified so.
  1401. TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
  1402. MockA a;
  1403. ON_CALL(a, ReturnResult(_))
  1404. .WillByDefault(Return(Result()));
  1405. // Define ordering:
  1406. // a.DoA(1) ==>
  1407. // a.DoA(2) ==> a.ReturnResult(3)
  1408. Expectation e = EXPECT_CALL(a, DoA(1));
  1409. const ExpectationSet es = EXPECT_CALL(a, DoA(2));
  1410. EXPECT_CALL(a, ReturnResult(3))
  1411. .After(e, es);
  1412. // May only be called last.
  1413. EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
  1414. a.DoA(2);
  1415. a.DoA(1);
  1416. a.ReturnResult(3);
  1417. }
  1418. // Calls must satisfy the partial order when specified so.
  1419. TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
  1420. MockA a;
  1421. // Define ordering:
  1422. // a.DoA(1) ==>
  1423. // a.DoA(2) ==> a.DoA(3)
  1424. Expectation e = EXPECT_CALL(a, DoA(1));
  1425. const ExpectationSet es = EXPECT_CALL(a, DoA(2));
  1426. EXPECT_CALL(a, DoA(3))
  1427. .After(e, es);
  1428. a.DoA(2);
  1429. // May only be called last.
  1430. EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
  1431. a.DoA(1);
  1432. a.DoA(3);
  1433. }
  1434. // .After() can be combined with .InSequence().
  1435. TEST(AfterTest, CanBeUsedWithInSequence) {
  1436. MockA a;
  1437. Sequence s;
  1438. Expectation e = EXPECT_CALL(a, DoA(1));
  1439. EXPECT_CALL(a, DoA(2)).InSequence(s);
  1440. EXPECT_CALL(a, DoA(3))
  1441. .InSequence(s)
  1442. .After(e);
  1443. a.DoA(1);
  1444. // May only be after DoA(2).
  1445. EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
  1446. a.DoA(2);
  1447. a.DoA(3);
  1448. }
  1449. // .After() can be called multiple times.
  1450. TEST(AfterTest, CanBeCalledManyTimes) {
  1451. MockA a;
  1452. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1453. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1454. Expectation e3 = EXPECT_CALL(a, DoA(3));
  1455. EXPECT_CALL(a, DoA(4))
  1456. .After(e1)
  1457. .After(e2)
  1458. .After(e3);
  1459. a.DoA(3);
  1460. a.DoA(1);
  1461. a.DoA(2);
  1462. a.DoA(4);
  1463. }
  1464. // .After() accepts up to 5 arguments.
  1465. TEST(AfterTest, AcceptsUpToFiveArguments) {
  1466. MockA a;
  1467. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1468. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1469. Expectation e3 = EXPECT_CALL(a, DoA(3));
  1470. ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
  1471. ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
  1472. EXPECT_CALL(a, DoA(6))
  1473. .After(e1, e2, e3, es1, es2);
  1474. a.DoA(5);
  1475. a.DoA(2);
  1476. a.DoA(4);
  1477. a.DoA(1);
  1478. a.DoA(3);
  1479. a.DoA(6);
  1480. }
  1481. // .After() allows input to contain duplicated Expectations.
  1482. TEST(AfterTest, AcceptsDuplicatedInput) {
  1483. MockA a;
  1484. ON_CALL(a, ReturnResult(_))
  1485. .WillByDefault(Return(Result()));
  1486. // Define ordering:
  1487. // DoA(1) ==>
  1488. // DoA(2) ==> ReturnResult(3)
  1489. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1490. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1491. ExpectationSet es;
  1492. es += e1;
  1493. es += e2;
  1494. EXPECT_CALL(a, ReturnResult(3))
  1495. .After(e1, e2, es, e1);
  1496. a.DoA(1);
  1497. // May only be after DoA(2).
  1498. EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
  1499. a.DoA(2);
  1500. a.ReturnResult(3);
  1501. }
  1502. // An Expectation added to an ExpectationSet after it has been used in
  1503. // an .After() has no effect.
  1504. TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
  1505. MockA a;
  1506. ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
  1507. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1508. EXPECT_CALL(a, DoA(3))
  1509. .After(es1);
  1510. es1 += e2;
  1511. a.DoA(1);
  1512. a.DoA(3);
  1513. a.DoA(2);
  1514. }
  1515. // Tests that Google Mock correctly handles calls to mock functions
  1516. // after a mock object owning one of their pre-requisites has died.
  1517. // Tests that calls that satisfy the original spec are successful.
  1518. TEST(DeletingMockEarlyTest, Success1) {
  1519. MockB* const b1 = new MockB;
  1520. MockA* const a = new MockA;
  1521. MockB* const b2 = new MockB;
  1522. {
  1523. InSequence dummy;
  1524. EXPECT_CALL(*b1, DoB(_))
  1525. .WillOnce(Return(1));
  1526. EXPECT_CALL(*a, Binary(_, _))
  1527. .Times(AnyNumber())
  1528. .WillRepeatedly(Return(true));
  1529. EXPECT_CALL(*b2, DoB(_))
  1530. .Times(AnyNumber())
  1531. .WillRepeatedly(Return(2));
  1532. }
  1533. EXPECT_EQ(1, b1->DoB(1));
  1534. delete b1;
  1535. // a's pre-requisite has died.
  1536. EXPECT_TRUE(a->Binary(0, 1));
  1537. delete b2;
  1538. // a's successor has died.
  1539. EXPECT_TRUE(a->Binary(1, 2));
  1540. delete a;
  1541. }
  1542. // Tests that calls that satisfy the original spec are successful.
  1543. TEST(DeletingMockEarlyTest, Success2) {
  1544. MockB* const b1 = new MockB;
  1545. MockA* const a = new MockA;
  1546. MockB* const b2 = new MockB;
  1547. {
  1548. InSequence dummy;
  1549. EXPECT_CALL(*b1, DoB(_))
  1550. .WillOnce(Return(1));
  1551. EXPECT_CALL(*a, Binary(_, _))
  1552. .Times(AnyNumber());
  1553. EXPECT_CALL(*b2, DoB(_))
  1554. .Times(AnyNumber())
  1555. .WillRepeatedly(Return(2));
  1556. }
  1557. delete a; // a is trivially satisfied.
  1558. EXPECT_EQ(1, b1->DoB(1));
  1559. EXPECT_EQ(2, b2->DoB(2));
  1560. delete b1;
  1561. delete b2;
  1562. }
  1563. // Tests that it's OK to delete a mock object itself in its action.
  1564. // Suppresses warning on unreferenced formal parameter in MSVC with
  1565. // -W4.
  1566. #ifdef _MSC_VER
  1567. # pragma warning(push)
  1568. # pragma warning(disable:4100)
  1569. #endif
  1570. ACTION_P(Delete, ptr) { delete ptr; }
  1571. #ifdef _MSC_VER
  1572. # pragma warning(pop)
  1573. #endif
  1574. TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
  1575. MockA* const a = new MockA;
  1576. EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
  1577. a->DoA(42); // This will cause a to be deleted.
  1578. }
  1579. TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
  1580. MockA* const a = new MockA;
  1581. EXPECT_CALL(*a, ReturnResult(_))
  1582. .WillOnce(DoAll(Delete(a), Return(Result())));
  1583. a->ReturnResult(42); // This will cause a to be deleted.
  1584. }
  1585. // Tests that calls that violate the original spec yield failures.
  1586. TEST(DeletingMockEarlyTest, Failure1) {
  1587. MockB* const b1 = new MockB;
  1588. MockA* const a = new MockA;
  1589. MockB* const b2 = new MockB;
  1590. {
  1591. InSequence dummy;
  1592. EXPECT_CALL(*b1, DoB(_))
  1593. .WillOnce(Return(1));
  1594. EXPECT_CALL(*a, Binary(_, _))
  1595. .Times(AnyNumber());
  1596. EXPECT_CALL(*b2, DoB(_))
  1597. .Times(AnyNumber())
  1598. .WillRepeatedly(Return(2));
  1599. }
  1600. delete a; // a is trivially satisfied.
  1601. EXPECT_NONFATAL_FAILURE({
  1602. b2->DoB(2);
  1603. }, "Unexpected mock function call");
  1604. EXPECT_EQ(1, b1->DoB(1));
  1605. delete b1;
  1606. delete b2;
  1607. }
  1608. // Tests that calls that violate the original spec yield failures.
  1609. TEST(DeletingMockEarlyTest, Failure2) {
  1610. MockB* const b1 = new MockB;
  1611. MockA* const a = new MockA;
  1612. MockB* const b2 = new MockB;
  1613. {
  1614. InSequence dummy;
  1615. EXPECT_CALL(*b1, DoB(_));
  1616. EXPECT_CALL(*a, Binary(_, _))
  1617. .Times(AnyNumber());
  1618. EXPECT_CALL(*b2, DoB(_))
  1619. .Times(AnyNumber());
  1620. }
  1621. EXPECT_NONFATAL_FAILURE(delete b1,
  1622. "Actual: never called");
  1623. EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
  1624. "Unexpected mock function call");
  1625. EXPECT_NONFATAL_FAILURE(b2->DoB(1),
  1626. "Unexpected mock function call");
  1627. delete a;
  1628. delete b2;
  1629. }
  1630. class EvenNumberCardinality : public CardinalityInterface {
  1631. public:
  1632. // Returns true if and only if call_count calls will satisfy this
  1633. // cardinality.
  1634. bool IsSatisfiedByCallCount(int call_count) const override {
  1635. return call_count % 2 == 0;
  1636. }
  1637. // Returns true if and only if call_count calls will saturate this
  1638. // cardinality.
  1639. bool IsSaturatedByCallCount(int /* call_count */) const override {
  1640. return false;
  1641. }
  1642. // Describes self to an ostream.
  1643. void DescribeTo(::std::ostream* os) const override {
  1644. *os << "called even number of times";
  1645. }
  1646. };
  1647. Cardinality EvenNumber() {
  1648. return Cardinality(new EvenNumberCardinality);
  1649. }
  1650. TEST(ExpectationBaseTest,
  1651. AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
  1652. MockA* a = new MockA;
  1653. Sequence s;
  1654. EXPECT_CALL(*a, DoA(1))
  1655. .Times(EvenNumber())
  1656. .InSequence(s);
  1657. EXPECT_CALL(*a, DoA(2))
  1658. .Times(AnyNumber())
  1659. .InSequence(s);
  1660. EXPECT_CALL(*a, DoA(3))
  1661. .Times(AnyNumber());
  1662. a->DoA(3);
  1663. a->DoA(1);
  1664. EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
  1665. EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
  1666. }
  1667. // The following tests verify the message generated when a mock
  1668. // function is called.
  1669. struct Printable {
  1670. };
  1671. inline void operator<<(::std::ostream& os, const Printable&) {
  1672. os << "Printable";
  1673. }
  1674. struct Unprintable {
  1675. Unprintable() : value(0) {}
  1676. int value;
  1677. };
  1678. class MockC {
  1679. public:
  1680. MockC() {}
  1681. MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
  1682. const Printable& x, Unprintable y));
  1683. MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
  1684. private:
  1685. GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
  1686. };
  1687. class VerboseFlagPreservingFixture : public testing::Test {
  1688. protected:
  1689. VerboseFlagPreservingFixture()
  1690. : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}
  1691. ~VerboseFlagPreservingFixture() override {
  1692. GMOCK_FLAG_SET(verbose, saved_verbose_flag_);
  1693. }
  1694. private:
  1695. const std::string saved_verbose_flag_;
  1696. GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
  1697. };
  1698. #if GTEST_HAS_STREAM_REDIRECTION
  1699. // Tests that an uninteresting mock function call on a naggy mock
  1700. // generates a warning without the stack trace when
  1701. // --gmock_verbose=warning is specified.
  1702. TEST(FunctionCallMessageTest,
  1703. UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
  1704. GMOCK_FLAG_SET(verbose, kWarningVerbosity);
  1705. NaggyMock<MockC> c;
  1706. CaptureStdout();
  1707. c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
  1708. const std::string output = GetCapturedStdout();
  1709. EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
  1710. EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
  1711. }
  1712. // Tests that an uninteresting mock function call on a naggy mock
  1713. // generates a warning containing the stack trace when
  1714. // --gmock_verbose=info is specified.
  1715. TEST(FunctionCallMessageTest,
  1716. UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
  1717. GMOCK_FLAG_SET(verbose, kInfoVerbosity);
  1718. NaggyMock<MockC> c;
  1719. CaptureStdout();
  1720. c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
  1721. const std::string output = GetCapturedStdout();
  1722. EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
  1723. EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
  1724. # ifndef NDEBUG
  1725. // We check the stack trace content in dbg-mode only, as opt-mode
  1726. // may inline the call we are interested in seeing.
  1727. // Verifies that a void mock function's name appears in the stack
  1728. // trace.
  1729. EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
  1730. // Verifies that a non-void mock function's name appears in the
  1731. // stack trace.
  1732. CaptureStdout();
  1733. c.NonVoidMethod();
  1734. const std::string output2 = GetCapturedStdout();
  1735. EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
  1736. # endif // NDEBUG
  1737. }
  1738. // Tests that an uninteresting mock function call on a naggy mock
  1739. // causes the function arguments and return value to be printed.
  1740. TEST(FunctionCallMessageTest,
  1741. UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
  1742. // A non-void mock function.
  1743. NaggyMock<MockB> b;
  1744. CaptureStdout();
  1745. b.DoB();
  1746. const std::string output1 = GetCapturedStdout();
  1747. EXPECT_PRED_FORMAT2(
  1748. IsSubstring,
  1749. "Uninteresting mock function call - returning default value.\n"
  1750. " Function call: DoB()\n"
  1751. " Returns: 0\n", output1.c_str());
  1752. // Makes sure the return value is printed.
  1753. // A void mock function.
  1754. NaggyMock<MockC> c;
  1755. CaptureStdout();
  1756. c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
  1757. const std::string output2 = GetCapturedStdout();
  1758. EXPECT_THAT(output2.c_str(),
  1759. ContainsRegex(
  1760. "Uninteresting mock function call - returning directly\\.\n"
  1761. " Function call: VoidMethod"
  1762. "\\(false, 5, \"Hi\", NULL, @.+ "
  1763. "Printable, 4-byte object <00-00 00-00>\\)"));
  1764. // A void function has no return value to print.
  1765. }
  1766. // Tests how the --gmock_verbose flag affects Google Mock's output.
  1767. class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
  1768. public:
  1769. // Verifies that the given Google Mock output is correct. (When
  1770. // should_print is true, the output should match the given regex and
  1771. // contain the given function name in the stack trace. When it's
  1772. // false, the output should be empty.)
  1773. void VerifyOutput(const std::string& output, bool should_print,
  1774. const std::string& expected_substring,
  1775. const std::string& function_name) {
  1776. if (should_print) {
  1777. EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
  1778. # ifndef NDEBUG
  1779. // We check the stack trace content in dbg-mode only, as opt-mode
  1780. // may inline the call we are interested in seeing.
  1781. EXPECT_THAT(output.c_str(), HasSubstr(function_name));
  1782. # else
  1783. // Suppresses 'unused function parameter' warnings.
  1784. static_cast<void>(function_name);
  1785. # endif // NDEBUG
  1786. } else {
  1787. EXPECT_STREQ("", output.c_str());
  1788. }
  1789. }
  1790. // Tests how the flag affects expected calls.
  1791. void TestExpectedCall(bool should_print) {
  1792. MockA a;
  1793. EXPECT_CALL(a, DoA(5));
  1794. EXPECT_CALL(a, Binary(_, 1))
  1795. .WillOnce(Return(true));
  1796. // A void-returning function.
  1797. CaptureStdout();
  1798. a.DoA(5);
  1799. VerifyOutput(
  1800. GetCapturedStdout(),
  1801. should_print,
  1802. "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
  1803. " Function call: DoA(5)\n"
  1804. "Stack trace:\n",
  1805. "DoA");
  1806. // A non-void-returning function.
  1807. CaptureStdout();
  1808. a.Binary(2, 1);
  1809. VerifyOutput(
  1810. GetCapturedStdout(),
  1811. should_print,
  1812. "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
  1813. " Function call: Binary(2, 1)\n"
  1814. " Returns: true\n"
  1815. "Stack trace:\n",
  1816. "Binary");
  1817. }
  1818. // Tests how the flag affects uninteresting calls on a naggy mock.
  1819. void TestUninterestingCallOnNaggyMock(bool should_print) {
  1820. NaggyMock<MockA> a;
  1821. const std::string note =
  1822. "NOTE: You can safely ignore the above warning unless this "
  1823. "call should not happen. Do not suppress it by blindly adding "
  1824. "an EXPECT_CALL() if you don't mean to enforce the call. "
  1825. "See "
  1826. "https://github.com/google/googletest/blob/master/docs/"
  1827. "gmock_cook_book.md#"
  1828. "knowing-when-to-expect for details.";
  1829. // A void-returning function.
  1830. CaptureStdout();
  1831. a.DoA(5);
  1832. VerifyOutput(
  1833. GetCapturedStdout(),
  1834. should_print,
  1835. "\nGMOCK WARNING:\n"
  1836. "Uninteresting mock function call - returning directly.\n"
  1837. " Function call: DoA(5)\n" +
  1838. note,
  1839. "DoA");
  1840. // A non-void-returning function.
  1841. CaptureStdout();
  1842. a.Binary(2, 1);
  1843. VerifyOutput(
  1844. GetCapturedStdout(),
  1845. should_print,
  1846. "\nGMOCK WARNING:\n"
  1847. "Uninteresting mock function call - returning default value.\n"
  1848. " Function call: Binary(2, 1)\n"
  1849. " Returns: false\n" +
  1850. note,
  1851. "Binary");
  1852. }
  1853. };
  1854. // Tests that --gmock_verbose=info causes both expected and
  1855. // uninteresting calls to be reported.
  1856. TEST_F(GMockVerboseFlagTest, Info) {
  1857. GMOCK_FLAG_SET(verbose, kInfoVerbosity);
  1858. TestExpectedCall(true);
  1859. TestUninterestingCallOnNaggyMock(true);
  1860. }
  1861. // Tests that --gmock_verbose=warning causes uninteresting calls to be
  1862. // reported.
  1863. TEST_F(GMockVerboseFlagTest, Warning) {
  1864. GMOCK_FLAG_SET(verbose, kWarningVerbosity);
  1865. TestExpectedCall(false);
  1866. TestUninterestingCallOnNaggyMock(true);
  1867. }
  1868. // Tests that --gmock_verbose=warning causes neither expected nor
  1869. // uninteresting calls to be reported.
  1870. TEST_F(GMockVerboseFlagTest, Error) {
  1871. GMOCK_FLAG_SET(verbose, kErrorVerbosity);
  1872. TestExpectedCall(false);
  1873. TestUninterestingCallOnNaggyMock(false);
  1874. }
  1875. // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
  1876. // as --gmock_verbose=warning.
  1877. TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
  1878. GMOCK_FLAG_SET(verbose, "invalid"); // Treated as "warning".
  1879. TestExpectedCall(false);
  1880. TestUninterestingCallOnNaggyMock(true);
  1881. }
  1882. #endif // GTEST_HAS_STREAM_REDIRECTION
  1883. // A helper class that generates a failure when printed. We use it to
  1884. // ensure that Google Mock doesn't print a value (even to an internal
  1885. // buffer) when it is not supposed to do so.
  1886. class PrintMeNot {};
  1887. void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
  1888. ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
  1889. << "printed even to an internal buffer.";
  1890. }
  1891. class LogTestHelper {
  1892. public:
  1893. LogTestHelper() {}
  1894. MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
  1895. private:
  1896. GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
  1897. };
  1898. class GMockLogTest : public VerboseFlagPreservingFixture {
  1899. protected:
  1900. LogTestHelper helper_;
  1901. };
  1902. TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
  1903. GMOCK_FLAG_SET(verbose, kWarningVerbosity);
  1904. EXPECT_CALL(helper_, Foo(_))
  1905. .WillOnce(Return(PrintMeNot()));
  1906. helper_.Foo(PrintMeNot()); // This is an expected call.
  1907. }
  1908. TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
  1909. GMOCK_FLAG_SET(verbose, kErrorVerbosity);
  1910. EXPECT_CALL(helper_, Foo(_))
  1911. .WillOnce(Return(PrintMeNot()));
  1912. helper_.Foo(PrintMeNot()); // This is an expected call.
  1913. }
  1914. TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
  1915. GMOCK_FLAG_SET(verbose, kErrorVerbosity);
  1916. ON_CALL(helper_, Foo(_))
  1917. .WillByDefault(Return(PrintMeNot()));
  1918. helper_.Foo(PrintMeNot()); // This should generate a warning.
  1919. }
  1920. // Tests Mock::AllowLeak().
  1921. TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
  1922. MockA* a = new MockA;
  1923. Mock::AllowLeak(a);
  1924. }
  1925. TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
  1926. MockA* a = new MockA;
  1927. Mock::AllowLeak(a);
  1928. ON_CALL(*a, DoA(_)).WillByDefault(Return());
  1929. a->DoA(0);
  1930. }
  1931. TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
  1932. MockA* a = new MockA;
  1933. ON_CALL(*a, DoA(_)).WillByDefault(Return());
  1934. Mock::AllowLeak(a);
  1935. }
  1936. TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
  1937. MockA* a = new MockA;
  1938. Mock::AllowLeak(a);
  1939. EXPECT_CALL(*a, DoA(_));
  1940. a->DoA(0);
  1941. }
  1942. TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
  1943. MockA* a = new MockA;
  1944. EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
  1945. Mock::AllowLeak(a);
  1946. }
  1947. TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
  1948. MockA* a = new MockA;
  1949. ON_CALL(*a, DoA(_)).WillByDefault(Return());
  1950. EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
  1951. Mock::AllowLeak(a);
  1952. }
  1953. // Tests that we can verify and clear a mock object's expectations
  1954. // when none of its methods has expectations.
  1955. TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
  1956. MockB b;
  1957. ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
  1958. // There should be no expectations on the methods now, so we can
  1959. // freely call them.
  1960. EXPECT_EQ(0, b.DoB());
  1961. EXPECT_EQ(0, b.DoB(1));
  1962. }
  1963. // Tests that we can verify and clear a mock object's expectations
  1964. // when some, but not all, of its methods have expectations *and* the
  1965. // verification succeeds.
  1966. TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
  1967. MockB b;
  1968. EXPECT_CALL(b, DoB())
  1969. .WillOnce(Return(1));
  1970. b.DoB();
  1971. ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
  1972. // There should be no expectations on the methods now, so we can
  1973. // freely call them.
  1974. EXPECT_EQ(0, b.DoB());
  1975. EXPECT_EQ(0, b.DoB(1));
  1976. }
  1977. // Tests that we can verify and clear a mock object's expectations
  1978. // when some, but not all, of its methods have expectations *and* the
  1979. // verification fails.
  1980. TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
  1981. MockB b;
  1982. EXPECT_CALL(b, DoB())
  1983. .WillOnce(Return(1));
  1984. bool result = true;
  1985. EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
  1986. "Actual: never called");
  1987. ASSERT_FALSE(result);
  1988. // There should be no expectations on the methods now, so we can
  1989. // freely call them.
  1990. EXPECT_EQ(0, b.DoB());
  1991. EXPECT_EQ(0, b.DoB(1));
  1992. }
  1993. // Tests that we can verify and clear a mock object's expectations
  1994. // when all of its methods have expectations.
  1995. TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
  1996. MockB b;
  1997. EXPECT_CALL(b, DoB())
  1998. .WillOnce(Return(1));
  1999. EXPECT_CALL(b, DoB(_))
  2000. .WillOnce(Return(2));
  2001. b.DoB();
  2002. b.DoB(1);
  2003. ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
  2004. // There should be no expectations on the methods now, so we can
  2005. // freely call them.
  2006. EXPECT_EQ(0, b.DoB());
  2007. EXPECT_EQ(0, b.DoB(1));
  2008. }
  2009. // Tests that we can verify and clear a mock object's expectations
  2010. // when a method has more than one expectation.
  2011. TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
  2012. MockB b;
  2013. EXPECT_CALL(b, DoB(0))
  2014. .WillOnce(Return(1));
  2015. EXPECT_CALL(b, DoB(_))
  2016. .WillOnce(Return(2));
  2017. b.DoB(1);
  2018. bool result = true;
  2019. EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
  2020. "Actual: never called");
  2021. ASSERT_FALSE(result);
  2022. // There should be no expectations on the methods now, so we can
  2023. // freely call them.
  2024. EXPECT_EQ(0, b.DoB());
  2025. EXPECT_EQ(0, b.DoB(1));
  2026. }
  2027. // Tests that we can call VerifyAndClearExpectations() on the same
  2028. // mock object multiple times.
  2029. TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
  2030. MockB b;
  2031. EXPECT_CALL(b, DoB());
  2032. b.DoB();
  2033. Mock::VerifyAndClearExpectations(&b);
  2034. EXPECT_CALL(b, DoB(_))
  2035. .WillOnce(Return(1));
  2036. b.DoB(1);
  2037. Mock::VerifyAndClearExpectations(&b);
  2038. Mock::VerifyAndClearExpectations(&b);
  2039. // There should be no expectations on the methods now, so we can
  2040. // freely call them.
  2041. EXPECT_EQ(0, b.DoB());
  2042. EXPECT_EQ(0, b.DoB(1));
  2043. }
  2044. // Tests that we can clear a mock object's default actions when none
  2045. // of its methods has default actions.
  2046. TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
  2047. MockB b;
  2048. // If this crashes or generates a failure, the test will catch it.
  2049. Mock::VerifyAndClear(&b);
  2050. EXPECT_EQ(0, b.DoB());
  2051. }
  2052. // Tests that we can clear a mock object's default actions when some,
  2053. // but not all of its methods have default actions.
  2054. TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
  2055. MockB b;
  2056. ON_CALL(b, DoB())
  2057. .WillByDefault(Return(1));
  2058. Mock::VerifyAndClear(&b);
  2059. // Verifies that the default action of int DoB() was removed.
  2060. EXPECT_EQ(0, b.DoB());
  2061. }
  2062. // Tests that we can clear a mock object's default actions when all of
  2063. // its methods have default actions.
  2064. TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
  2065. MockB b;
  2066. ON_CALL(b, DoB())
  2067. .WillByDefault(Return(1));
  2068. ON_CALL(b, DoB(_))
  2069. .WillByDefault(Return(2));
  2070. Mock::VerifyAndClear(&b);
  2071. // Verifies that the default action of int DoB() was removed.
  2072. EXPECT_EQ(0, b.DoB());
  2073. // Verifies that the default action of int DoB(int) was removed.
  2074. EXPECT_EQ(0, b.DoB(0));
  2075. }
  2076. // Tests that we can clear a mock object's default actions when a
  2077. // method has more than one ON_CALL() set on it.
  2078. TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
  2079. MockB b;
  2080. ON_CALL(b, DoB(0))
  2081. .WillByDefault(Return(1));
  2082. ON_CALL(b, DoB(_))
  2083. .WillByDefault(Return(2));
  2084. Mock::VerifyAndClear(&b);
  2085. // Verifies that the default actions (there are two) of int DoB(int)
  2086. // were removed.
  2087. EXPECT_EQ(0, b.DoB(0));
  2088. EXPECT_EQ(0, b.DoB(1));
  2089. }
  2090. // Tests that we can call VerifyAndClear() on a mock object multiple
  2091. // times.
  2092. TEST(VerifyAndClearTest, CanCallManyTimes) {
  2093. MockB b;
  2094. ON_CALL(b, DoB())
  2095. .WillByDefault(Return(1));
  2096. Mock::VerifyAndClear(&b);
  2097. Mock::VerifyAndClear(&b);
  2098. ON_CALL(b, DoB(_))
  2099. .WillByDefault(Return(1));
  2100. Mock::VerifyAndClear(&b);
  2101. EXPECT_EQ(0, b.DoB());
  2102. EXPECT_EQ(0, b.DoB(1));
  2103. }
  2104. // Tests that VerifyAndClear() works when the verification succeeds.
  2105. TEST(VerifyAndClearTest, Success) {
  2106. MockB b;
  2107. ON_CALL(b, DoB())
  2108. .WillByDefault(Return(1));
  2109. EXPECT_CALL(b, DoB(1))
  2110. .WillOnce(Return(2));
  2111. b.DoB();
  2112. b.DoB(1);
  2113. ASSERT_TRUE(Mock::VerifyAndClear(&b));
  2114. // There should be no expectations on the methods now, so we can
  2115. // freely call them.
  2116. EXPECT_EQ(0, b.DoB());
  2117. EXPECT_EQ(0, b.DoB(1));
  2118. }
  2119. // Tests that VerifyAndClear() works when the verification fails.
  2120. TEST(VerifyAndClearTest, Failure) {
  2121. MockB b;
  2122. ON_CALL(b, DoB(_))
  2123. .WillByDefault(Return(1));
  2124. EXPECT_CALL(b, DoB())
  2125. .WillOnce(Return(2));
  2126. b.DoB(1);
  2127. bool result = true;
  2128. EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
  2129. "Actual: never called");
  2130. ASSERT_FALSE(result);
  2131. // There should be no expectations on the methods now, so we can
  2132. // freely call them.
  2133. EXPECT_EQ(0, b.DoB());
  2134. EXPECT_EQ(0, b.DoB(1));
  2135. }
  2136. // Tests that VerifyAndClear() works when the default actions and
  2137. // expectations are set on a const mock object.
  2138. TEST(VerifyAndClearTest, Const) {
  2139. MockB b;
  2140. ON_CALL(Const(b), DoB())
  2141. .WillByDefault(Return(1));
  2142. EXPECT_CALL(Const(b), DoB())
  2143. .WillOnce(DoDefault())
  2144. .WillOnce(Return(2));
  2145. b.DoB();
  2146. b.DoB();
  2147. ASSERT_TRUE(Mock::VerifyAndClear(&b));
  2148. // There should be no expectations on the methods now, so we can
  2149. // freely call them.
  2150. EXPECT_EQ(0, b.DoB());
  2151. EXPECT_EQ(0, b.DoB(1));
  2152. }
  2153. // Tests that we can set default actions and expectations on a mock
  2154. // object after VerifyAndClear() has been called on it.
  2155. TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
  2156. MockB b;
  2157. ON_CALL(b, DoB())
  2158. .WillByDefault(Return(1));
  2159. EXPECT_CALL(b, DoB(_))
  2160. .WillOnce(Return(2));
  2161. b.DoB(1);
  2162. Mock::VerifyAndClear(&b);
  2163. EXPECT_CALL(b, DoB())
  2164. .WillOnce(Return(3));
  2165. ON_CALL(b, DoB(_))
  2166. .WillByDefault(Return(4));
  2167. EXPECT_EQ(3, b.DoB());
  2168. EXPECT_EQ(4, b.DoB(1));
  2169. }
  2170. // Tests that calling VerifyAndClear() on one mock object does not
  2171. // affect other mock objects (either of the same type or not).
  2172. TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
  2173. MockA a;
  2174. MockB b1;
  2175. MockB b2;
  2176. ON_CALL(a, Binary(_, _))
  2177. .WillByDefault(Return(true));
  2178. EXPECT_CALL(a, Binary(_, _))
  2179. .WillOnce(DoDefault())
  2180. .WillOnce(Return(false));
  2181. ON_CALL(b1, DoB())
  2182. .WillByDefault(Return(1));
  2183. EXPECT_CALL(b1, DoB(_))
  2184. .WillOnce(Return(2));
  2185. ON_CALL(b2, DoB())
  2186. .WillByDefault(Return(3));
  2187. EXPECT_CALL(b2, DoB(_));
  2188. b2.DoB(0);
  2189. Mock::VerifyAndClear(&b2);
  2190. // Verifies that the default actions and expectations of a and b1
  2191. // are still in effect.
  2192. EXPECT_TRUE(a.Binary(0, 0));
  2193. EXPECT_FALSE(a.Binary(0, 0));
  2194. EXPECT_EQ(1, b1.DoB());
  2195. EXPECT_EQ(2, b1.DoB(0));
  2196. }
  2197. TEST(VerifyAndClearTest,
  2198. DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
  2199. std::shared_ptr<MockA> a(new MockA);
  2200. ReferenceHoldingMock test_mock;
  2201. // EXPECT_CALL stores a reference to a inside test_mock.
  2202. EXPECT_CALL(test_mock, AcceptReference(_))
  2203. .WillRepeatedly(SetArgPointee<0>(a));
  2204. // Throw away the reference to the mock that we have in a. After this, the
  2205. // only reference to it is stored by test_mock.
  2206. a.reset();
  2207. // When test_mock goes out of scope, it destroys the last remaining reference
  2208. // to the mock object originally pointed to by a. This will cause the MockA
  2209. // destructor to be called from inside the ReferenceHoldingMock destructor.
  2210. // The state of all mocks is protected by a single global lock, but there
  2211. // should be no deadlock.
  2212. }
  2213. TEST(VerifyAndClearTest,
  2214. DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
  2215. std::shared_ptr<MockA> a(new MockA);
  2216. ReferenceHoldingMock test_mock;
  2217. // ON_CALL stores a reference to a inside test_mock.
  2218. ON_CALL(test_mock, AcceptReference(_))
  2219. .WillByDefault(SetArgPointee<0>(a));
  2220. // Throw away the reference to the mock that we have in a. After this, the
  2221. // only reference to it is stored by test_mock.
  2222. a.reset();
  2223. // When test_mock goes out of scope, it destroys the last remaining reference
  2224. // to the mock object originally pointed to by a. This will cause the MockA
  2225. // destructor to be called from inside the ReferenceHoldingMock destructor.
  2226. // The state of all mocks is protected by a single global lock, but there
  2227. // should be no deadlock.
  2228. }
  2229. // Tests that a mock function's action can call a mock function
  2230. // (either the same function or a different one) either as an explicit
  2231. // action or as a default action without causing a dead lock. It
  2232. // verifies that the action is not performed inside the critical
  2233. // section.
  2234. TEST(SynchronizationTest, CanCallMockMethodInAction) {
  2235. MockA a;
  2236. MockC c;
  2237. ON_CALL(a, DoA(_))
  2238. .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
  2239. &MockC::NonVoidMethod)));
  2240. EXPECT_CALL(a, DoA(1));
  2241. EXPECT_CALL(a, DoA(1))
  2242. .WillOnce(Invoke(&a, &MockA::DoA))
  2243. .RetiresOnSaturation();
  2244. EXPECT_CALL(c, NonVoidMethod());
  2245. a.DoA(1);
  2246. // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
  2247. // which will in turn match the first EXPECT_CALL() and trigger a call to
  2248. // c.NonVoidMethod() that was specified by the ON_CALL() since the first
  2249. // EXPECT_CALL() did not specify an action.
  2250. }
  2251. TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
  2252. MockA a;
  2253. int do_a_arg0 = 0;
  2254. ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
  2255. int do_a_47_arg0 = 0;
  2256. ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
  2257. a.DoA(17);
  2258. EXPECT_THAT(do_a_arg0, 17);
  2259. EXPECT_THAT(do_a_47_arg0, 0);
  2260. a.DoA(47);
  2261. EXPECT_THAT(do_a_arg0, 17);
  2262. EXPECT_THAT(do_a_47_arg0, 47);
  2263. ON_CALL(a, Binary).WillByDefault(Return(true));
  2264. ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
  2265. EXPECT_THAT(a.Binary(14, 17), true);
  2266. EXPECT_THAT(a.Binary(17, 14), false);
  2267. }
  2268. TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
  2269. MockB b;
  2270. ON_CALL(b, DoB()).WillByDefault(Return(9));
  2271. ON_CALL(b, DoB(5)).WillByDefault(Return(11));
  2272. EXPECT_THAT(b.DoB(), 9);
  2273. EXPECT_THAT(b.DoB(1), 0); // default value
  2274. EXPECT_THAT(b.DoB(5), 11);
  2275. }
  2276. struct MockWithConstMethods {
  2277. public:
  2278. MOCK_CONST_METHOD1(Foo, int(int));
  2279. MOCK_CONST_METHOD2(Bar, int(int, const char*));
  2280. };
  2281. TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
  2282. MockWithConstMethods mock;
  2283. ON_CALL(mock, Foo).WillByDefault(Return(7));
  2284. ON_CALL(mock, Bar).WillByDefault(Return(33));
  2285. EXPECT_THAT(mock.Foo(17), 7);
  2286. EXPECT_THAT(mock.Bar(27, "purple"), 33);
  2287. }
  2288. class MockConstOverload {
  2289. public:
  2290. MOCK_METHOD1(Overloaded, int(int));
  2291. MOCK_CONST_METHOD1(Overloaded, int(int));
  2292. };
  2293. TEST(ParameterlessExpectationsTest,
  2294. CanSetExpectationsForConstOverloadedMethods) {
  2295. MockConstOverload mock;
  2296. ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
  2297. ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
  2298. ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
  2299. ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
  2300. EXPECT_THAT(mock.Overloaded(1), 7);
  2301. EXPECT_THAT(mock.Overloaded(5), 9);
  2302. EXPECT_THAT(mock.Overloaded(7), 7);
  2303. const MockConstOverload& const_mock = mock;
  2304. EXPECT_THAT(const_mock.Overloaded(1), 0);
  2305. EXPECT_THAT(const_mock.Overloaded(5), 11);
  2306. EXPECT_THAT(const_mock.Overloaded(7), 13);
  2307. }
  2308. } // namespace
  2309. // Allows the user to define their own main and then invoke gmock_main
  2310. // from it. This might be necessary on some platforms which require
  2311. // specific setup and teardown.
  2312. #if GMOCK_RENAME_MAIN
  2313. int gmock_main(int argc, char **argv) {
  2314. #else
  2315. int main(int argc, char **argv) {
  2316. #endif // GMOCK_RENAME_MAIN
  2317. testing::InitGoogleMock(&argc, argv);
  2318. // Ensures that the tests pass no matter what value of
  2319. // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
  2320. GMOCK_FLAG_SET(catch_leaked_mocks, true);
  2321. GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);
  2322. return RUN_ALL_TESTS();
  2323. }