gmock-spec-builders_test.cc 73 KB

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