gmock-spec-builders_test.cc 73 KB

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