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