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