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