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