gmock-spec-builders_test.cc 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599
  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() = default;
  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() = default;
  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() = default;
  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() = default;
  121. virtual int Method() = 0;
  122. };
  123. class MockCC : public CC {
  124. public:
  125. MockCC() = default;
  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. // TODO(b/396121064) - Fix this test under MSVC
  653. #ifndef _MSC_VER
  654. // It should be possible to return a non-moveable type from a mock action in
  655. // C++17 and above, where it's guaranteed that such a type can be initialized
  656. // from a prvalue returned from a function.
  657. TEST(ExpectCallTest, NonMoveableType) {
  658. // Define a non-moveable result type.
  659. struct NonMoveableStruct {
  660. explicit NonMoveableStruct(int x_in) : x(x_in) {}
  661. NonMoveableStruct(NonMoveableStruct&&) = delete;
  662. int x;
  663. };
  664. static_assert(!std::is_move_constructible_v<NonMoveableStruct>);
  665. static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);
  666. static_assert(!std::is_move_assignable_v<NonMoveableStruct>);
  667. static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);
  668. // We should be able to use a callable that returns that result as both a
  669. // OnceAction and an Action, whether the callable ignores arguments or not.
  670. const auto return_17 = [] { return NonMoveableStruct(17); };
  671. static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});
  672. static_cast<void>(Action<NonMoveableStruct()>{return_17});
  673. static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});
  674. static_cast<void>(Action<NonMoveableStruct(int)>{return_17});
  675. // It should be possible to return the result end to end through an
  676. // EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
  677. MockFunction<NonMoveableStruct()> mock;
  678. EXPECT_CALL(mock, Call) //
  679. .WillOnce(return_17) //
  680. .WillRepeatedly(return_17);
  681. EXPECT_EQ(17, mock.AsStdFunction()().x);
  682. EXPECT_EQ(17, mock.AsStdFunction()().x);
  683. EXPECT_EQ(17, mock.AsStdFunction()().x);
  684. }
  685. #endif // _MSC_VER
  686. // Tests that the n-th action is taken for the n-th matching
  687. // invocation.
  688. TEST(ExpectCallTest, NthMatchTakesNthAction) {
  689. MockB b;
  690. EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(
  691. Return(3));
  692. EXPECT_EQ(1, b.DoB());
  693. EXPECT_EQ(2, b.DoB());
  694. EXPECT_EQ(3, b.DoB());
  695. }
  696. // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
  697. // list is exhausted.
  698. TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
  699. MockB b;
  700. EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
  701. EXPECT_EQ(1, b.DoB());
  702. EXPECT_EQ(2, b.DoB());
  703. EXPECT_EQ(2, b.DoB());
  704. }
  705. #if GTEST_HAS_STREAM_REDIRECTION
  706. // Tests that the default action is taken when the WillOnce(...) list is
  707. // exhausted and there is no WillRepeatedly().
  708. TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
  709. MockB b;
  710. EXPECT_CALL(b, DoB(_)).Times(1);
  711. EXPECT_CALL(b, DoB())
  712. .Times(AnyNumber())
  713. .WillOnce(Return(1))
  714. .WillOnce(Return(2));
  715. CaptureStdout();
  716. EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
  717. // expectation has no action clause at all.
  718. EXPECT_EQ(1, b.DoB());
  719. EXPECT_EQ(2, b.DoB());
  720. const std::string output1 = GetCapturedStdout();
  721. EXPECT_STREQ("", output1.c_str());
  722. CaptureStdout();
  723. EXPECT_EQ(0, b.DoB());
  724. EXPECT_EQ(0, b.DoB());
  725. const std::string output2 = GetCapturedStdout();
  726. EXPECT_THAT(output2.c_str(),
  727. HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
  728. "Called 3 times, but only 2 WillOnce()s are specified"
  729. " - returning default value."));
  730. EXPECT_THAT(output2.c_str(),
  731. HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
  732. "Called 4 times, but only 2 WillOnce()s are specified"
  733. " - returning default value."));
  734. }
  735. TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) {
  736. MockB b;
  737. std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
  738. EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
  739. EXPECT_EQ(1, b.DoB());
  740. CaptureStdout();
  741. EXPECT_EQ(0, b.DoB());
  742. const std::string output = GetCapturedStdout();
  743. // The warning message should contain the call location.
  744. EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
  745. }
  746. TEST(FunctionMockerMessageTest,
  747. ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
  748. std::string on_call_location;
  749. CaptureStdout();
  750. {
  751. NaggyMock<MockB> b;
  752. on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
  753. ON_CALL(b, DoB(_)).WillByDefault(Return(0));
  754. b.DoB(0);
  755. }
  756. EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
  757. }
  758. #endif // GTEST_HAS_STREAM_REDIRECTION
  759. // Tests that an uninteresting call performs the default action.
  760. TEST(UninterestingCallTest, DoesDefaultAction) {
  761. // When there is an ON_CALL() statement, the action specified by it
  762. // should be taken.
  763. MockA a;
  764. ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
  765. EXPECT_TRUE(a.Binary(1, 2));
  766. // When there is no ON_CALL(), the default value for the return type
  767. // should be returned.
  768. MockB b;
  769. EXPECT_EQ(0, b.DoB());
  770. }
  771. // Tests that an unexpected call performs the default action.
  772. TEST(UnexpectedCallTest, DoesDefaultAction) {
  773. // When there is an ON_CALL() statement, the action specified by it
  774. // should be taken.
  775. MockA a;
  776. ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
  777. EXPECT_CALL(a, Binary(0, 0));
  778. a.Binary(0, 0);
  779. bool result = false;
  780. EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
  781. "Unexpected mock function call");
  782. EXPECT_TRUE(result);
  783. // When there is no ON_CALL(), the default value for the return type
  784. // should be returned.
  785. MockB b;
  786. EXPECT_CALL(b, DoB(0)).Times(0);
  787. int n = -1;
  788. EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call");
  789. EXPECT_EQ(0, n);
  790. }
  791. // Tests that when an unexpected void function generates the right
  792. // failure message.
  793. TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
  794. // First, tests the message when there is only one EXPECT_CALL().
  795. MockA a1;
  796. EXPECT_CALL(a1, DoA(1));
  797. a1.DoA(1);
  798. // Ideally we should match the failure message against a regex, but
  799. // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
  800. // multiple sub-strings instead.
  801. EXPECT_NONFATAL_FAILURE(
  802. a1.DoA(9),
  803. "Unexpected mock function call - returning directly.\n"
  804. " Function call: DoA(9)\n"
  805. "Google Mock tried the following 1 expectation, but it didn't match:");
  806. EXPECT_NONFATAL_FAILURE(
  807. a1.DoA(9),
  808. " Expected arg #0: is equal to 1\n"
  809. " Actual: 9\n"
  810. " Expected: to be called once\n"
  811. " Actual: called once - saturated and active");
  812. // Next, tests the message when there are more than one EXPECT_CALL().
  813. MockA a2;
  814. EXPECT_CALL(a2, DoA(1));
  815. EXPECT_CALL(a2, DoA(3));
  816. a2.DoA(1);
  817. EXPECT_NONFATAL_FAILURE(
  818. a2.DoA(2),
  819. "Unexpected mock function call - returning directly.\n"
  820. " Function call: DoA(2)\n"
  821. "Google Mock tried the following 2 expectations, but none matched:");
  822. EXPECT_NONFATAL_FAILURE(
  823. a2.DoA(2),
  824. "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
  825. " Expected arg #0: is equal to 1\n"
  826. " Actual: 2\n"
  827. " Expected: to be called once\n"
  828. " Actual: called once - saturated and active");
  829. EXPECT_NONFATAL_FAILURE(
  830. a2.DoA(2),
  831. "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
  832. " Expected arg #0: is equal to 3\n"
  833. " Actual: 2\n"
  834. " Expected: to be called once\n"
  835. " Actual: never called - unsatisfied and active");
  836. a2.DoA(3);
  837. }
  838. // Tests that an unexpected non-void function generates the right
  839. // failure message.
  840. TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
  841. MockB b1;
  842. EXPECT_CALL(b1, DoB(1));
  843. b1.DoB(1);
  844. EXPECT_NONFATAL_FAILURE(
  845. b1.DoB(2),
  846. "Unexpected mock function call - returning default value.\n"
  847. " Function call: DoB(2)\n"
  848. " Returns: 0\n"
  849. "Google Mock tried the following 1 expectation, but it didn't match:");
  850. EXPECT_NONFATAL_FAILURE(
  851. b1.DoB(2),
  852. " Expected arg #0: is equal to 1\n"
  853. " Actual: 2\n"
  854. " Expected: to be called once\n"
  855. " Actual: called once - saturated and active");
  856. }
  857. // Tests that Google Mock explains that an retired expectation doesn't
  858. // match the call.
  859. TEST(UnexpectedCallTest, RetiredExpectation) {
  860. MockB b;
  861. EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();
  862. b.DoB(1);
  863. EXPECT_NONFATAL_FAILURE(b.DoB(1),
  864. " Expected: the expectation is active\n"
  865. " Actual: it is retired");
  866. }
  867. // Tests that Google Mock explains that an expectation that doesn't
  868. // match the arguments doesn't match the call.
  869. TEST(UnexpectedCallTest, UnmatchedArguments) {
  870. MockB b;
  871. EXPECT_CALL(b, DoB(1));
  872. EXPECT_NONFATAL_FAILURE(b.DoB(2),
  873. " Expected arg #0: is equal to 1\n"
  874. " Actual: 2\n");
  875. b.DoB(1);
  876. }
  877. // Tests that Google Mock explains that an expectation with
  878. // unsatisfied pre-requisites doesn't match the call.
  879. TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
  880. Sequence s1, s2;
  881. MockB b;
  882. EXPECT_CALL(b, DoB(1)).InSequence(s1);
  883. EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);
  884. EXPECT_CALL(b, DoB(3)).InSequence(s2);
  885. EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);
  886. ::testing::TestPartResultArray failures;
  887. {
  888. ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
  889. b.DoB(4);
  890. // Now 'failures' contains the Google Test failures generated by
  891. // the above statement.
  892. }
  893. // There should be one non-fatal failure.
  894. ASSERT_EQ(1, failures.size());
  895. const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
  896. EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
  897. // Verifies that the failure message contains the two unsatisfied
  898. // pre-requisites but not the satisfied one.
  899. #ifdef GTEST_USES_POSIX_RE
  900. EXPECT_THAT(r.message(),
  901. ContainsRegex(
  902. // POSIX RE doesn't understand the (?s) prefix, but has no
  903. // trouble with (.|\n).
  904. "the following immediate pre-requisites are not satisfied:\n"
  905. "(.|\n)*: pre-requisite #0\n"
  906. "(.|\n)*: pre-requisite #1"));
  907. #else
  908. // We can only use Google Test's own simple regex.
  909. EXPECT_THAT(r.message(),
  910. ContainsRegex(
  911. "the following immediate pre-requisites are not satisfied:"));
  912. EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
  913. EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
  914. #endif // GTEST_USES_POSIX_RE
  915. b.DoB(1);
  916. b.DoB(3);
  917. b.DoB(4);
  918. }
  919. TEST(UndefinedReturnValueTest,
  920. ReturnValueIsMandatoryWhenNotDefaultConstructible) {
  921. MockA a;
  922. // FIXME: We should really verify the output message,
  923. // but we cannot yet due to that EXPECT_DEATH only captures stderr
  924. // while Google Mock logs to stdout.
  925. #if GTEST_HAS_EXCEPTIONS
  926. EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
  927. #else
  928. EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
  929. #endif
  930. }
  931. // Tests that an excessive call (one whose arguments match the
  932. // matchers but is called too many times) performs the default action.
  933. TEST(ExcessiveCallTest, DoesDefaultAction) {
  934. // When there is an ON_CALL() statement, the action specified by it
  935. // should be taken.
  936. MockA a;
  937. ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
  938. EXPECT_CALL(a, Binary(0, 0));
  939. a.Binary(0, 0);
  940. bool result = false;
  941. EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
  942. "Mock function called more times than expected");
  943. EXPECT_TRUE(result);
  944. // When there is no ON_CALL(), the default value for the return type
  945. // should be returned.
  946. MockB b;
  947. EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0);
  948. int n = -1;
  949. EXPECT_NONFATAL_FAILURE(
  950. n = b.DoB(0),
  951. "Mock function \"DoB Method\" called more times than expected");
  952. EXPECT_EQ(0, n);
  953. }
  954. // Tests that when a void function is called too many times,
  955. // the failure message contains the argument values.
  956. TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
  957. MockA a;
  958. EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0);
  959. EXPECT_NONFATAL_FAILURE(
  960. a.DoA(9),
  961. "Mock function \"DoA Method\" called more times than expected - "
  962. "returning directly.\n"
  963. " Function call: DoA(9)\n"
  964. " Expected: to be never called\n"
  965. " Actual: called once - over-saturated and active");
  966. }
  967. // Tests that when a non-void function is called too many times, the
  968. // failure message contains the argument values and the return value.
  969. TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
  970. MockB b;
  971. EXPECT_CALL(b, DoB(_));
  972. b.DoB(1);
  973. EXPECT_NONFATAL_FAILURE(
  974. b.DoB(2),
  975. "Mock function called more times than expected - "
  976. "returning default value.\n"
  977. " Function call: DoB(2)\n"
  978. " Returns: 0\n"
  979. " Expected: to be called once\n"
  980. " Actual: called twice - over-saturated and active");
  981. }
  982. // Tests using sequences.
  983. TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
  984. MockA a;
  985. {
  986. InSequence dummy;
  987. EXPECT_CALL(a, DoA(1));
  988. EXPECT_CALL(a, DoA(2));
  989. }
  990. EXPECT_NONFATAL_FAILURE(
  991. { // NOLINT
  992. a.DoA(2);
  993. },
  994. "Unexpected mock function call");
  995. a.DoA(1);
  996. a.DoA(2);
  997. }
  998. TEST(InSequenceTest, NestedInSequence) {
  999. MockA a;
  1000. {
  1001. InSequence dummy;
  1002. EXPECT_CALL(a, DoA(1));
  1003. {
  1004. InSequence dummy2;
  1005. EXPECT_CALL(a, DoA(2));
  1006. EXPECT_CALL(a, DoA(3));
  1007. }
  1008. }
  1009. EXPECT_NONFATAL_FAILURE(
  1010. { // NOLINT
  1011. a.DoA(1);
  1012. a.DoA(3);
  1013. },
  1014. "Unexpected mock function call");
  1015. a.DoA(2);
  1016. a.DoA(3);
  1017. }
  1018. TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
  1019. MockA a;
  1020. {
  1021. InSequence dummy;
  1022. EXPECT_CALL(a, DoA(1));
  1023. EXPECT_CALL(a, DoA(2));
  1024. }
  1025. EXPECT_CALL(a, DoA(3));
  1026. EXPECT_NONFATAL_FAILURE(
  1027. { // NOLINT
  1028. a.DoA(2);
  1029. },
  1030. "Unexpected mock function call");
  1031. a.DoA(3);
  1032. a.DoA(1);
  1033. a.DoA(2);
  1034. }
  1035. // Tests that any order is allowed when no sequence is used.
  1036. TEST(SequenceTest, AnyOrderIsOkByDefault) {
  1037. {
  1038. MockA a;
  1039. MockB b;
  1040. EXPECT_CALL(a, DoA(1));
  1041. EXPECT_CALL(b, DoB()).Times(AnyNumber());
  1042. a.DoA(1);
  1043. b.DoB();
  1044. }
  1045. { // NOLINT
  1046. MockA a;
  1047. MockB b;
  1048. EXPECT_CALL(a, DoA(1));
  1049. EXPECT_CALL(b, DoB()).Times(AnyNumber());
  1050. b.DoB();
  1051. a.DoA(1);
  1052. }
  1053. }
  1054. // Tests that the calls must be in strict order when a complete order
  1055. // is specified.
  1056. TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
  1057. MockA a;
  1058. ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
  1059. Sequence s;
  1060. EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
  1061. EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
  1062. EXPECT_CALL(a, ReturnResult(3)).InSequence(s);
  1063. a.ReturnResult(1);
  1064. // May only be called after a.ReturnResult(2).
  1065. EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
  1066. a.ReturnResult(2);
  1067. a.ReturnResult(3);
  1068. }
  1069. // Tests that the calls must be in strict order when a complete order
  1070. // is specified.
  1071. TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
  1072. MockA a;
  1073. ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
  1074. Sequence s;
  1075. EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
  1076. EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
  1077. // May only be called after a.ReturnResult(1).
  1078. EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
  1079. a.ReturnResult(1);
  1080. a.ReturnResult(2);
  1081. }
  1082. // Tests specifying a DAG using multiple sequences.
  1083. class PartialOrderTest : public testing::Test {
  1084. protected:
  1085. PartialOrderTest() {
  1086. ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result()));
  1087. // Specifies this partial ordering:
  1088. //
  1089. // a.ReturnResult(1) ==>
  1090. // a.ReturnResult(2) * n ==> a.ReturnResult(3)
  1091. // b.DoB() * 2 ==>
  1092. Sequence x, y;
  1093. EXPECT_CALL(a_, ReturnResult(1)).InSequence(x);
  1094. EXPECT_CALL(b_, DoB()).Times(2).InSequence(y);
  1095. EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y);
  1096. EXPECT_CALL(a_, ReturnResult(3)).InSequence(x);
  1097. }
  1098. MockA a_;
  1099. MockB b_;
  1100. };
  1101. TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
  1102. a_.ReturnResult(1);
  1103. b_.DoB();
  1104. // May only be called after the second DoB().
  1105. EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
  1106. b_.DoB();
  1107. a_.ReturnResult(3);
  1108. }
  1109. TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
  1110. // May only be called after ReturnResult(1).
  1111. EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
  1112. a_.ReturnResult(1);
  1113. b_.DoB();
  1114. b_.DoB();
  1115. a_.ReturnResult(3);
  1116. }
  1117. TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
  1118. // May only be called last.
  1119. EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
  1120. a_.ReturnResult(1);
  1121. b_.DoB();
  1122. b_.DoB();
  1123. a_.ReturnResult(3);
  1124. }
  1125. TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
  1126. a_.ReturnResult(1);
  1127. b_.DoB();
  1128. b_.DoB();
  1129. a_.ReturnResult(3);
  1130. // May only be called before ReturnResult(3).
  1131. EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
  1132. }
  1133. TEST(SequenceTest, Retirement) {
  1134. MockA a;
  1135. Sequence s;
  1136. EXPECT_CALL(a, DoA(1)).InSequence(s);
  1137. EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation();
  1138. EXPECT_CALL(a, DoA(1)).InSequence(s);
  1139. a.DoA(1);
  1140. a.DoA(2);
  1141. a.DoA(1);
  1142. }
  1143. // Tests Expectation.
  1144. TEST(ExpectationTest, ConstrutorsWork) {
  1145. MockA a;
  1146. Expectation e1; // Default ctor.
  1147. // Ctor from various forms of EXPECT_CALL.
  1148. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1149. Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
  1150. {
  1151. Sequence s;
  1152. Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
  1153. Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
  1154. }
  1155. Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
  1156. Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
  1157. Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
  1158. Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
  1159. Expectation e10 = e2; // Copy ctor.
  1160. EXPECT_THAT(e1, Ne(e2));
  1161. EXPECT_THAT(e2, Eq(e10));
  1162. a.DoA(2);
  1163. a.DoA(3);
  1164. a.DoA(4);
  1165. a.DoA(5);
  1166. a.DoA(6);
  1167. a.DoA(7);
  1168. a.DoA(8);
  1169. a.DoA(9);
  1170. }
  1171. TEST(ExpectationTest, AssignmentWorks) {
  1172. MockA a;
  1173. Expectation e1;
  1174. Expectation e2 = EXPECT_CALL(a, DoA(1));
  1175. EXPECT_THAT(e1, Ne(e2));
  1176. e1 = e2;
  1177. EXPECT_THAT(e1, Eq(e2));
  1178. a.DoA(1);
  1179. }
  1180. // Tests ExpectationSet.
  1181. TEST(ExpectationSetTest, MemberTypesAreCorrect) {
  1182. ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
  1183. }
  1184. TEST(ExpectationSetTest, ConstructorsWork) {
  1185. MockA a;
  1186. Expectation e1;
  1187. const Expectation e2;
  1188. ExpectationSet es1; // Default ctor.
  1189. ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
  1190. ExpectationSet es3 = e1; // Ctor from Expectation.
  1191. ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
  1192. ExpectationSet es5 = e2; // Ctor from const Expectation.
  1193. ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
  1194. ExpectationSet es7 = es2; // Copy ctor.
  1195. EXPECT_EQ(0, es1.size());
  1196. EXPECT_EQ(1, es2.size());
  1197. EXPECT_EQ(1, es3.size());
  1198. EXPECT_EQ(1, es4.size());
  1199. EXPECT_EQ(1, es5.size());
  1200. EXPECT_EQ(1, es6.size());
  1201. EXPECT_EQ(1, es7.size());
  1202. EXPECT_THAT(es3, Ne(es2));
  1203. EXPECT_THAT(es4, Eq(es3));
  1204. EXPECT_THAT(es5, Eq(es4));
  1205. EXPECT_THAT(es6, Eq(es5));
  1206. EXPECT_THAT(es7, Eq(es2));
  1207. a.DoA(1);
  1208. }
  1209. TEST(ExpectationSetTest, AssignmentWorks) {
  1210. ExpectationSet es1;
  1211. ExpectationSet es2 = Expectation();
  1212. es1 = es2;
  1213. EXPECT_EQ(1, es1.size());
  1214. EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
  1215. EXPECT_THAT(es1, Eq(es2));
  1216. }
  1217. TEST(ExpectationSetTest, InsertionWorks) {
  1218. ExpectationSet es1;
  1219. Expectation e1;
  1220. es1 += e1;
  1221. EXPECT_EQ(1, es1.size());
  1222. EXPECT_THAT(*(es1.begin()), Eq(e1));
  1223. MockA a;
  1224. Expectation e2 = EXPECT_CALL(a, DoA(1));
  1225. es1 += e2;
  1226. EXPECT_EQ(2, es1.size());
  1227. ExpectationSet::const_iterator it1 = es1.begin();
  1228. ExpectationSet::const_iterator it2 = it1;
  1229. ++it2;
  1230. EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
  1231. EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
  1232. a.DoA(1);
  1233. }
  1234. TEST(ExpectationSetTest, SizeWorks) {
  1235. ExpectationSet es;
  1236. EXPECT_EQ(0, es.size());
  1237. es += Expectation();
  1238. EXPECT_EQ(1, es.size());
  1239. MockA a;
  1240. es += EXPECT_CALL(a, DoA(1));
  1241. EXPECT_EQ(2, es.size());
  1242. a.DoA(1);
  1243. }
  1244. TEST(ExpectationSetTest, IsEnumerable) {
  1245. ExpectationSet es;
  1246. EXPECT_TRUE(es.begin() == es.end());
  1247. es += Expectation();
  1248. ExpectationSet::const_iterator it = es.begin();
  1249. EXPECT_TRUE(it != es.end());
  1250. EXPECT_THAT(*it, Eq(Expectation()));
  1251. ++it;
  1252. EXPECT_TRUE(it == es.end());
  1253. }
  1254. // Tests the .After() clause.
  1255. TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
  1256. MockA a;
  1257. ExpectationSet es;
  1258. es += EXPECT_CALL(a, DoA(1));
  1259. es += EXPECT_CALL(a, DoA(2));
  1260. EXPECT_CALL(a, DoA(3)).After(es);
  1261. a.DoA(1);
  1262. a.DoA(2);
  1263. a.DoA(3);
  1264. }
  1265. TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
  1266. MockA a;
  1267. MockB b;
  1268. // The following also verifies that const Expectation objects work
  1269. // too. Do not remove the const modifiers.
  1270. const Expectation e1 = EXPECT_CALL(a, DoA(1));
  1271. const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
  1272. EXPECT_CALL(a, DoA(2)).After(e2);
  1273. a.DoA(1);
  1274. b.DoB();
  1275. b.DoB();
  1276. a.DoA(2);
  1277. }
  1278. // Calls must be in strict order when specified so using .After().
  1279. TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
  1280. MockA a;
  1281. MockB b;
  1282. // Define ordering:
  1283. // a.DoA(1) ==> b.DoB() ==> a.DoA(2)
  1284. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1285. Expectation e2 = EXPECT_CALL(b, DoB()).After(e1);
  1286. EXPECT_CALL(a, DoA(2)).After(e2);
  1287. a.DoA(1);
  1288. // May only be called after DoB().
  1289. EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
  1290. b.DoB();
  1291. a.DoA(2);
  1292. }
  1293. // Calls must be in strict order when specified so using .After().
  1294. TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
  1295. MockA a;
  1296. MockB b;
  1297. // Define ordering:
  1298. // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
  1299. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1300. Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
  1301. EXPECT_CALL(a, DoA(2)).After(e2);
  1302. a.DoA(1);
  1303. b.DoB();
  1304. // May only be called after the second DoB().
  1305. EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
  1306. b.DoB();
  1307. a.DoA(2);
  1308. }
  1309. // Calls must satisfy the partial order when specified so.
  1310. TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
  1311. MockA a;
  1312. ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
  1313. // Define ordering:
  1314. // a.DoA(1) ==>
  1315. // a.DoA(2) ==> a.ReturnResult(3)
  1316. Expectation e = EXPECT_CALL(a, DoA(1));
  1317. const ExpectationSet es = EXPECT_CALL(a, DoA(2));
  1318. EXPECT_CALL(a, ReturnResult(3)).After(e, es);
  1319. // May only be called last.
  1320. EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
  1321. a.DoA(2);
  1322. a.DoA(1);
  1323. a.ReturnResult(3);
  1324. }
  1325. // Calls must satisfy the partial order when specified so.
  1326. TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
  1327. MockA a;
  1328. // Define ordering:
  1329. // a.DoA(1) ==>
  1330. // a.DoA(2) ==> a.DoA(3)
  1331. Expectation e = EXPECT_CALL(a, DoA(1));
  1332. const ExpectationSet es = EXPECT_CALL(a, DoA(2));
  1333. EXPECT_CALL(a, DoA(3)).After(e, es);
  1334. a.DoA(2);
  1335. // May only be called last.
  1336. EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
  1337. a.DoA(1);
  1338. a.DoA(3);
  1339. }
  1340. // .After() can be combined with .InSequence().
  1341. TEST(AfterTest, CanBeUsedWithInSequence) {
  1342. MockA a;
  1343. Sequence s;
  1344. Expectation e = EXPECT_CALL(a, DoA(1));
  1345. EXPECT_CALL(a, DoA(2)).InSequence(s);
  1346. EXPECT_CALL(a, DoA(3)).InSequence(s).After(e);
  1347. a.DoA(1);
  1348. // May only be after DoA(2).
  1349. EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
  1350. a.DoA(2);
  1351. a.DoA(3);
  1352. }
  1353. // .After() can be called multiple times.
  1354. TEST(AfterTest, CanBeCalledManyTimes) {
  1355. MockA a;
  1356. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1357. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1358. Expectation e3 = EXPECT_CALL(a, DoA(3));
  1359. EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3);
  1360. a.DoA(3);
  1361. a.DoA(1);
  1362. a.DoA(2);
  1363. a.DoA(4);
  1364. }
  1365. // .After() accepts up to 5 arguments.
  1366. TEST(AfterTest, AcceptsUpToFiveArguments) {
  1367. MockA a;
  1368. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1369. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1370. Expectation e3 = EXPECT_CALL(a, DoA(3));
  1371. ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
  1372. ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
  1373. EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2);
  1374. a.DoA(5);
  1375. a.DoA(2);
  1376. a.DoA(4);
  1377. a.DoA(1);
  1378. a.DoA(3);
  1379. a.DoA(6);
  1380. }
  1381. // .After() allows input to contain duplicated Expectations.
  1382. TEST(AfterTest, AcceptsDuplicatedInput) {
  1383. MockA a;
  1384. ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
  1385. // Define ordering:
  1386. // DoA(1) ==>
  1387. // DoA(2) ==> ReturnResult(3)
  1388. Expectation e1 = EXPECT_CALL(a, DoA(1));
  1389. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1390. ExpectationSet es;
  1391. es += e1;
  1392. es += e2;
  1393. EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1);
  1394. a.DoA(1);
  1395. // May only be after DoA(2).
  1396. EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
  1397. a.DoA(2);
  1398. a.ReturnResult(3);
  1399. }
  1400. // An Expectation added to an ExpectationSet after it has been used in
  1401. // an .After() has no effect.
  1402. TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
  1403. MockA a;
  1404. ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
  1405. Expectation e2 = EXPECT_CALL(a, DoA(2));
  1406. EXPECT_CALL(a, DoA(3)).After(es1);
  1407. es1 += e2;
  1408. a.DoA(1);
  1409. a.DoA(3);
  1410. a.DoA(2);
  1411. }
  1412. // Tests that Google Mock correctly handles calls to mock functions
  1413. // after a mock object owning one of their pre-requisites has died.
  1414. // Tests that calls that satisfy the original spec are successful.
  1415. TEST(DeletingMockEarlyTest, Success1) {
  1416. MockB* const b1 = new MockB;
  1417. MockA* const a = new MockA;
  1418. MockB* const b2 = new MockB;
  1419. {
  1420. InSequence dummy;
  1421. EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
  1422. EXPECT_CALL(*a, Binary(_, _))
  1423. .Times(AnyNumber())
  1424. .WillRepeatedly(Return(true));
  1425. EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
  1426. }
  1427. EXPECT_EQ(1, b1->DoB(1));
  1428. delete b1;
  1429. // a's pre-requisite has died.
  1430. EXPECT_TRUE(a->Binary(0, 1));
  1431. delete b2;
  1432. // a's successor has died.
  1433. EXPECT_TRUE(a->Binary(1, 2));
  1434. delete a;
  1435. }
  1436. // Tests that calls that satisfy the original spec are successful.
  1437. TEST(DeletingMockEarlyTest, Success2) {
  1438. MockB* const b1 = new MockB;
  1439. MockA* const a = new MockA;
  1440. MockB* const b2 = new MockB;
  1441. {
  1442. InSequence dummy;
  1443. EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
  1444. EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
  1445. EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
  1446. }
  1447. delete a; // a is trivially satisfied.
  1448. EXPECT_EQ(1, b1->DoB(1));
  1449. EXPECT_EQ(2, b2->DoB(2));
  1450. delete b1;
  1451. delete b2;
  1452. }
  1453. // Tests that it's OK to delete a mock object itself in its action.
  1454. // Suppresses warning on unreferenced formal parameter in MSVC with
  1455. // -W4.
  1456. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)
  1457. ACTION_P(Delete, ptr) { delete ptr; }
  1458. GTEST_DISABLE_MSC_WARNINGS_POP_() // 4100
  1459. TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
  1460. MockA* const a = new MockA;
  1461. EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
  1462. a->DoA(42); // This will cause a to be deleted.
  1463. }
  1464. TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
  1465. MockA* const a = new MockA;
  1466. EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));
  1467. a->ReturnResult(42); // This will cause a to be deleted.
  1468. }
  1469. // Tests that calls that violate the original spec yield failures.
  1470. TEST(DeletingMockEarlyTest, Failure1) {
  1471. MockB* const b1 = new MockB;
  1472. MockA* const a = new MockA;
  1473. MockB* const b2 = new MockB;
  1474. {
  1475. InSequence dummy;
  1476. EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
  1477. EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
  1478. EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
  1479. }
  1480. delete a; // a is trivially satisfied.
  1481. EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call");
  1482. EXPECT_EQ(1, b1->DoB(1));
  1483. delete b1;
  1484. delete b2;
  1485. }
  1486. // Tests that calls that violate the original spec yield failures.
  1487. TEST(DeletingMockEarlyTest, Failure2) {
  1488. MockB* const b1 = new MockB;
  1489. MockA* const a = new MockA;
  1490. MockB* const b2 = new MockB;
  1491. {
  1492. InSequence dummy;
  1493. EXPECT_CALL(*b1, DoB(_));
  1494. EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
  1495. EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());
  1496. }
  1497. EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called");
  1498. EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call");
  1499. EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call");
  1500. delete a;
  1501. delete b2;
  1502. }
  1503. class EvenNumberCardinality : public CardinalityInterface {
  1504. public:
  1505. // Returns true if and only if call_count calls will satisfy this
  1506. // cardinality.
  1507. bool IsSatisfiedByCallCount(int call_count) const override {
  1508. return call_count % 2 == 0;
  1509. }
  1510. // Returns true if and only if call_count calls will saturate this
  1511. // cardinality.
  1512. bool IsSaturatedByCallCount(int /* call_count */) const override {
  1513. return false;
  1514. }
  1515. // Describes self to an ostream.
  1516. void DescribeTo(::std::ostream* os) const override {
  1517. *os << "called even number of times";
  1518. }
  1519. };
  1520. Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }
  1521. TEST(ExpectationBaseTest,
  1522. AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
  1523. MockA* a = new MockA;
  1524. Sequence s;
  1525. EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);
  1526. EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);
  1527. EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());
  1528. a->DoA(3);
  1529. a->DoA(1);
  1530. EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
  1531. EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
  1532. }
  1533. // The following tests verify the message generated when a mock
  1534. // function is called.
  1535. struct Printable {};
  1536. inline void operator<<(::std::ostream& os, const Printable&) {
  1537. os << "Printable";
  1538. }
  1539. struct Unprintable {
  1540. Unprintable() : value(0) {}
  1541. int value;
  1542. };
  1543. class MockC {
  1544. public:
  1545. MockC() = default;
  1546. MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
  1547. const Printable& x, Unprintable y));
  1548. MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
  1549. private:
  1550. MockC(const MockC&) = delete;
  1551. MockC& operator=(const MockC&) = delete;
  1552. };
  1553. class VerboseFlagPreservingFixture : public testing::Test {
  1554. protected:
  1555. VerboseFlagPreservingFixture()
  1556. : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}
  1557. ~VerboseFlagPreservingFixture() override {
  1558. GMOCK_FLAG_SET(verbose, saved_verbose_flag_);
  1559. }
  1560. private:
  1561. const std::string saved_verbose_flag_;
  1562. VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;
  1563. VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =
  1564. delete;
  1565. };
  1566. #if GTEST_HAS_STREAM_REDIRECTION
  1567. // Tests that an uninteresting mock function call on a naggy mock
  1568. // generates a warning without the stack trace when
  1569. // --gmock_verbose=warning is specified.
  1570. TEST(FunctionCallMessageTest,
  1571. UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
  1572. GMOCK_FLAG_SET(verbose, kWarningVerbosity);
  1573. NaggyMock<MockC> c;
  1574. CaptureStdout();
  1575. c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
  1576. const std::string output = GetCapturedStdout();
  1577. EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
  1578. EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
  1579. }
  1580. // Tests that an uninteresting mock function call on a naggy mock
  1581. // generates a warning containing the stack trace when
  1582. // --gmock_verbose=info is specified.
  1583. TEST(FunctionCallMessageTest,
  1584. UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
  1585. GMOCK_FLAG_SET(verbose, kInfoVerbosity);
  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(IsSubstring, "Stack trace:", output);
  1592. #ifndef NDEBUG
  1593. // We check the stack trace content in dbg-mode only, as opt-mode
  1594. // may inline the call we are interested in seeing.
  1595. // Verifies that a void mock function's name appears in the stack
  1596. // trace.
  1597. EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
  1598. // Verifies that a non-void mock function's name appears in the
  1599. // stack trace.
  1600. CaptureStdout();
  1601. c.NonVoidMethod();
  1602. const std::string output2 = GetCapturedStdout();
  1603. EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
  1604. #endif // NDEBUG
  1605. }
  1606. // Tests that an uninteresting mock function call on a naggy mock
  1607. // causes the function arguments and return value to be printed.
  1608. TEST(FunctionCallMessageTest,
  1609. UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
  1610. // A non-void mock function.
  1611. NaggyMock<MockB> b;
  1612. CaptureStdout();
  1613. b.DoB();
  1614. const std::string output1 = GetCapturedStdout();
  1615. EXPECT_PRED_FORMAT2(
  1616. IsSubstring,
  1617. "Uninteresting mock function call - returning default value.\n"
  1618. " Function call: DoB()\n"
  1619. " Returns: 0\n",
  1620. output1.c_str());
  1621. // Makes sure the return value is printed.
  1622. // A void mock function.
  1623. NaggyMock<MockC> c;
  1624. CaptureStdout();
  1625. c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
  1626. const std::string output2 = GetCapturedStdout();
  1627. EXPECT_THAT(
  1628. output2.c_str(),
  1629. ContainsRegex("Uninteresting mock function call - returning directly\\.\n"
  1630. " Function call: VoidMethod"
  1631. "\\(false, 5, \"Hi\", NULL, @.+ "
  1632. "Printable, 4-byte object <00-00 00-00>\\)"));
  1633. // A void function has no return value to print.
  1634. }
  1635. // Tests how the --gmock_verbose flag affects Google Mock's output.
  1636. class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
  1637. public:
  1638. // Verifies that the given Google Mock output is correct. (When
  1639. // should_print is true, the output should match the given regex and
  1640. // contain the given function name in the stack trace. When it's
  1641. // false, the output should be empty.)
  1642. void VerifyOutput(const std::string& output, bool should_print,
  1643. const std::string& expected_substring,
  1644. const std::string& function_name) {
  1645. if (should_print) {
  1646. EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
  1647. #ifndef NDEBUG
  1648. // We check the stack trace content in dbg-mode only, as opt-mode
  1649. // may inline the call we are interested in seeing.
  1650. EXPECT_THAT(output.c_str(), HasSubstr(function_name));
  1651. #else
  1652. // Suppresses 'unused function parameter' warnings.
  1653. static_cast<void>(function_name);
  1654. #endif // NDEBUG
  1655. } else {
  1656. EXPECT_STREQ("", output.c_str());
  1657. }
  1658. }
  1659. // Tests how the flag affects expected calls.
  1660. void TestExpectedCall(bool should_print) {
  1661. MockA a;
  1662. EXPECT_CALL(a, DoA(5));
  1663. EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));
  1664. // A void-returning function.
  1665. CaptureStdout();
  1666. a.DoA(5);
  1667. VerifyOutput(GetCapturedStdout(), should_print,
  1668. "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
  1669. " Function call: DoA(5)\n"
  1670. "Stack trace:\n",
  1671. "DoA");
  1672. // A non-void-returning function.
  1673. CaptureStdout();
  1674. a.Binary(2, 1);
  1675. VerifyOutput(GetCapturedStdout(), should_print,
  1676. "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
  1677. " Function call: Binary(2, 1)\n"
  1678. " Returns: true\n"
  1679. "Stack trace:\n",
  1680. "Binary");
  1681. }
  1682. // Tests how the flag affects uninteresting calls on a naggy mock.
  1683. void TestUninterestingCallOnNaggyMock(bool should_print) {
  1684. NaggyMock<MockA> a;
  1685. const std::string note =
  1686. "NOTE: You can safely ignore the above warning unless this "
  1687. "call should not happen. Do not suppress it by blindly adding "
  1688. "an EXPECT_CALL() if you don't mean to enforce the call. "
  1689. "See "
  1690. "https://github.com/google/googletest/blob/main/docs/"
  1691. "gmock_cook_book.md#"
  1692. "knowing-when-to-expect-useoncall for details.";
  1693. // A void-returning function.
  1694. CaptureStdout();
  1695. a.DoA(5);
  1696. VerifyOutput(GetCapturedStdout(), should_print,
  1697. "\nGMOCK WARNING:\n"
  1698. "Uninteresting mock function call - returning directly.\n"
  1699. " Function call: DoA(5)\n" +
  1700. note,
  1701. "DoA");
  1702. // A non-void-returning function.
  1703. CaptureStdout();
  1704. a.Binary(2, 1);
  1705. VerifyOutput(GetCapturedStdout(), should_print,
  1706. "\nGMOCK WARNING:\n"
  1707. "Uninteresting mock function call - returning default value.\n"
  1708. " Function call: Binary(2, 1)\n"
  1709. " Returns: false\n" +
  1710. note,
  1711. "Binary");
  1712. }
  1713. };
  1714. // Tests that --gmock_verbose=info causes both expected and
  1715. // uninteresting calls to be reported.
  1716. TEST_F(GMockVerboseFlagTest, Info) {
  1717. GMOCK_FLAG_SET(verbose, kInfoVerbosity);
  1718. TestExpectedCall(true);
  1719. TestUninterestingCallOnNaggyMock(true);
  1720. }
  1721. // Tests that --gmock_verbose=warning causes uninteresting calls to be
  1722. // reported.
  1723. TEST_F(GMockVerboseFlagTest, Warning) {
  1724. GMOCK_FLAG_SET(verbose, kWarningVerbosity);
  1725. TestExpectedCall(false);
  1726. TestUninterestingCallOnNaggyMock(true);
  1727. }
  1728. // Tests that --gmock_verbose=warning causes neither expected nor
  1729. // uninteresting calls to be reported.
  1730. TEST_F(GMockVerboseFlagTest, Error) {
  1731. GMOCK_FLAG_SET(verbose, kErrorVerbosity);
  1732. TestExpectedCall(false);
  1733. TestUninterestingCallOnNaggyMock(false);
  1734. }
  1735. // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
  1736. // as --gmock_verbose=warning.
  1737. TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
  1738. GMOCK_FLAG_SET(verbose, "invalid"); // Treated as "warning".
  1739. TestExpectedCall(false);
  1740. TestUninterestingCallOnNaggyMock(true);
  1741. }
  1742. #endif // GTEST_HAS_STREAM_REDIRECTION
  1743. // A helper class that generates a failure when printed. We use it to
  1744. // ensure that Google Mock doesn't print a value (even to an internal
  1745. // buffer) when it is not supposed to do so.
  1746. class PrintMeNot {};
  1747. void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
  1748. ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
  1749. << "printed even to an internal buffer.";
  1750. }
  1751. class LogTestHelper {
  1752. public:
  1753. LogTestHelper() = default;
  1754. MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
  1755. private:
  1756. LogTestHelper(const LogTestHelper&) = delete;
  1757. LogTestHelper& operator=(const LogTestHelper&) = delete;
  1758. };
  1759. class GMockLogTest : public VerboseFlagPreservingFixture {
  1760. protected:
  1761. LogTestHelper helper_;
  1762. };
  1763. TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
  1764. GMOCK_FLAG_SET(verbose, kWarningVerbosity);
  1765. EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
  1766. helper_.Foo(PrintMeNot()); // This is an expected call.
  1767. }
  1768. TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
  1769. GMOCK_FLAG_SET(verbose, kErrorVerbosity);
  1770. EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
  1771. helper_.Foo(PrintMeNot()); // This is an expected call.
  1772. }
  1773. TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
  1774. GMOCK_FLAG_SET(verbose, kErrorVerbosity);
  1775. ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));
  1776. helper_.Foo(PrintMeNot()); // This should generate a warning.
  1777. }
  1778. // Tests Mock::AllowLeak().
  1779. TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
  1780. MockA* a = new MockA;
  1781. Mock::AllowLeak(a);
  1782. }
  1783. TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
  1784. MockA* a = new MockA;
  1785. Mock::AllowLeak(a);
  1786. ON_CALL(*a, DoA(_)).WillByDefault(Return());
  1787. a->DoA(0);
  1788. }
  1789. TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
  1790. MockA* a = new MockA;
  1791. ON_CALL(*a, DoA(_)).WillByDefault(Return());
  1792. Mock::AllowLeak(a);
  1793. }
  1794. TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
  1795. MockA* a = new MockA;
  1796. Mock::AllowLeak(a);
  1797. EXPECT_CALL(*a, DoA(_));
  1798. a->DoA(0);
  1799. }
  1800. TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
  1801. MockA* a = new MockA;
  1802. EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
  1803. Mock::AllowLeak(a);
  1804. }
  1805. TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
  1806. MockA* a = new MockA;
  1807. ON_CALL(*a, DoA(_)).WillByDefault(Return());
  1808. EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
  1809. Mock::AllowLeak(a);
  1810. }
  1811. // Tests that we can verify and clear a mock object's expectations
  1812. // when none of its methods has expectations.
  1813. TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
  1814. MockB b;
  1815. ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
  1816. // There should be no expectations on the methods now, so we can
  1817. // freely call them.
  1818. EXPECT_EQ(0, b.DoB());
  1819. EXPECT_EQ(0, b.DoB(1));
  1820. }
  1821. // Tests that we can verify and clear a mock object's expectations
  1822. // when some, but not all, of its methods have expectations *and* the
  1823. // verification succeeds.
  1824. TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
  1825. MockB b;
  1826. EXPECT_CALL(b, DoB()).WillOnce(Return(1));
  1827. b.DoB();
  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 fails.
  1837. TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
  1838. MockB b;
  1839. EXPECT_CALL(b, DoB()).WillOnce(Return(1));
  1840. bool result = true;
  1841. EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
  1842. "Actual: never called");
  1843. ASSERT_FALSE(result);
  1844. // There should be no expectations on the methods now, so we can
  1845. // freely call them.
  1846. EXPECT_EQ(0, b.DoB());
  1847. EXPECT_EQ(0, b.DoB(1));
  1848. }
  1849. // Tests that we can verify and clear a mock object's expectations
  1850. // when all of its methods have expectations.
  1851. TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
  1852. MockB b;
  1853. EXPECT_CALL(b, DoB()).WillOnce(Return(1));
  1854. EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
  1855. b.DoB();
  1856. b.DoB(1);
  1857. ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
  1858. // There should be no expectations on the methods now, so we can
  1859. // freely call them.
  1860. EXPECT_EQ(0, b.DoB());
  1861. EXPECT_EQ(0, b.DoB(1));
  1862. }
  1863. // Tests that we can verify and clear a mock object's expectations
  1864. // when a method has more than one expectation.
  1865. TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
  1866. MockB b;
  1867. EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));
  1868. EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
  1869. b.DoB(1);
  1870. bool result = true;
  1871. EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
  1872. "Actual: never called");
  1873. ASSERT_FALSE(result);
  1874. // There should be no expectations on the methods now, so we can
  1875. // freely call them.
  1876. EXPECT_EQ(0, b.DoB());
  1877. EXPECT_EQ(0, b.DoB(1));
  1878. }
  1879. // Tests that we can call VerifyAndClearExpectations() on the same
  1880. // mock object multiple times.
  1881. TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
  1882. MockB b;
  1883. EXPECT_CALL(b, DoB());
  1884. b.DoB();
  1885. Mock::VerifyAndClearExpectations(&b);
  1886. EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));
  1887. b.DoB(1);
  1888. Mock::VerifyAndClearExpectations(&b);
  1889. Mock::VerifyAndClearExpectations(&b);
  1890. // There should be no expectations on the methods now, so we can
  1891. // freely call them.
  1892. EXPECT_EQ(0, b.DoB());
  1893. EXPECT_EQ(0, b.DoB(1));
  1894. }
  1895. // Tests that we can clear a mock object's default actions when none
  1896. // of its methods has default actions.
  1897. TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
  1898. MockB b;
  1899. // If this crashes or generates a failure, the test will catch it.
  1900. Mock::VerifyAndClear(&b);
  1901. EXPECT_EQ(0, b.DoB());
  1902. }
  1903. // Tests that we can clear a mock object's default actions when some,
  1904. // but not all of its methods have default actions.
  1905. TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
  1906. MockB b;
  1907. ON_CALL(b, DoB()).WillByDefault(Return(1));
  1908. Mock::VerifyAndClear(&b);
  1909. // Verifies that the default action of int DoB() was removed.
  1910. EXPECT_EQ(0, b.DoB());
  1911. }
  1912. // Tests that we can clear a mock object's default actions when all of
  1913. // its methods have default actions.
  1914. TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
  1915. MockB b;
  1916. ON_CALL(b, DoB()).WillByDefault(Return(1));
  1917. ON_CALL(b, DoB(_)).WillByDefault(Return(2));
  1918. Mock::VerifyAndClear(&b);
  1919. // Verifies that the default action of int DoB() was removed.
  1920. EXPECT_EQ(0, b.DoB());
  1921. // Verifies that the default action of int DoB(int) was removed.
  1922. EXPECT_EQ(0, b.DoB(0));
  1923. }
  1924. // Tests that we can clear a mock object's default actions when a
  1925. // method has more than one ON_CALL() set on it.
  1926. TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
  1927. MockB b;
  1928. ON_CALL(b, DoB(0)).WillByDefault(Return(1));
  1929. ON_CALL(b, DoB(_)).WillByDefault(Return(2));
  1930. Mock::VerifyAndClear(&b);
  1931. // Verifies that the default actions (there are two) of int DoB(int)
  1932. // were removed.
  1933. EXPECT_EQ(0, b.DoB(0));
  1934. EXPECT_EQ(0, b.DoB(1));
  1935. }
  1936. // Tests that we can call VerifyAndClear() on a mock object multiple
  1937. // times.
  1938. TEST(VerifyAndClearTest, CanCallManyTimes) {
  1939. MockB b;
  1940. ON_CALL(b, DoB()).WillByDefault(Return(1));
  1941. Mock::VerifyAndClear(&b);
  1942. Mock::VerifyAndClear(&b);
  1943. ON_CALL(b, DoB(_)).WillByDefault(Return(1));
  1944. Mock::VerifyAndClear(&b);
  1945. EXPECT_EQ(0, b.DoB());
  1946. EXPECT_EQ(0, b.DoB(1));
  1947. }
  1948. // Tests that VerifyAndClear() works when the verification succeeds.
  1949. TEST(VerifyAndClearTest, Success) {
  1950. MockB b;
  1951. ON_CALL(b, DoB()).WillByDefault(Return(1));
  1952. EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));
  1953. b.DoB();
  1954. b.DoB(1);
  1955. ASSERT_TRUE(Mock::VerifyAndClear(&b));
  1956. // There should be no expectations on the methods now, so we can
  1957. // freely call them.
  1958. EXPECT_EQ(0, b.DoB());
  1959. EXPECT_EQ(0, b.DoB(1));
  1960. }
  1961. // Tests that VerifyAndClear() works when the verification fails.
  1962. TEST(VerifyAndClearTest, Failure) {
  1963. MockB b;
  1964. ON_CALL(b, DoB(_)).WillByDefault(Return(1));
  1965. EXPECT_CALL(b, DoB()).WillOnce(Return(2));
  1966. b.DoB(1);
  1967. bool result = true;
  1968. EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
  1969. "Actual: never called");
  1970. ASSERT_FALSE(result);
  1971. // There should be no expectations on the methods now, so we can
  1972. // freely call them.
  1973. EXPECT_EQ(0, b.DoB());
  1974. EXPECT_EQ(0, b.DoB(1));
  1975. }
  1976. // Tests that VerifyAndClear() works when the default actions and
  1977. // expectations are set on a const mock object.
  1978. TEST(VerifyAndClearTest, Const) {
  1979. MockB b;
  1980. ON_CALL(Const(b), DoB()).WillByDefault(Return(1));
  1981. EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));
  1982. b.DoB();
  1983. b.DoB();
  1984. ASSERT_TRUE(Mock::VerifyAndClear(&b));
  1985. // There should be no expectations on the methods now, so we can
  1986. // freely call them.
  1987. EXPECT_EQ(0, b.DoB());
  1988. EXPECT_EQ(0, b.DoB(1));
  1989. }
  1990. // Tests that we can set default actions and expectations on a mock
  1991. // object after VerifyAndClear() has been called on it.
  1992. TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
  1993. MockB b;
  1994. ON_CALL(b, DoB()).WillByDefault(Return(1));
  1995. EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
  1996. b.DoB(1);
  1997. Mock::VerifyAndClear(&b);
  1998. EXPECT_CALL(b, DoB()).WillOnce(Return(3));
  1999. ON_CALL(b, DoB(_)).WillByDefault(Return(4));
  2000. EXPECT_EQ(3, b.DoB());
  2001. EXPECT_EQ(4, b.DoB(1));
  2002. }
  2003. // Tests that calling VerifyAndClear() on one mock object does not
  2004. // affect other mock objects (either of the same type or not).
  2005. TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
  2006. MockA a;
  2007. MockB b1;
  2008. MockB b2;
  2009. ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
  2010. EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));
  2011. ON_CALL(b1, DoB()).WillByDefault(Return(1));
  2012. EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));
  2013. ON_CALL(b2, DoB()).WillByDefault(Return(3));
  2014. EXPECT_CALL(b2, DoB(_));
  2015. b2.DoB(0);
  2016. Mock::VerifyAndClear(&b2);
  2017. // Verifies that the default actions and expectations of a and b1
  2018. // are still in effect.
  2019. EXPECT_TRUE(a.Binary(0, 0));
  2020. EXPECT_FALSE(a.Binary(0, 0));
  2021. EXPECT_EQ(1, b1.DoB());
  2022. EXPECT_EQ(2, b1.DoB(0));
  2023. }
  2024. TEST(VerifyAndClearTest,
  2025. DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
  2026. std::shared_ptr<MockA> a(new MockA);
  2027. ReferenceHoldingMock test_mock;
  2028. // EXPECT_CALL stores a reference to a inside test_mock.
  2029. EXPECT_CALL(test_mock, AcceptReference(_))
  2030. .WillRepeatedly(SetArgPointee<0>(a));
  2031. // Throw away the reference to the mock that we have in a. After this, the
  2032. // only reference to it is stored by test_mock.
  2033. a.reset();
  2034. // When test_mock goes out of scope, it destroys the last remaining reference
  2035. // to the mock object originally pointed to by a. This will cause the MockA
  2036. // destructor to be called from inside the ReferenceHoldingMock destructor.
  2037. // The state of all mocks is protected by a single global lock, but there
  2038. // should be no deadlock.
  2039. }
  2040. TEST(VerifyAndClearTest,
  2041. DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
  2042. std::shared_ptr<MockA> a(new MockA);
  2043. ReferenceHoldingMock test_mock;
  2044. // ON_CALL stores a reference to a inside test_mock.
  2045. ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));
  2046. // Throw away the reference to the mock that we have in a. After this, the
  2047. // only reference to it is stored by test_mock.
  2048. a.reset();
  2049. // When test_mock goes out of scope, it destroys the last remaining reference
  2050. // to the mock object originally pointed to by a. This will cause the MockA
  2051. // destructor to be called from inside the ReferenceHoldingMock destructor.
  2052. // The state of all mocks is protected by a single global lock, but there
  2053. // should be no deadlock.
  2054. }
  2055. // Tests that a mock function's action can call a mock function
  2056. // (either the same function or a different one) either as an explicit
  2057. // action or as a default action without causing a dead lock. It
  2058. // verifies that the action is not performed inside the critical
  2059. // section.
  2060. TEST(SynchronizationTest, CanCallMockMethodInAction) {
  2061. MockA a;
  2062. MockC c;
  2063. ON_CALL(a, DoA(_)).WillByDefault(
  2064. IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));
  2065. EXPECT_CALL(a, DoA(1));
  2066. EXPECT_CALL(a, DoA(1))
  2067. .WillOnce(Invoke(&a, &MockA::DoA))
  2068. .RetiresOnSaturation();
  2069. EXPECT_CALL(c, NonVoidMethod());
  2070. a.DoA(1);
  2071. // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
  2072. // which will in turn match the first EXPECT_CALL() and trigger a call to
  2073. // c.NonVoidMethod() that was specified by the ON_CALL() since the first
  2074. // EXPECT_CALL() did not specify an action.
  2075. }
  2076. TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
  2077. MockA a;
  2078. int do_a_arg0 = 0;
  2079. ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
  2080. int do_a_47_arg0 = 0;
  2081. ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
  2082. a.DoA(17);
  2083. EXPECT_THAT(do_a_arg0, 17);
  2084. EXPECT_THAT(do_a_47_arg0, 0);
  2085. a.DoA(47);
  2086. EXPECT_THAT(do_a_arg0, 17);
  2087. EXPECT_THAT(do_a_47_arg0, 47);
  2088. ON_CALL(a, Binary).WillByDefault(Return(true));
  2089. ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
  2090. EXPECT_THAT(a.Binary(14, 17), true);
  2091. EXPECT_THAT(a.Binary(17, 14), false);
  2092. }
  2093. TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
  2094. MockB b;
  2095. ON_CALL(b, DoB()).WillByDefault(Return(9));
  2096. ON_CALL(b, DoB(5)).WillByDefault(Return(11));
  2097. EXPECT_THAT(b.DoB(), 9);
  2098. EXPECT_THAT(b.DoB(1), 0); // default value
  2099. EXPECT_THAT(b.DoB(5), 11);
  2100. }
  2101. struct MockWithConstMethods {
  2102. public:
  2103. MOCK_CONST_METHOD1(Foo, int(int));
  2104. MOCK_CONST_METHOD2(Bar, int(int, const char*));
  2105. };
  2106. TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
  2107. MockWithConstMethods mock;
  2108. ON_CALL(mock, Foo).WillByDefault(Return(7));
  2109. ON_CALL(mock, Bar).WillByDefault(Return(33));
  2110. EXPECT_THAT(mock.Foo(17), 7);
  2111. EXPECT_THAT(mock.Bar(27, "purple"), 33);
  2112. }
  2113. class MockConstOverload {
  2114. public:
  2115. MOCK_METHOD1(Overloaded, int(int));
  2116. MOCK_CONST_METHOD1(Overloaded, int(int));
  2117. };
  2118. TEST(ParameterlessExpectationsTest,
  2119. CanSetExpectationsForConstOverloadedMethods) {
  2120. MockConstOverload mock;
  2121. ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
  2122. ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
  2123. ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
  2124. ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
  2125. EXPECT_THAT(mock.Overloaded(1), 7);
  2126. EXPECT_THAT(mock.Overloaded(5), 9);
  2127. EXPECT_THAT(mock.Overloaded(7), 7);
  2128. const MockConstOverload& const_mock = mock;
  2129. EXPECT_THAT(const_mock.Overloaded(1), 0);
  2130. EXPECT_THAT(const_mock.Overloaded(5), 11);
  2131. EXPECT_THAT(const_mock.Overloaded(7), 13);
  2132. }
  2133. } // namespace
  2134. } // namespace testing
  2135. int main(int argc, char** argv) {
  2136. testing::InitGoogleMock(&argc, argv);
  2137. // Ensures that the tests pass no matter what value of
  2138. // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
  2139. GMOCK_FLAG_SET(catch_leaked_mocks, true);
  2140. GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);
  2141. return RUN_ALL_TESTS();
  2142. }