gmock-spec-builders_test.cc 73 KB

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