Sacado Package Browser (Single Doxygen Collection)  Version of the Day
 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.
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 
35 
36 #include <memory>
37 #include <ostream> // NOLINT
38 #include <sstream>
39 #include <string>
40 #include <type_traits>
41 
42 #include "gmock/gmock.h"
44 #include "gtest/gtest-spi.h"
45 #include "gtest/gtest.h"
47 
48 namespace testing {
49 namespace {
50 
52 using ::testing::internal::kAllow;
54 using ::testing::internal::kFail;
56 using ::testing::internal::kWarn;
58 
59 #if GTEST_HAS_STREAM_REDIRECTION
62 #endif
63 
64 class Incomplete;
65 
66 class MockIncomplete {
67  public:
68  // This line verifies that a mock method can take a by-reference
69  // argument of an incomplete type.
70  MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
71 };
72 
73 // Tells Google Mock how to print a value of type Incomplete.
74 void PrintTo(const Incomplete& x, ::std::ostream* os);
75 
76 TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
77  // Even though this mock class contains a mock method that takes
78  // by-reference an argument whose type is incomplete, we can still
79  // use the mock, as long as Google Mock knows how to print the
80  // argument.
81  MockIncomplete incomplete;
82  EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber());
83 }
84 
85 // The definition of the printer for the argument type doesn't have to
86 // be visible where the mock is used.
87 void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
88  *os << "incomplete";
89 }
90 
91 class Result {};
92 
93 // A type that's not default constructible.
94 class NonDefaultConstructible {
95  public:
96  explicit NonDefaultConstructible(int /* dummy */) {}
97 };
98 
99 class MockA {
100  public:
101  MockA() = default;
102 
103  MOCK_METHOD1(DoA, void(int n));
104  MOCK_METHOD1(ReturnResult, Result(int n));
105  MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
106  MOCK_METHOD2(Binary, bool(int x, int y));
107  MOCK_METHOD2(ReturnInt, int(int x, int y));
108 
109  private:
110  MockA(const MockA&) = delete;
111  MockA& operator=(const MockA&) = delete;
112 };
113 
114 class MockB {
115  public:
116  MockB() = default;
117 
118  MOCK_CONST_METHOD0(DoB, int()); // NOLINT
119  MOCK_METHOD1(DoB, int(int n)); // NOLINT
120 
121  private:
122  MockB(const MockB&) = delete;
123  MockB& operator=(const MockB&) = delete;
124 };
125 
126 class ReferenceHoldingMock {
127  public:
128  ReferenceHoldingMock() = default;
129 
130  MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
131 
132  private:
133  ReferenceHoldingMock(const ReferenceHoldingMock&) = delete;
134  ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete;
135 };
136 
137 // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
138 // redefining a mock method name. This could happen, for example, when
139 // the tested code #includes Win32 API headers which define many APIs
140 // as macros, e.g. #define TextOut TextOutW.
141 
142 #define Method MethodW
143 
144 class CC {
145  public:
146  virtual ~CC() = default;
147  virtual int Method() = 0;
148 };
149 class MockCC : public CC {
150  public:
151  MockCC() = default;
152 
153  MOCK_METHOD0(Method, int());
154 
155  private:
156  MockCC(const MockCC&) = delete;
157  MockCC& operator=(const MockCC&) = delete;
158 };
159 
160 // Tests that a method with expanded name compiles.
161 TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
162  MockCC cc;
163  ON_CALL(cc, Method());
164 }
165 
166 // Tests that the method with expanded name not only compiles but runs
167 // and returns a correct value, too.
168 TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
169  MockCC cc;
170  ON_CALL(cc, Method()).WillByDefault(Return(42));
171  EXPECT_EQ(42, cc.Method());
172 }
173 
174 // Tests that a method with expanded name compiles.
175 TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
176  MockCC cc;
177  EXPECT_CALL(cc, Method());
178  cc.Method();
179 }
180 
181 // Tests that it works, too.
182 TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
183  MockCC cc;
184  EXPECT_CALL(cc, Method()).WillOnce(Return(42));
185  EXPECT_EQ(42, cc.Method());
186 }
187 
188 #undef Method // Done with macro redefinition tests.
189 
190 // Tests that ON_CALL evaluates its arguments exactly once as promised
191 // by Google Mock.
192 TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
193  MockA a;
194  MockA* pa = &a;
195 
196  ON_CALL(*pa++, DoA(_));
197  EXPECT_EQ(&a + 1, pa);
198 }
199 
200 TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
201  MockA a;
202  int n = 0;
203 
204  ON_CALL(a, DoA(n++));
205  EXPECT_EQ(1, n);
206 }
207 
208 // Tests that the syntax of ON_CALL() is enforced at run time.
209 
210 TEST(OnCallSyntaxTest, WithIsOptional) {
211  MockA a;
212 
213  ON_CALL(a, DoA(5)).WillByDefault(Return());
214  ON_CALL(a, DoA(_)).With(_).WillByDefault(Return());
215 }
216 
217 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
218  MockA a;
219 
221  { // NOLINT
222  ON_CALL(a, ReturnResult(_))
223  .With(_)
224  .With(_)
225  .WillByDefault(Return(Result()));
226  },
227  ".With() cannot appear more than once in an ON_CALL()");
228 }
229 
230 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
231  MockA a;
232 
234  {
235  ON_CALL(a, DoA(5));
236  a.DoA(5);
237  },
238  "");
239 }
240 
241 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
242  MockA a;
243 
245  { // NOLINT
246  ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return());
247  },
248  ".WillByDefault() must appear exactly once in an ON_CALL()");
249 }
250 
251 // Tests that EXPECT_CALL evaluates its arguments exactly once as
252 // promised by Google Mock.
253 TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
254  MockA a;
255  MockA* pa = &a;
256 
257  EXPECT_CALL(*pa++, DoA(_));
258  a.DoA(0);
259  EXPECT_EQ(&a + 1, pa);
260 }
261 
262 TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
263  MockA a;
264  int n = 0;
265 
266  EXPECT_CALL(a, DoA(n++));
267  a.DoA(0);
268  EXPECT_EQ(1, n);
269 }
270 
271 // Tests that the syntax of EXPECT_CALL() is enforced at run time.
272 
273 TEST(ExpectCallSyntaxTest, WithIsOptional) {
274  MockA a;
275 
276  EXPECT_CALL(a, DoA(5)).Times(0);
277  EXPECT_CALL(a, DoA(6)).With(_).Times(0);
278 }
279 
280 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
281  MockA a;
282 
284  { // NOLINT
285  EXPECT_CALL(a, DoA(6)).With(_).With(_);
286  },
287  ".With() cannot appear more than once in an EXPECT_CALL()");
288 
289  a.DoA(6);
290 }
291 
292 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
293  MockA a;
294 
296  { // NOLINT
297  EXPECT_CALL(a, DoA(1)).Times(1).With(_);
298  },
299  ".With() must be the first clause in an EXPECT_CALL()");
300 
301  a.DoA(1);
302 
304  { // NOLINT
305  EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_);
306  },
307  ".With() must be the first clause in an EXPECT_CALL()");
308 
309  a.DoA(2);
310 }
311 
312 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
313  MockA a;
314 
315  EXPECT_CALL(a, DoA(1)).WillOnce(Return());
316 
317  EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
318 
319  a.DoA(1);
320  a.DoA(2);
321  a.DoA(2);
322 }
323 
324 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
325  MockA a;
326 
328  { // NOLINT
329  EXPECT_CALL(a, DoA(1)).Times(1).Times(2);
330  },
331  ".Times() cannot appear more than once in an EXPECT_CALL()");
332 
333  a.DoA(1);
334  a.DoA(1);
335 }
336 
337 TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
338  MockA a;
339  Sequence s;
340 
342  { // NOLINT
343  EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1);
344  },
345  ".Times() may only appear *before* ");
346 
347  a.DoA(1);
348 }
349 
350 TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
351  MockA a;
352  Sequence s;
353 
354  EXPECT_CALL(a, DoA(1));
355  EXPECT_CALL(a, DoA(2)).InSequence(s);
356 
357  a.DoA(1);
358  a.DoA(2);
359 }
360 
361 TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
362  MockA a;
363  Sequence s1, s2;
364 
365  EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1);
366 
367  a.DoA(1);
368 }
369 
370 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
371  MockA a;
372  Sequence s;
373 
374  Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber());
376  { // NOLINT
377  EXPECT_CALL(a, DoA(2)).After(e).InSequence(s);
378  },
379  ".InSequence() cannot appear after ");
380 
381  a.DoA(2);
382 }
383 
384 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
385  MockA a;
386  Sequence s;
387 
389  { // NOLINT
390  EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s);
391  },
392  ".InSequence() cannot appear after ");
393 
394  a.DoA(1);
395 }
396 
397 TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
398  MockA a;
399 
400  Expectation e = EXPECT_CALL(a, DoA(1));
402  { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); },
403  ".After() cannot appear after ");
404 
405  a.DoA(1);
406  a.DoA(2);
407 }
408 
409 TEST(ExpectCallSyntaxTest, WillIsOptional) {
410  MockA a;
411 
412  EXPECT_CALL(a, DoA(1));
413  EXPECT_CALL(a, DoA(2)).WillOnce(Return());
414 
415  a.DoA(1);
416  a.DoA(2);
417 }
418 
419 TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
420  MockA a;
421 
422  EXPECT_CALL(a, DoA(1))
423  .Times(AnyNumber())
424  .WillOnce(Return())
425  .WillOnce(Return())
426  .WillOnce(Return());
427 }
428 
429 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
430  MockA a;
431 
433  { // NOLINT
434  EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return());
435  },
436  ".WillOnce() cannot appear after ");
437 
438  a.DoA(1);
439 }
440 
441 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
442  MockA a;
443 
444  EXPECT_CALL(a, DoA(1)).WillOnce(Return());
445  EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
446 
447  a.DoA(1);
448  a.DoA(2);
449  a.DoA(2);
450 }
451 
452 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
453  MockA a;
454 
456  { // NOLINT
457  EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly(
458  Return());
459  },
460  ".WillRepeatedly() cannot appear more than once in an "
461  "EXPECT_CALL()");
462 }
463 
464 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
465  MockA a;
466 
468  { // NOLINT
469  EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return());
470  },
471  ".WillRepeatedly() cannot appear after ");
472 }
473 
474 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
475  MockA a;
476 
477  EXPECT_CALL(a, DoA(1));
478  EXPECT_CALL(a, DoA(1)).RetiresOnSaturation();
479 
480  a.DoA(1);
481  a.DoA(1);
482 }
483 
484 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
485  MockA a;
486 
488  { // NOLINT
489  EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation();
490  },
491  ".RetiresOnSaturation() cannot appear more than once");
492 
493  a.DoA(1);
494 }
495 
496 TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
497  {
498  MockA a;
499  EXPECT_CALL(a, DoA(1));
500  a.DoA(1);
501  }
503  { // NOLINT
504  MockA a;
505  EXPECT_CALL(a, DoA(1));
506  },
507  "to be called once");
509  { // NOLINT
510  MockA a;
511  EXPECT_CALL(a, DoA(1));
512  a.DoA(1);
513  a.DoA(1);
514  },
515  "to be called once");
516 }
517 
518 #if GTEST_HAS_STREAM_REDIRECTION
519 
520 // Tests that Google Mock doesn't print a warning when the number of
521 // WillOnce() is adequate.
522 TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
523  CaptureStdout();
524  {
525  MockB b;
526 
527  // It's always fine to omit WillOnce() entirely.
528  EXPECT_CALL(b, DoB()).Times(0);
529  EXPECT_CALL(b, DoB(1)).Times(AtMost(1));
530  EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1));
531 
532  // It's fine for the number of WillOnce()s to equal the upper bound.
533  EXPECT_CALL(b, DoB(3))
534  .Times(Between(1, 2))
535  .WillOnce(Return(1))
536  .WillOnce(Return(2));
537 
538  // It's fine for the number of WillOnce()s to be smaller than the
539  // upper bound when there is a WillRepeatedly().
540  EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly(
541  Return(2));
542 
543  // Satisfies the above expectations.
544  b.DoB(2);
545  b.DoB(3);
546  }
547  EXPECT_STREQ("", GetCapturedStdout().c_str());
548 }
549 
550 // Tests that Google Mock warns on having too many actions in an
551 // expectation compared to its cardinality.
552 TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
553  CaptureStdout();
554  {
555  MockB b;
556 
557  // Warns when the number of WillOnce()s is larger than the upper bound.
558  EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); // #1
559  EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce(
560  Return(2)); // #2
561  EXPECT_CALL(b, DoB(1))
562  .Times(1)
563  .WillOnce(Return(1))
564  .WillOnce(Return(2))
565  .RetiresOnSaturation(); // #3
566 
567  // Warns when the number of WillOnce()s equals the upper bound and
568  // there is a WillRepeatedly().
569  EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); // #4
570  EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly(
571  Return(2)); // #5
572 
573  // Satisfies the above expectations.
574  b.DoB(1);
575  b.DoB(2);
576  }
577  const std::string output = GetCapturedStdout();
579  "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
580  "Expected to be never called, but has 1 WillOnce().",
581  output); // #1
583  "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
584  "Expected to be called at most once, "
585  "but has 2 WillOnce()s.",
586  output); // #2
588  IsSubstring,
589  "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
590  "Expected to be called once, but has 2 WillOnce()s.",
591  output); // #3
593  "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
594  "Expected to be never called, but has 0 WillOnce()s "
595  "and a WillRepeatedly().",
596  output); // #4
598  IsSubstring,
599  "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
600  "Expected to be called once, but has 1 WillOnce() "
601  "and a WillRepeatedly().",
602  output); // #5
603 }
604 
605 // Tests that Google Mock warns on having too few actions in an
606 // expectation compared to its cardinality.
607 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
608  MockB b;
609 
610  EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1));
611 
612  CaptureStdout();
613  b.DoB();
614  const std::string output = GetCapturedStdout();
616  "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
617  "Expected to be called between 2 and 3 times, "
618  "but has only 1 WillOnce().",
619  output);
620  b.DoB();
621 }
622 
623 TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
624  int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);
625 
626  GMOCK_FLAG_SET(default_mock_behavior, kAllow);
627  CaptureStdout();
628  {
629  MockA a;
630  a.DoA(0);
631  }
632  std::string output = GetCapturedStdout();
633  EXPECT_TRUE(output.empty()) << output;
634 
635  GMOCK_FLAG_SET(default_mock_behavior, kWarn);
636  CaptureStdout();
637  {
638  MockA a;
639  a.DoA(0);
640  }
641  std::string warning_output = GetCapturedStdout();
642  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
643  EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
644  warning_output);
645 
646  GMOCK_FLAG_SET(default_mock_behavior, kFail);
648  {
649  MockA a;
650  a.DoA(0);
651  },
652  "Uninteresting mock function call");
653 
654  // Out of bounds values are converted to kWarn
655  GMOCK_FLAG_SET(default_mock_behavior, -1);
656  CaptureStdout();
657  {
658  MockA a;
659  a.DoA(0);
660  }
661  warning_output = GetCapturedStdout();
662  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
663  EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
664  warning_output);
665  GMOCK_FLAG_SET(default_mock_behavior, 3);
666  CaptureStdout();
667  {
668  MockA a;
669  a.DoA(0);
670  }
671  warning_output = GetCapturedStdout();
672  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
673  EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
674  warning_output);
675 
676  GMOCK_FLAG_SET(default_mock_behavior, original_behavior);
677 }
678 
679 #endif // GTEST_HAS_STREAM_REDIRECTION
680 
681 // Tests the semantics of ON_CALL().
682 
683 // Tests that the built-in default action is taken when no ON_CALL()
684 // is specified.
685 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
686  MockB b;
687  EXPECT_CALL(b, DoB());
688 
689  EXPECT_EQ(0, b.DoB());
690 }
691 
692 // Tests that the built-in default action is taken when no ON_CALL()
693 // matches the invocation.
694 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
695  MockB b;
696  ON_CALL(b, DoB(1)).WillByDefault(Return(1));
697  EXPECT_CALL(b, DoB(_));
698 
699  EXPECT_EQ(0, b.DoB(2));
700 }
701 
702 // Tests that the last matching ON_CALL() action is taken.
703 TEST(OnCallTest, PicksLastMatchingOnCall) {
704  MockB b;
705  ON_CALL(b, DoB(_)).WillByDefault(Return(3));
706  ON_CALL(b, DoB(2)).WillByDefault(Return(2));
707  ON_CALL(b, DoB(1)).WillByDefault(Return(1));
708  EXPECT_CALL(b, DoB(_));
709 
710  EXPECT_EQ(2, b.DoB(2));
711 }
712 
713 // Tests the semantics of EXPECT_CALL().
714 
715 // Tests that any call is allowed when no EXPECT_CALL() is specified.
716 TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
717  MockB b;
718  EXPECT_CALL(b, DoB());
719  // There is no expectation on DoB(int).
720 
721  b.DoB();
722 
723  // DoB(int) can be called any number of times.
724  b.DoB(1);
725  b.DoB(2);
726 }
727 
728 // Tests that the last matching EXPECT_CALL() fires.
729 TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
730  MockB b;
731  EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2));
732  EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1));
733 
734  EXPECT_EQ(1, b.DoB(1));
735 }
736 
737 // Tests lower-bound violation.
738 TEST(ExpectCallTest, CatchesTooFewCalls) {
740  { // NOLINT
741  MockB b;
742  EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2));
743 
744  b.DoB(5);
745  },
746  "Actual function \"DoB Method\" call count "
747  "doesn't match EXPECT_CALL(b, DoB(5))...\n"
748  " Expected: to be called at least twice\n"
749  " Actual: called once - unsatisfied and active");
750 }
751 
752 // Tests that the cardinality can be inferred when no Times(...) is
753 // specified.
754 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
755  {
756  MockB b;
757  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
758 
759  EXPECT_EQ(1, b.DoB());
760  EXPECT_EQ(2, b.DoB());
761  }
762 
764  { // NOLINT
765  MockB b;
766  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
767 
768  EXPECT_EQ(1, b.DoB());
769  },
770  "to be called twice");
771 
772  { // NOLINT
773  MockB b;
774  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
775 
776  EXPECT_EQ(1, b.DoB());
777  EXPECT_EQ(2, b.DoB());
778  EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
779  }
780 }
781 
782 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
783  {
784  MockB b;
785  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
786 
787  EXPECT_EQ(1, b.DoB());
788  }
789 
790  { // NOLINT
791  MockB b;
792  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
793 
794  EXPECT_EQ(1, b.DoB());
795  EXPECT_EQ(2, b.DoB());
796  EXPECT_EQ(2, b.DoB());
797  }
798 
800  { // NOLINT
801  MockB b;
802  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
803  },
804  "to be called at least once");
805 }
806 
807 #if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \
808  GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L
809 
810 // It should be possible to return a non-moveable type from a mock action in
811 // C++17 and above, where it's guaranteed that such a type can be initialized
812 // from a prvalue returned from a function.
813 TEST(ExpectCallTest, NonMoveableType) {
814  // Define a non-moveable result type.
815  struct NonMoveableStruct {
816  explicit NonMoveableStruct(int x_in) : x(x_in) {}
817  NonMoveableStruct(NonMoveableStruct&&) = delete;
818 
819  int x;
820  };
821 
822  static_assert(!std::is_move_constructible_v<NonMoveableStruct>);
823  static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);
824 
825  static_assert(!std::is_move_assignable_v<NonMoveableStruct>);
826  static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);
827 
828  // We should be able to use a callable that returns that result as both a
829  // OnceAction and an Action, whether the callable ignores arguments or not.
830  const auto return_17 = [] { return NonMoveableStruct(17); };
831 
832  static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});
833  static_cast<void>(Action<NonMoveableStruct()>{return_17});
834 
835  static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});
836  static_cast<void>(Action<NonMoveableStruct(int)>{return_17});
837 
838  // It should be possible to return the result end to end through an
839  // EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
840  MockFunction<NonMoveableStruct()> mock;
841  EXPECT_CALL(mock, Call) //
842  .WillOnce(return_17) //
843  .WillRepeatedly(return_17);
844 
845  EXPECT_EQ(17, mock.AsStdFunction()().x);
846  EXPECT_EQ(17, mock.AsStdFunction()().x);
847  EXPECT_EQ(17, mock.AsStdFunction()().x);
848 }
849 
850 #endif // C++17 and above
851 
852 // Tests that the n-th action is taken for the n-th matching
853 // invocation.
854 TEST(ExpectCallTest, NthMatchTakesNthAction) {
855  MockB b;
856  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(
857  Return(3));
858 
859  EXPECT_EQ(1, b.DoB());
860  EXPECT_EQ(2, b.DoB());
861  EXPECT_EQ(3, b.DoB());
862 }
863 
864 // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
865 // list is exhausted.
866 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
867  MockB b;
868  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
869 
870  EXPECT_EQ(1, b.DoB());
871  EXPECT_EQ(2, b.DoB());
872  EXPECT_EQ(2, b.DoB());
873 }
874 
875 #if GTEST_HAS_STREAM_REDIRECTION
876 
877 // Tests that the default action is taken when the WillOnce(...) list is
878 // exhausted and there is no WillRepeatedly().
879 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
880  MockB b;
881  EXPECT_CALL(b, DoB(_)).Times(1);
882  EXPECT_CALL(b, DoB())
883  .Times(AnyNumber())
884  .WillOnce(Return(1))
885  .WillOnce(Return(2));
886 
887  CaptureStdout();
888  EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
889  // expectation has no action clause at all.
890  EXPECT_EQ(1, b.DoB());
891  EXPECT_EQ(2, b.DoB());
892  const std::string output1 = GetCapturedStdout();
893  EXPECT_STREQ("", output1.c_str());
894 
895  CaptureStdout();
896  EXPECT_EQ(0, b.DoB());
897  EXPECT_EQ(0, b.DoB());
898  const std::string output2 = GetCapturedStdout();
899  EXPECT_THAT(output2.c_str(),
900  HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
901  "Called 3 times, but only 2 WillOnce()s are specified"
902  " - returning default value."));
903  EXPECT_THAT(output2.c_str(),
904  HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
905  "Called 4 times, but only 2 WillOnce()s are specified"
906  " - returning default value."));
907 }
908 
909 TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) {
910  MockB b;
911  std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
912  EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
913 
914  EXPECT_EQ(1, b.DoB());
915 
916  CaptureStdout();
917  EXPECT_EQ(0, b.DoB());
918  const std::string output = GetCapturedStdout();
919  // The warning message should contain the call location.
920  EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
921 }
922 
923 TEST(FunctionMockerMessageTest,
924  ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
925  std::string on_call_location;
926  CaptureStdout();
927  {
928  NaggyMock<MockB> b;
929  on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
930  ON_CALL(b, DoB(_)).WillByDefault(Return(0));
931  b.DoB(0);
932  }
933  EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
934 }
935 
936 #endif // GTEST_HAS_STREAM_REDIRECTION
937 
938 // Tests that an uninteresting call performs the default action.
939 TEST(UninterestingCallTest, DoesDefaultAction) {
940  // When there is an ON_CALL() statement, the action specified by it
941  // should be taken.
942  MockA a;
943  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
944  EXPECT_TRUE(a.Binary(1, 2));
945 
946  // When there is no ON_CALL(), the default value for the return type
947  // should be returned.
948  MockB b;
949  EXPECT_EQ(0, b.DoB());
950 }
951 
952 // Tests that an unexpected call performs the default action.
953 TEST(UnexpectedCallTest, DoesDefaultAction) {
954  // When there is an ON_CALL() statement, the action specified by it
955  // should be taken.
956  MockA a;
957  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
958  EXPECT_CALL(a, Binary(0, 0));
959  a.Binary(0, 0);
960  bool result = false;
961  EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
962  "Unexpected mock function call");
963  EXPECT_TRUE(result);
964 
965  // When there is no ON_CALL(), the default value for the return type
966  // should be returned.
967  MockB b;
968  EXPECT_CALL(b, DoB(0)).Times(0);
969  int n = -1;
970  EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call");
971  EXPECT_EQ(0, n);
972 }
973 
974 // Tests that when an unexpected void function generates the right
975 // failure message.
976 TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
977  // First, tests the message when there is only one EXPECT_CALL().
978  MockA a1;
979  EXPECT_CALL(a1, DoA(1));
980  a1.DoA(1);
981  // Ideally we should match the failure message against a regex, but
982  // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
983  // multiple sub-strings instead.
985  a1.DoA(9),
986  "Unexpected mock function call - returning directly.\n"
987  " Function call: DoA(9)\n"
988  "Google Mock tried the following 1 expectation, but it didn't match:");
990  a1.DoA(9),
991  " Expected arg #0: is equal to 1\n"
992  " Actual: 9\n"
993  " Expected: to be called once\n"
994  " Actual: called once - saturated and active");
995 
996  // Next, tests the message when there are more than one EXPECT_CALL().
997  MockA a2;
998  EXPECT_CALL(a2, DoA(1));
999  EXPECT_CALL(a2, DoA(3));
1000  a2.DoA(1);
1002  a2.DoA(2),
1003  "Unexpected mock function call - returning directly.\n"
1004  " Function call: DoA(2)\n"
1005  "Google Mock tried the following 2 expectations, but none matched:");
1007  a2.DoA(2),
1008  "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1009  " Expected arg #0: is equal to 1\n"
1010  " Actual: 2\n"
1011  " Expected: to be called once\n"
1012  " Actual: called once - saturated and active");
1014  a2.DoA(2),
1015  "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1016  " Expected arg #0: is equal to 3\n"
1017  " Actual: 2\n"
1018  " Expected: to be called once\n"
1019  " Actual: never called - unsatisfied and active");
1020  a2.DoA(3);
1021 }
1022 
1023 // Tests that an unexpected non-void function generates the right
1024 // failure message.
1025 TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1026  MockB b1;
1027  EXPECT_CALL(b1, DoB(1));
1028  b1.DoB(1);
1030  b1.DoB(2),
1031  "Unexpected mock function call - returning default value.\n"
1032  " Function call: DoB(2)\n"
1033  " Returns: 0\n"
1034  "Google Mock tried the following 1 expectation, but it didn't match:");
1036  b1.DoB(2),
1037  " Expected arg #0: is equal to 1\n"
1038  " Actual: 2\n"
1039  " Expected: to be called once\n"
1040  " Actual: called once - saturated and active");
1041 }
1042 
1043 // Tests that Google Mock explains that an retired expectation doesn't
1044 // match the call.
1045 TEST(UnexpectedCallTest, RetiredExpectation) {
1046  MockB b;
1047  EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();
1048 
1049  b.DoB(1);
1050  EXPECT_NONFATAL_FAILURE(b.DoB(1),
1051  " Expected: the expectation is active\n"
1052  " Actual: it is retired");
1053 }
1054 
1055 // Tests that Google Mock explains that an expectation that doesn't
1056 // match the arguments doesn't match the call.
1057 TEST(UnexpectedCallTest, UnmatchedArguments) {
1058  MockB b;
1059  EXPECT_CALL(b, DoB(1));
1060 
1061  EXPECT_NONFATAL_FAILURE(b.DoB(2),
1062  " Expected arg #0: is equal to 1\n"
1063  " Actual: 2\n");
1064  b.DoB(1);
1065 }
1066 
1067 // Tests that Google Mock explains that an expectation with
1068 // unsatisfied pre-requisites doesn't match the call.
1069 TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {
1070  Sequence s1, s2;
1071  MockB b;
1072  EXPECT_CALL(b, DoB(1)).InSequence(s1);
1073  EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);
1074  EXPECT_CALL(b, DoB(3)).InSequence(s2);
1075  EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);
1076 
1077  ::testing::TestPartResultArray failures;
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);
1088  EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1089 
1090  // Verifies that the failure message contains the two unsatisfied
1091  // pre-requisites but not the satisfied one.
1092 #ifdef GTEST_USES_POSIX_RE
1093  EXPECT_THAT(r.message(),
1094  ContainsRegex(
1095  // POSIX RE doesn't understand the (?s) prefix, but has no
1096  // trouble with (.|\n).
1097  "the following immediate pre-requisites are not satisfied:\n"
1098  "(.|\n)*: pre-requisite #0\n"
1099  "(.|\n)*: pre-requisite #1"));
1100 #else
1101  // We can only use Google Test's own simple regex.
1102  EXPECT_THAT(r.message(),
1103  ContainsRegex(
1104  "the following immediate pre-requisites are not satisfied:"));
1105  EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1106  EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1107 #endif // GTEST_USES_POSIX_RE
1108 
1109  b.DoB(1);
1110  b.DoB(3);
1111  b.DoB(4);
1112 }
1113 
1114 TEST(UndefinedReturnValueTest,
1115  ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1116  MockA a;
1117  // FIXME: We should really verify the output message,
1118  // but we cannot yet due to that EXPECT_DEATH only captures stderr
1119  // while Google Mock logs to stdout.
1120 #if GTEST_HAS_EXCEPTIONS
1121  EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1122 #else
1123  EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1124 #endif
1125 }
1126 
1127 // Tests that an excessive call (one whose arguments match the
1128 // matchers but is called too many times) performs the default action.
1129 TEST(ExcessiveCallTest, DoesDefaultAction) {
1130  // When there is an ON_CALL() statement, the action specified by it
1131  // should be taken.
1132  MockA a;
1133  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
1134  EXPECT_CALL(a, Binary(0, 0));
1135  a.Binary(0, 0);
1136  bool result = false;
1137  EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1138  "Mock function called more times than expected");
1139  EXPECT_TRUE(result);
1140 
1141  // When there is no ON_CALL(), the default value for the return type
1142  // should be returned.
1143  MockB b;
1144  EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0);
1145  int n = -1;
1147  n = b.DoB(0),
1148  "Mock function \"DoB Method\" called more times than expected");
1149  EXPECT_EQ(0, n);
1150 }
1151 
1152 // Tests that when a void function is called too many times,
1153 // the failure message contains the argument values.
1154 TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1155  MockA a;
1156  EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0);
1158  a.DoA(9),
1159  "Mock function \"DoA Method\" called more times than expected - "
1160  "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.
1168 TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1169  MockB b;
1170  EXPECT_CALL(b, DoB(_));
1171  b.DoB(1);
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 
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 
1194  { // NOLINT
1195  a.DoA(2);
1196  },
1197  "Unexpected mock function call");
1198 
1199  a.DoA(1);
1200  a.DoA(2);
1201 }
1202 
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 
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 
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 
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.
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.
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.
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:
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 
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 
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 
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 
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 
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 
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 
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 
1436 TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1437  ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1438 }
1439 
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 
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 
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 
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 
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 
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 
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().
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().
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.
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.
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().
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.
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.
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.
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.
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.
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.
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.
1775 
1776 ACTION_P(Delete, ptr) { delete ptr; }
1777 
1779 
1780 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1781  MockA* const a = new MockA;
1782  EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1783  a->DoA(42); // This will cause a to be deleted.
1784 }
1785 
1786 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1787  MockA* const a = new MockA;
1788  EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));
1789  a->ReturnResult(42); // This will cause a to be deleted.
1790 }
1791 
1792 // Tests that calls that violate the original spec yield failures.
1793 TEST(DeletingMockEarlyTest, Failure1) {
1794  MockB* const b1 = new MockB;
1795  MockA* const a = new MockA;
1796  MockB* const b2 = new MockB;
1797 
1798  {
1799  InSequence dummy;
1800  EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
1801  EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
1802  EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
1803  }
1804 
1805  delete a; // a is trivially satisfied.
1806  EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call");
1807  EXPECT_EQ(1, b1->DoB(1));
1808  delete b1;
1809  delete b2;
1810 }
1811 
1812 // Tests that calls that violate the original spec yield failures.
1813 TEST(DeletingMockEarlyTest, Failure2) {
1814  MockB* const b1 = new MockB;
1815  MockA* const a = new MockA;
1816  MockB* const b2 = new MockB;
1817 
1818  {
1819  InSequence dummy;
1820  EXPECT_CALL(*b1, DoB(_));
1821  EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
1822  EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());
1823  }
1824 
1825  EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called");
1826  EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call");
1827  EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call");
1828  delete a;
1829  delete b2;
1830 }
1831 
1832 class EvenNumberCardinality : public CardinalityInterface {
1833  public:
1834  // Returns true if and only if call_count calls will satisfy this
1835  // cardinality.
1836  bool IsSatisfiedByCallCount(int call_count) const override {
1837  return call_count % 2 == 0;
1838  }
1839 
1840  // Returns true if and only if call_count calls will saturate this
1841  // cardinality.
1842  bool IsSaturatedByCallCount(int /* call_count */) const override {
1843  return false;
1844  }
1845 
1846  // Describes self to an ostream.
1847  void DescribeTo(::std::ostream* os) const override {
1848  *os << "called even number of times";
1849  }
1850 };
1851 
1852 Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }
1853 
1854 TEST(ExpectationBaseTest,
1855  AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1856  MockA* a = new MockA;
1857  Sequence s;
1858 
1859  EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);
1860  EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);
1861  EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());
1862 
1863  a->DoA(3);
1864  a->DoA(1);
1865  EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1866  EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1867 }
1868 
1869 // The following tests verify the message generated when a mock
1870 // function is called.
1871 
1872 struct Printable {};
1873 
1874 inline void operator<<(::std::ostream& os, const Printable&) {
1875  os << "Printable";
1876 }
1877 
1878 struct Unprintable {
1879  Unprintable() : value(0) {}
1880  int value;
1881 };
1882 
1883 class MockC {
1884  public:
1885  MockC() = default;
1886 
1887  MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
1888  const Printable& x, Unprintable y));
1889  MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
1890 
1891  private:
1892  MockC(const MockC&) = delete;
1893  MockC& operator=(const MockC&) = delete;
1894 };
1895 
1896 class VerboseFlagPreservingFixture : public testing::Test {
1897  protected:
1898  VerboseFlagPreservingFixture()
1899  : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}
1900 
1901  ~VerboseFlagPreservingFixture() override {
1903  }
1904 
1905  private:
1906  const std::string saved_verbose_flag_;
1907 
1908  VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;
1909  VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =
1910  delete;
1911 };
1912 
1913 #if GTEST_HAS_STREAM_REDIRECTION
1914 
1915 // Tests that an uninteresting mock function call on a naggy mock
1916 // generates a warning without the stack trace when
1917 // --gmock_verbose=warning is specified.
1918 TEST(FunctionCallMessageTest,
1919  UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
1921  NaggyMock<MockC> c;
1922  CaptureStdout();
1923  c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1924  const std::string output = GetCapturedStdout();
1925  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1926  EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
1927 }
1928 
1929 // Tests that an uninteresting mock function call on a naggy mock
1930 // generates a warning containing the stack trace when
1931 // --gmock_verbose=info is specified.
1932 TEST(FunctionCallMessageTest,
1933  UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
1934  GMOCK_FLAG_SET(verbose, kInfoVerbosity);
1935  NaggyMock<MockC> c;
1936  CaptureStdout();
1937  c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1938  const std::string output = GetCapturedStdout();
1939  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1940  EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
1941 
1942 #ifndef NDEBUG
1943 
1944  // We check the stack trace content in dbg-mode only, as opt-mode
1945  // may inline the call we are interested in seeing.
1946 
1947  // Verifies that a void mock function's name appears in the stack
1948  // trace.
1949  EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
1950 
1951  // Verifies that a non-void mock function's name appears in the
1952  // stack trace.
1953  CaptureStdout();
1954  c.NonVoidMethod();
1955  const std::string output2 = GetCapturedStdout();
1956  EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
1957 
1958 #endif // NDEBUG
1959 }
1960 
1961 // Tests that an uninteresting mock function call on a naggy mock
1962 // causes the function arguments and return value to be printed.
1963 TEST(FunctionCallMessageTest,
1964  UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
1965  // A non-void mock function.
1966  NaggyMock<MockB> b;
1967  CaptureStdout();
1968  b.DoB();
1969  const std::string output1 = GetCapturedStdout();
1971  IsSubstring,
1972  "Uninteresting mock function call - returning default value.\n"
1973  " Function call: DoB()\n"
1974  " Returns: 0\n",
1975  output1.c_str());
1976  // Makes sure the return value is printed.
1977 
1978  // A void mock function.
1979  NaggyMock<MockC> c;
1980  CaptureStdout();
1981  c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1982  const std::string output2 = GetCapturedStdout();
1983  EXPECT_THAT(
1984  output2.c_str(),
1985  ContainsRegex("Uninteresting mock function call - returning directly\\.\n"
1986  " Function call: VoidMethod"
1987  "\\(false, 5, \"Hi\", NULL, @.+ "
1988  "Printable, 4-byte object <00-00 00-00>\\)"));
1989  // A void function has no return value to print.
1990 }
1991 
1992 // Tests how the --gmock_verbose flag affects Google Mock's output.
1993 
1994 class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
1995  public:
1996  // Verifies that the given Google Mock output is correct. (When
1997  // should_print is true, the output should match the given regex and
1998  // contain the given function name in the stack trace. When it's
1999  // false, the output should be empty.)
2000  void VerifyOutput(const std::string& output, bool should_print,
2001  const std::string& expected_substring,
2002  const std::string& function_name) {
2003  if (should_print) {
2004  EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2005 #ifndef NDEBUG
2006  // We check the stack trace content in dbg-mode only, as opt-mode
2007  // may inline the call we are interested in seeing.
2008  EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2009 #else
2010  // Suppresses 'unused function parameter' warnings.
2011  static_cast<void>(function_name);
2012 #endif // NDEBUG
2013  } else {
2014  EXPECT_STREQ("", output.c_str());
2015  }
2016  }
2017 
2018  // Tests how the flag affects expected calls.
2019  void TestExpectedCall(bool should_print) {
2020  MockA a;
2021  EXPECT_CALL(a, DoA(5));
2022  EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));
2023 
2024  // A void-returning function.
2025  CaptureStdout();
2026  a.DoA(5);
2027  VerifyOutput(GetCapturedStdout(), should_print,
2028  "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2029  " Function call: DoA(5)\n"
2030  "Stack trace:\n",
2031  "DoA");
2032 
2033  // A non-void-returning function.
2034  CaptureStdout();
2035  a.Binary(2, 1);
2036  VerifyOutput(GetCapturedStdout(), should_print,
2037  "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2038  " Function call: Binary(2, 1)\n"
2039  " Returns: true\n"
2040  "Stack trace:\n",
2041  "Binary");
2042  }
2043 
2044  // Tests how the flag affects uninteresting calls on a naggy mock.
2045  void TestUninterestingCallOnNaggyMock(bool should_print) {
2046  NaggyMock<MockA> a;
2047  const std::string note =
2048  "NOTE: You can safely ignore the above warning unless this "
2049  "call should not happen. Do not suppress it by blindly adding "
2050  "an EXPECT_CALL() if you don't mean to enforce the call. "
2051  "See "
2052  "https://github.com/google/googletest/blob/main/docs/"
2053  "gmock_cook_book.md#"
2054  "knowing-when-to-expect-useoncall for details.";
2055 
2056  // A void-returning function.
2057  CaptureStdout();
2058  a.DoA(5);
2059  VerifyOutput(GetCapturedStdout(), should_print,
2060  "\nGMOCK WARNING:\n"
2061  "Uninteresting mock function call - returning directly.\n"
2062  " Function call: DoA(5)\n" +
2063  note,
2064  "DoA");
2065 
2066  // A non-void-returning function.
2067  CaptureStdout();
2068  a.Binary(2, 1);
2069  VerifyOutput(GetCapturedStdout(), should_print,
2070  "\nGMOCK WARNING:\n"
2071  "Uninteresting mock function call - returning default value.\n"
2072  " Function call: Binary(2, 1)\n"
2073  " Returns: false\n" +
2074  note,
2075  "Binary");
2076  }
2077 };
2078 
2079 // Tests that --gmock_verbose=info causes both expected and
2080 // uninteresting calls to be reported.
2081 TEST_F(GMockVerboseFlagTest, Info) {
2082  GMOCK_FLAG_SET(verbose, kInfoVerbosity);
2083  TestExpectedCall(true);
2084  TestUninterestingCallOnNaggyMock(true);
2085 }
2086 
2087 // Tests that --gmock_verbose=warning causes uninteresting calls to be
2088 // reported.
2089 TEST_F(GMockVerboseFlagTest, Warning) {
2091  TestExpectedCall(false);
2092  TestUninterestingCallOnNaggyMock(true);
2093 }
2094 
2095 // Tests that --gmock_verbose=warning causes neither expected nor
2096 // uninteresting calls to be reported.
2097 TEST_F(GMockVerboseFlagTest, Error) {
2098  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2099  TestExpectedCall(false);
2100  TestUninterestingCallOnNaggyMock(false);
2101 }
2102 
2103 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2104 // as --gmock_verbose=warning.
2105 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2106  GMOCK_FLAG_SET(verbose, "invalid"); // Treated as "warning".
2107  TestExpectedCall(false);
2108  TestUninterestingCallOnNaggyMock(true);
2109 }
2110 
2111 #endif // GTEST_HAS_STREAM_REDIRECTION
2112 
2113 // A helper class that generates a failure when printed. We use it to
2114 // ensure that Google Mock doesn't print a value (even to an internal
2115 // buffer) when it is not supposed to do so.
2116 class PrintMeNot {};
2117 
2118 void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2119  ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2120  << "printed even to an internal buffer.";
2121 }
2122 
2123 class LogTestHelper {
2124  public:
2125  LogTestHelper() = default;
2126 
2127  MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2128 
2129  private:
2130  LogTestHelper(const LogTestHelper&) = delete;
2131  LogTestHelper& operator=(const LogTestHelper&) = delete;
2132 };
2133 
2134 class GMockLogTest : public VerboseFlagPreservingFixture {
2135  protected:
2136  LogTestHelper helper_;
2137 };
2138 
2139 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2141  EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
2142  helper_.Foo(PrintMeNot()); // This is an expected call.
2143 }
2144 
2145 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2146  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2147  EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
2148  helper_.Foo(PrintMeNot()); // This is an expected call.
2149 }
2150 
2151 TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2152  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2153  ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));
2154  helper_.Foo(PrintMeNot()); // This should generate a warning.
2155 }
2156 
2157 // Tests Mock::AllowLeak().
2158 
2159 TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2160  MockA* a = new MockA;
2161  Mock::AllowLeak(a);
2162 }
2163 
2164 TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2165  MockA* a = new MockA;
2166  Mock::AllowLeak(a);
2167  ON_CALL(*a, DoA(_)).WillByDefault(Return());
2168  a->DoA(0);
2169 }
2170 
2171 TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2172  MockA* a = new MockA;
2173  ON_CALL(*a, DoA(_)).WillByDefault(Return());
2174  Mock::AllowLeak(a);
2175 }
2176 
2177 TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2178  MockA* a = new MockA;
2179  Mock::AllowLeak(a);
2180  EXPECT_CALL(*a, DoA(_));
2181  a->DoA(0);
2182 }
2183 
2184 TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2185  MockA* a = new MockA;
2186  EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2187  Mock::AllowLeak(a);
2188 }
2189 
2190 TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2191  MockA* a = new MockA;
2192  ON_CALL(*a, DoA(_)).WillByDefault(Return());
2193  EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2194  Mock::AllowLeak(a);
2195 }
2196 
2197 // Tests that we can verify and clear a mock object's expectations
2198 // when none of its methods has expectations.
2199 TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2200  MockB b;
2201  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2202 
2203  // There should be no expectations on the methods now, so we can
2204  // freely call them.
2205  EXPECT_EQ(0, b.DoB());
2206  EXPECT_EQ(0, b.DoB(1));
2207 }
2208 
2209 // Tests that we can verify and clear a mock object's expectations
2210 // when some, but not all, of its methods have expectations *and* the
2211 // verification succeeds.
2212 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2213  MockB b;
2214  EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2215  b.DoB();
2216  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2217 
2218  // There should be no expectations on the methods now, so we can
2219  // freely call them.
2220  EXPECT_EQ(0, b.DoB());
2221  EXPECT_EQ(0, b.DoB(1));
2222 }
2223 
2224 // Tests that we can verify and clear a mock object's expectations
2225 // when some, but not all, of its methods have expectations *and* the
2226 // verification fails.
2227 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2228  MockB b;
2229  EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2230  bool result = true;
2231  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2232  "Actual: never called");
2233  ASSERT_FALSE(result);
2234 
2235  // There should be no expectations on the methods now, so we can
2236  // freely call them.
2237  EXPECT_EQ(0, b.DoB());
2238  EXPECT_EQ(0, b.DoB(1));
2239 }
2240 
2241 // Tests that we can verify and clear a mock object's expectations
2242 // when all of its methods have expectations.
2243 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2244  MockB b;
2245  EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2246  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2247  b.DoB();
2248  b.DoB(1);
2249  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2250 
2251  // There should be no expectations on the methods now, so we can
2252  // freely call them.
2253  EXPECT_EQ(0, b.DoB());
2254  EXPECT_EQ(0, b.DoB(1));
2255 }
2256 
2257 // Tests that we can verify and clear a mock object's expectations
2258 // when a method has more than one expectation.
2259 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2260  MockB b;
2261  EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));
2262  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2263  b.DoB(1);
2264  bool result = true;
2265  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2266  "Actual: never called");
2267  ASSERT_FALSE(result);
2268 
2269  // There should be no expectations on the methods now, so we can
2270  // freely call them.
2271  EXPECT_EQ(0, b.DoB());
2272  EXPECT_EQ(0, b.DoB(1));
2273 }
2274 
2275 // Tests that we can call VerifyAndClearExpectations() on the same
2276 // mock object multiple times.
2277 TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2278  MockB b;
2279  EXPECT_CALL(b, DoB());
2280  b.DoB();
2281  Mock::VerifyAndClearExpectations(&b);
2282 
2283  EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));
2284  b.DoB(1);
2285  Mock::VerifyAndClearExpectations(&b);
2286  Mock::VerifyAndClearExpectations(&b);
2287 
2288  // There should be no expectations on the methods now, so we can
2289  // freely call them.
2290  EXPECT_EQ(0, b.DoB());
2291  EXPECT_EQ(0, b.DoB(1));
2292 }
2293 
2294 // Tests that we can clear a mock object's default actions when none
2295 // of its methods has default actions.
2296 TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2297  MockB b;
2298  // If this crashes or generates a failure, the test will catch it.
2299  Mock::VerifyAndClear(&b);
2300  EXPECT_EQ(0, b.DoB());
2301 }
2302 
2303 // Tests that we can clear a mock object's default actions when some,
2304 // but not all of its methods have default actions.
2305 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2306  MockB b;
2307  ON_CALL(b, DoB()).WillByDefault(Return(1));
2308 
2309  Mock::VerifyAndClear(&b);
2310 
2311  // Verifies that the default action of int DoB() was removed.
2312  EXPECT_EQ(0, b.DoB());
2313 }
2314 
2315 // Tests that we can clear a mock object's default actions when all of
2316 // its methods have default actions.
2317 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2318  MockB b;
2319  ON_CALL(b, DoB()).WillByDefault(Return(1));
2320  ON_CALL(b, DoB(_)).WillByDefault(Return(2));
2321 
2322  Mock::VerifyAndClear(&b);
2323 
2324  // Verifies that the default action of int DoB() was removed.
2325  EXPECT_EQ(0, b.DoB());
2326 
2327  // Verifies that the default action of int DoB(int) was removed.
2328  EXPECT_EQ(0, b.DoB(0));
2329 }
2330 
2331 // Tests that we can clear a mock object's default actions when a
2332 // method has more than one ON_CALL() set on it.
2333 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2334  MockB b;
2335  ON_CALL(b, DoB(0)).WillByDefault(Return(1));
2336  ON_CALL(b, DoB(_)).WillByDefault(Return(2));
2337 
2338  Mock::VerifyAndClear(&b);
2339 
2340  // Verifies that the default actions (there are two) of int DoB(int)
2341  // were removed.
2342  EXPECT_EQ(0, b.DoB(0));
2343  EXPECT_EQ(0, b.DoB(1));
2344 }
2345 
2346 // Tests that we can call VerifyAndClear() on a mock object multiple
2347 // times.
2348 TEST(VerifyAndClearTest, CanCallManyTimes) {
2349  MockB b;
2350  ON_CALL(b, DoB()).WillByDefault(Return(1));
2351  Mock::VerifyAndClear(&b);
2352  Mock::VerifyAndClear(&b);
2353 
2354  ON_CALL(b, DoB(_)).WillByDefault(Return(1));
2355  Mock::VerifyAndClear(&b);
2356 
2357  EXPECT_EQ(0, b.DoB());
2358  EXPECT_EQ(0, b.DoB(1));
2359 }
2360 
2361 // Tests that VerifyAndClear() works when the verification succeeds.
2362 TEST(VerifyAndClearTest, Success) {
2363  MockB b;
2364  ON_CALL(b, DoB()).WillByDefault(Return(1));
2365  EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));
2366 
2367  b.DoB();
2368  b.DoB(1);
2369  ASSERT_TRUE(Mock::VerifyAndClear(&b));
2370 
2371  // There should be no expectations on the methods now, so we can
2372  // freely call them.
2373  EXPECT_EQ(0, b.DoB());
2374  EXPECT_EQ(0, b.DoB(1));
2375 }
2376 
2377 // Tests that VerifyAndClear() works when the verification fails.
2378 TEST(VerifyAndClearTest, Failure) {
2379  MockB b;
2380  ON_CALL(b, DoB(_)).WillByDefault(Return(1));
2381  EXPECT_CALL(b, DoB()).WillOnce(Return(2));
2382 
2383  b.DoB(1);
2384  bool result = true;
2385  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2386  "Actual: never called");
2387  ASSERT_FALSE(result);
2388 
2389  // There should be no expectations on the methods now, so we can
2390  // freely call them.
2391  EXPECT_EQ(0, b.DoB());
2392  EXPECT_EQ(0, b.DoB(1));
2393 }
2394 
2395 // Tests that VerifyAndClear() works when the default actions and
2396 // expectations are set on a const mock object.
2397 TEST(VerifyAndClearTest, Const) {
2398  MockB b;
2399  ON_CALL(Const(b), DoB()).WillByDefault(Return(1));
2400 
2401  EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));
2402 
2403  b.DoB();
2404  b.DoB();
2405  ASSERT_TRUE(Mock::VerifyAndClear(&b));
2406 
2407  // There should be no expectations on the methods now, so we can
2408  // freely call them.
2409  EXPECT_EQ(0, b.DoB());
2410  EXPECT_EQ(0, b.DoB(1));
2411 }
2412 
2413 // Tests that we can set default actions and expectations on a mock
2414 // object after VerifyAndClear() has been called on it.
2415 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2416  MockB b;
2417  ON_CALL(b, DoB()).WillByDefault(Return(1));
2418  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2419  b.DoB(1);
2420 
2421  Mock::VerifyAndClear(&b);
2422 
2423  EXPECT_CALL(b, DoB()).WillOnce(Return(3));
2424  ON_CALL(b, DoB(_)).WillByDefault(Return(4));
2425 
2426  EXPECT_EQ(3, b.DoB());
2427  EXPECT_EQ(4, b.DoB(1));
2428 }
2429 
2430 // Tests that calling VerifyAndClear() on one mock object does not
2431 // affect other mock objects (either of the same type or not).
2432 TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2433  MockA a;
2434  MockB b1;
2435  MockB b2;
2436 
2437  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
2438  EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));
2439 
2440  ON_CALL(b1, DoB()).WillByDefault(Return(1));
2441  EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));
2442 
2443  ON_CALL(b2, DoB()).WillByDefault(Return(3));
2444  EXPECT_CALL(b2, DoB(_));
2445 
2446  b2.DoB(0);
2447  Mock::VerifyAndClear(&b2);
2448 
2449  // Verifies that the default actions and expectations of a and b1
2450  // are still in effect.
2451  EXPECT_TRUE(a.Binary(0, 0));
2452  EXPECT_FALSE(a.Binary(0, 0));
2453 
2454  EXPECT_EQ(1, b1.DoB());
2455  EXPECT_EQ(2, b1.DoB(0));
2456 }
2457 
2458 TEST(VerifyAndClearTest,
2459  DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2460  std::shared_ptr<MockA> a(new MockA);
2461  ReferenceHoldingMock test_mock;
2462 
2463  // EXPECT_CALL stores a reference to a inside test_mock.
2464  EXPECT_CALL(test_mock, AcceptReference(_))
2465  .WillRepeatedly(SetArgPointee<0>(a));
2466 
2467  // Throw away the reference to the mock that we have in a. After this, the
2468  // only reference to it is stored by test_mock.
2469  a.reset();
2470 
2471  // When test_mock goes out of scope, it destroys the last remaining reference
2472  // to the mock object originally pointed to by a. This will cause the MockA
2473  // destructor to be called from inside the ReferenceHoldingMock destructor.
2474  // The state of all mocks is protected by a single global lock, but there
2475  // should be no deadlock.
2476 }
2477 
2478 TEST(VerifyAndClearTest,
2479  DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2480  std::shared_ptr<MockA> a(new MockA);
2481  ReferenceHoldingMock test_mock;
2482 
2483  // ON_CALL stores a reference to a inside test_mock.
2484  ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));
2485 
2486  // Throw away the reference to the mock that we have in a. After this, the
2487  // only reference to it is stored by test_mock.
2488  a.reset();
2489 
2490  // When test_mock goes out of scope, it destroys the last remaining reference
2491  // to the mock object originally pointed to by a. This will cause the MockA
2492  // destructor to be called from inside the ReferenceHoldingMock destructor.
2493  // The state of all mocks is protected by a single global lock, but there
2494  // should be no deadlock.
2495 }
2496 
2497 // Tests that a mock function's action can call a mock function
2498 // (either the same function or a different one) either as an explicit
2499 // action or as a default action without causing a dead lock. It
2500 // verifies that the action is not performed inside the critical
2501 // section.
2502 TEST(SynchronizationTest, CanCallMockMethodInAction) {
2503  MockA a;
2504  MockC c;
2505  ON_CALL(a, DoA(_)).WillByDefault(
2506  IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));
2507  EXPECT_CALL(a, DoA(1));
2508  EXPECT_CALL(a, DoA(1))
2509  .WillOnce(Invoke(&a, &MockA::DoA))
2510  .RetiresOnSaturation();
2511  EXPECT_CALL(c, NonVoidMethod());
2512 
2513  a.DoA(1);
2514  // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2515  // which will in turn match the first EXPECT_CALL() and trigger a call to
2516  // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2517  // EXPECT_CALL() did not specify an action.
2518 }
2519 
2520 TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
2521  MockA a;
2522  int do_a_arg0 = 0;
2523  ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
2524  int do_a_47_arg0 = 0;
2525  ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
2526 
2527  a.DoA(17);
2528  EXPECT_THAT(do_a_arg0, 17);
2529  EXPECT_THAT(do_a_47_arg0, 0);
2530  a.DoA(47);
2531  EXPECT_THAT(do_a_arg0, 17);
2532  EXPECT_THAT(do_a_47_arg0, 47);
2533 
2534  ON_CALL(a, Binary).WillByDefault(Return(true));
2535  ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
2536  EXPECT_THAT(a.Binary(14, 17), true);
2537  EXPECT_THAT(a.Binary(17, 14), false);
2538 }
2539 
2540 TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
2541  MockB b;
2542  ON_CALL(b, DoB()).WillByDefault(Return(9));
2543  ON_CALL(b, DoB(5)).WillByDefault(Return(11));
2544 
2545  EXPECT_THAT(b.DoB(), 9);
2546  EXPECT_THAT(b.DoB(1), 0); // default value
2547  EXPECT_THAT(b.DoB(5), 11);
2548 }
2549 
2550 struct MockWithConstMethods {
2551  public:
2552  MOCK_CONST_METHOD1(Foo, int(int));
2553  MOCK_CONST_METHOD2(Bar, int(int, const char*));
2554 };
2555 
2556 TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
2557  MockWithConstMethods mock;
2558  ON_CALL(mock, Foo).WillByDefault(Return(7));
2559  ON_CALL(mock, Bar).WillByDefault(Return(33));
2560 
2561  EXPECT_THAT(mock.Foo(17), 7);
2562  EXPECT_THAT(mock.Bar(27, "purple"), 33);
2563 }
2564 
2565 class MockConstOverload {
2566  public:
2567  MOCK_METHOD1(Overloaded, int(int));
2568  MOCK_CONST_METHOD1(Overloaded, int(int));
2569 };
2570 
2571 TEST(ParameterlessExpectationsTest,
2572  CanSetExpectationsForConstOverloadedMethods) {
2573  MockConstOverload mock;
2574  ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
2575  ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
2576  ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
2577  ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
2578 
2579  EXPECT_THAT(mock.Overloaded(1), 7);
2580  EXPECT_THAT(mock.Overloaded(5), 9);
2581  EXPECT_THAT(mock.Overloaded(7), 7);
2582 
2583  const MockConstOverload& const_mock = mock;
2584  EXPECT_THAT(const_mock.Overloaded(1), 0);
2585  EXPECT_THAT(const_mock.Overloaded(5), 11);
2586  EXPECT_THAT(const_mock.Overloaded(7), 13);
2587 }
2588 
2589 } // namespace
2590 } // namespace testing
2591 
2592 int main(int argc, char** argv) {
2593  testing::InitGoogleMock(&argc, argv);
2594  // Ensures that the tests pass no matter what value of
2595  // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2596  GMOCK_FLAG_SET(catch_leaked_mocks, true);
2598 
2599  return RUN_ALL_TESTS();
2600 }
#define EXPECT_DEATH_IF_SUPPORTED(statement, regex)
GTEST_API_ std::string GetCapturedStdout()
#define EXPECT_PRED_FORMAT2(pred_format, v1, v2)
GTEST_API_ Cardinality AtLeast(int n)
#define EXPECT_NONFATAL_FAILURE(statement, substr)
#define ACTION_P(name,...)
GTEST_API_ Cardinality AtMost(int n)
#define MOCK_METHOD6(m,...)
TEST_F(TestInfoTest, Names)
GTEST_API_ void InitGoogleMock(int *argc, char **argv)
Definition: gmock.cc:203
const std::string saved_verbose_flag_
#define MOCK_METHOD0(m,...)
internal::DoAllAction< typename std::decay< Action >::type...> DoAll(Action &&...action)
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1914
#define ON_CALL(obj, call)
GTEST_DISABLE_MSC_WARNINGS_POP_() template< int &...ExplicitParameterBarrier
GTEST_API_ void CaptureStdout()
#define EXPECT_ANY_THROW(statement)
Definition: gtest.h:1795
internal::InvokeWithoutArgsAction< typename std::decay< FunctionImpl >::type > InvokeWithoutArgs(FunctionImpl function_impl)
std::ostream & operator<<(std::ostream &os, const Message &sb)
const char kWarningVerbosity[]
#define MOCK_METHOD2(m,...)
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
Definition: gtest-port.cc:1003
std::decay< FunctionImpl >::type Invoke(FunctionImpl &&function_impl)
expr expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c *expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr1 c expr2 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr2 expr1 expr2 expr1 expr1 expr1 expr2 expr1 expr2 expr1 expr1 expr1 c
#define ASSERT_TRUE(condition)
Definition: gtest.h:1831
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
Definition: gtest-port.h:377
const char * p
LogTestHelper helper_
int main()
Definition: ad_example.cpp:171
TEST(GTestEnvVarTest, Dummy)
#define GMOCK_FLAG_GET(name)
Definition: gmock-port.h:135
int value
#define EXPECT_STREQ(s1, s2)
Definition: gtest.h:1953
#define MOCK_METHOD1(m,...)
GTEST_API_ AssertionResult IsSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition: gtest.cc:1876
#define MOCK_CONST_METHOD0(m,...)
#define GMOCK_FLAG_SET(name, value)
Definition: gmock-port.h:136
#define MOCK_CONST_METHOD2(m,...)
GTEST_API_ Cardinality Between(int min, int max)
void PrintTo(const T &value,::std::ostream *os)
#define EXPECT_THAT(value, matcher)
GTEST_API_ Cardinality AnyNumber()
internal::DoDefaultAction DoDefault()
internal::ReturnAction< R > Return(R value)
#define EXPECT_CALL(obj, call)
#define Method
static GTEST_INTERNAL_ATTRIBUTE_MAYBE_UNUSED bool dummy2
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1884
int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_
Definition: gtest.h:2334
const double y
#define EXPECT_TRUE(condition)
Definition: gtest.h:1823
GTEST_API_ AssertionResult IsNotSubstring(const char *needle_expr, const char *haystack_expr, const char *needle, const char *haystack)
Definition: gtest.cc:1886
#define ADD_FAILURE()
Definition: gtest.h:1750
internal::IgnoreResultAction< A > IgnoreResult(const A &an_action)
#define MOCK_CONST_METHOD1(m,...)
#define EXPECT_FALSE(condition)
Definition: gtest.h:1827
const char kErrorVerbosity[]
#define ASSERT_FALSE(condition)
Definition: gtest.h:1835
int n
const char * Binary(const char *input, short n)
static void Delete(T *x)