gmock-spec-builders_test.cc 73 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Copyright 2007, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Gennadiy Civil's avatar
 
Gennadiy Civil committed
29

30
31
32
33
34

// Google Mock - a framework for writing C++ mock classes.
//
// This file tests the spec builder syntax.

35
#include "gmock/gmock-spec-builders.h"
36

misterg's avatar
misterg committed
37
#include <memory>
38
39
40
41
#include <ostream>  // NOLINT
#include <sstream>
#include <string>

42
43
44
45
#include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
46
#include "gtest/internal/gtest-port.h"
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

namespace testing {
namespace internal {

// Helper class for testing the Expectation class template.
class ExpectationTester {
 public:
  // Sets the call count of the given expectation to the given number.
  void SetCallCount(int n, ExpectationBase* exp) {
    exp->call_count_ = n;
  }
};

}  // namespace internal
}  // namespace testing

namespace {

using testing::_;
using testing::AnyNumber;
using testing::AtLeast;
using testing::AtMost;
using testing::Between;
using testing::Cardinality;
using testing::CardinalityInterface;
using testing::Const;
Krystian Kuzniarek's avatar
Krystian Kuzniarek committed
73
using testing::ContainsRegex;
74
75
using testing::DoAll;
using testing::DoDefault;
76
77
78
using testing::Eq;
using testing::Expectation;
using testing::ExpectationSet;
79
using testing::Gt;
Abseil Team's avatar
Abseil Team committed
80
using testing::IgnoreResult;
81
82
83
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
84
using testing::IsNotSubstring;
85
86
87
88
using testing::IsSubstring;
using testing::Lt;
using testing::Message;
using testing::Mock;
89
using testing::NaggyMock;
90
using testing::Ne;
91
using testing::Return;
92
using testing::SaveArg;
93
using testing::Sequence;
94
using testing::SetArgPointee;
95
using testing::internal::ExpectationTester;
96
using testing::internal::FormatFileLocation;
97
using testing::internal::kAllow;
98
using testing::internal::kErrorVerbosity;
99
using testing::internal::kFail;
100
using testing::internal::kInfoVerbosity;
101
using testing::internal::kWarn;
102
103
using testing::internal::kWarningVerbosity;

104
#if GTEST_HAS_STREAM_REDIRECTION
105
106
107
using testing::HasSubstr;
using testing::internal::CaptureStdout;
using testing::internal::GetCapturedStdout;
108
#endif
109

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
class Incomplete;

class MockIncomplete {
 public:
  // This line verifies that a mock method can take a by-reference
  // argument of an incomplete type.
  MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
};

// Tells Google Mock how to print a value of type Incomplete.
void PrintTo(const Incomplete& x, ::std::ostream* os);

TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
  // Even though this mock class contains a mock method that takes
  // by-reference an argument whose type is incomplete, we can still
  // use the mock, as long as Google Mock knows how to print the
  // argument.
  MockIncomplete incomplete;
  EXPECT_CALL(incomplete, ByRefFunc(_))
      .Times(AnyNumber());
}

// The definition of the printer for the argument type doesn't have to
// be visible where the mock is used.
void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
  *os << "incomplete";
}

138
139
class Result {};

140
141
142
143
144
145
// A type that's not default constructible.
class NonDefaultConstructible {
 public:
  explicit NonDefaultConstructible(int /* dummy */) {}
};

146
147
class MockA {
 public:
148
149
  MockA() {}

150
151
152
153
154
  MOCK_METHOD1(DoA, void(int n));
  MOCK_METHOD1(ReturnResult, Result(int n));
  MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
  MOCK_METHOD2(Binary, bool(int x, int y));
  MOCK_METHOD2(ReturnInt, int(int x, int y));
155
156
157

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
158
159
160
161
};

class MockB {
 public:
162
163
  MockB() {}

164
165
  MOCK_CONST_METHOD0(DoB, int());  // NOLINT
  MOCK_METHOD1(DoB, int(int n));  // NOLINT
166
167
168

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
169
170
};

171
172
173
174
class ReferenceHoldingMock {
 public:
  ReferenceHoldingMock() {}

misterg's avatar
misterg committed
175
  MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
176
177
178
179
180

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
};

181
182
183
184
185
186
187
188
189
190
191
192
193
194
// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
// redefining a mock method name. This could happen, for example, when
// the tested code #includes Win32 API headers which define many APIs
// as macros, e.g. #define TextOut TextOutW.

#define Method MethodW

class CC {
 public:
  virtual ~CC() {}
  virtual int Method() = 0;
};
class MockCC : public CC {
 public:
195
196
  MockCC() {}

197
  MOCK_METHOD0(Method, int());
198
199
200

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
};

// Tests that a method with expanded name compiles.
TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
  MockCC cc;
  ON_CALL(cc, Method());
}

// Tests that the method with expanded name not only compiles but runs
// and returns a correct value, too.
TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
  MockCC cc;
  ON_CALL(cc, Method()).WillByDefault(Return(42));
  EXPECT_EQ(42, cc.Method());
}

// Tests that a method with expanded name compiles.
TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
  MockCC cc;
  EXPECT_CALL(cc, Method());
  cc.Method();
}

// Tests that it works, too.
TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
  MockCC cc;
  EXPECT_CALL(cc, Method()).WillOnce(Return(42));
  EXPECT_EQ(42, cc.Method());
}

#undef Method  // Done with macro redefinition tests.

// Tests that ON_CALL evaluates its arguments exactly once as promised
// by Google Mock.
TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
  MockA a;
  MockA* pa = &a;

  ON_CALL(*pa++, DoA(_));
  EXPECT_EQ(&a + 1, pa);
}

TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
  MockA a;
  int n = 0;

  ON_CALL(a, DoA(n++));
  EXPECT_EQ(1, n);
}

// Tests that the syntax of ON_CALL() is enforced at run time.

253
TEST(OnCallSyntaxTest, WithIsOptional) {
254
255
256
257
258
  MockA a;

  ON_CALL(a, DoA(5))
      .WillByDefault(Return());
  ON_CALL(a, DoA(_))
259
      .With(_)
260
261
262
      .WillByDefault(Return());
}

263
TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
264
265
266
267
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    ON_CALL(a, ReturnResult(_))
268
269
        .With(_)
        .With(_)
270
        .WillByDefault(Return(Result()));
271
272
273
  }, ".With() cannot appear more than once in an ON_CALL()");
}

274
275
276
TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
  MockA a;

277
  EXPECT_DEATH_IF_SUPPORTED({
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    ON_CALL(a, DoA(5));
    a.DoA(5);
  }, "");
}

TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    ON_CALL(a, DoA(5))
        .WillByDefault(Return())
        .WillByDefault(Return());
  }, ".WillByDefault() must appear exactly once in an ON_CALL()");
}

// Tests that EXPECT_CALL evaluates its arguments exactly once as
// promised by Google Mock.
TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
  MockA a;
  MockA* pa = &a;

  EXPECT_CALL(*pa++, DoA(_));
  a.DoA(0);
  EXPECT_EQ(&a + 1, pa);
}

TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
  MockA a;
  int n = 0;

  EXPECT_CALL(a, DoA(n++));
  a.DoA(0);
  EXPECT_EQ(1, n);
}

// Tests that the syntax of EXPECT_CALL() is enforced at run time.

315
TEST(ExpectCallSyntaxTest, WithIsOptional) {
316
317
318
319
320
  MockA a;

  EXPECT_CALL(a, DoA(5))
      .Times(0);
  EXPECT_CALL(a, DoA(6))
321
      .With(_)
322
323
324
      .Times(0);
}

325
TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
326
327
328
329
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(6))
330
331
332
        .With(_)
        .With(_);
  }, ".With() cannot appear more than once in an EXPECT_CALL()");
333
334
335
336

  a.DoA(6);
}

337
TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
338
339
340
341
342
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .Times(1)
343
344
        .With(_);
  }, ".With() must be the first clause in an EXPECT_CALL()");
345
346
347
348
349
350

  a.DoA(1);

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(2))
        .WillOnce(Return())
351
352
        .With(_);
  }, ".With() must be the first clause in an EXPECT_CALL()");
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392

  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
  MockA a;

  EXPECT_CALL(a, DoA(1))
      .WillOnce(Return());

  EXPECT_CALL(a, DoA(2))
      .WillOnce(Return())
      .WillRepeatedly(Return());

  a.DoA(1);
  a.DoA(2);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .Times(1)
        .Times(2);
  }, ".Times() cannot appear more than once in an EXPECT_CALL()");

  a.DoA(1);
  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
  MockA a;
  Sequence s;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .InSequence(s)
        .Times(1);
393
  }, ".Times() may only appear *before* ");
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420

  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
  MockA a;
  Sequence s;

  EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(2))
      .InSequence(s);

  a.DoA(1);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
  MockA a;
  Sequence s1, s2;

  EXPECT_CALL(a, DoA(1))
      .InSequence(s1, s2)
      .InSequence(s1);

  a.DoA(1);
}

421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
  MockA a;
  Sequence s;

  Expectation e = EXPECT_CALL(a, DoA(1))
      .Times(AnyNumber());
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(2))
        .After(e)
        .InSequence(s);
  }, ".InSequence() cannot appear after ");

  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
437
438
439
440
441
442
443
444
445
446
447
448
  MockA a;
  Sequence s;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .WillOnce(Return())
        .InSequence(s);
  }, ".InSequence() cannot appear after ");

  a.DoA(1);
}

449
450
451
452
453
454
455
456
457
458
459
460
461
462
TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
  MockA a;

  Expectation e = EXPECT_CALL(a, DoA(1));
  EXPECT_NONFATAL_FAILURE({
    EXPECT_CALL(a, DoA(2))
        .WillOnce(Return())
        .After(e);
  }, ".After() cannot appear after ");

  a.DoA(1);
  a.DoA(2);
}

463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
TEST(ExpectCallSyntaxTest, WillIsOptional) {
  MockA a;

  EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(2))
      .WillOnce(Return());

  a.DoA(1);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
  MockA a;

  EXPECT_CALL(a, DoA(1))
      .Times(AnyNumber())
      .WillOnce(Return())
      .WillOnce(Return())
      .WillOnce(Return());
}

TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .WillRepeatedly(Return())
        .WillOnce(Return());
  }, ".WillOnce() cannot appear after ");

  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
  MockA a;

  EXPECT_CALL(a, DoA(1))
      .WillOnce(Return());
  EXPECT_CALL(a, DoA(2))
      .WillOnce(Return())
      .WillRepeatedly(Return());

  a.DoA(1);
  a.DoA(2);
  a.DoA(2);
}

TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .WillRepeatedly(Return())
        .WillRepeatedly(Return());
  }, ".WillRepeatedly() cannot appear more than once in an "
     "EXPECT_CALL()");
}

TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .RetiresOnSaturation()
        .WillRepeatedly(Return());
  }, ".WillRepeatedly() cannot appear after ");
}

TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
  MockA a;

  EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(1))
      .RetiresOnSaturation();

  a.DoA(1);
  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
  MockA a;

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    EXPECT_CALL(a, DoA(1))
        .RetiresOnSaturation()
        .RetiresOnSaturation();
  }, ".RetiresOnSaturation() cannot appear more than once");

  a.DoA(1);
}

TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
  {
    MockA a;
    EXPECT_CALL(a, DoA(1));
    a.DoA(1);
  }
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockA a;
    EXPECT_CALL(a, DoA(1));
  }, "to be called once");
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockA a;
    EXPECT_CALL(a, DoA(1));
    a.DoA(1);
    a.DoA(1);
  }, "to be called once");
}

572
#if GTEST_HAS_STREAM_REDIRECTION
573
574
575
576

// Tests that Google Mock doesn't print a warning when the number of
// WillOnce() is adequate.
TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
577
  CaptureStdout();
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
  {
    MockB b;

    // It's always fine to omit WillOnce() entirely.
    EXPECT_CALL(b, DoB())
        .Times(0);
    EXPECT_CALL(b, DoB(1))
        .Times(AtMost(1));
    EXPECT_CALL(b, DoB(2))
        .Times(1)
        .WillRepeatedly(Return(1));

    // It's fine for the number of WillOnce()s to equal the upper bound.
    EXPECT_CALL(b, DoB(3))
        .Times(Between(1, 2))
        .WillOnce(Return(1))
        .WillOnce(Return(2));

    // It's fine for the number of WillOnce()s to be smaller than the
    // upper bound when there is a WillRepeatedly().
    EXPECT_CALL(b, DoB(4))
        .Times(AtMost(3))
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));

    // Satisfies the above expectations.
    b.DoB(2);
    b.DoB(3);
  }
607
  EXPECT_STREQ("", GetCapturedStdout().c_str());
608
609
610
611
612
}

// Tests that Google Mock warns on having too many actions in an
// expectation compared to its cardinality.
TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
613
  CaptureStdout();
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
  {
    MockB b;

    // Warns when the number of WillOnce()s is larger than the upper bound.
    EXPECT_CALL(b, DoB())
        .Times(0)
        .WillOnce(Return(1));  // #1
    EXPECT_CALL(b, DoB())
        .Times(AtMost(1))
        .WillOnce(Return(1))
        .WillOnce(Return(2));  // #2
    EXPECT_CALL(b, DoB(1))
        .Times(1)
        .WillOnce(Return(1))
        .WillOnce(Return(2))
        .RetiresOnSaturation();  // #3

    // Warns when the number of WillOnce()s equals the upper bound and
    // there is a WillRepeatedly().
    EXPECT_CALL(b, DoB())
        .Times(0)
        .WillRepeatedly(Return(1));  // #4
    EXPECT_CALL(b, DoB(2))
        .Times(1)
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));  // #5

    // Satisfies the above expectations.
    b.DoB(1);
    b.DoB(2);
  }
645
  const std::string output = GetCapturedStdout();
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
      "Expected to be never called, but has 1 WillOnce().",
      output);  // #1
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
      "Expected to be called at most once, "
      "but has 2 WillOnce()s.",
      output);  // #2
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
      "Expected to be called once, but has 2 WillOnce()s.",
      output);  // #3
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
      "Expected to be never called, but has 0 WillOnce()s "
      "and a WillRepeatedly().",
      output);  // #4
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
      "Expected to be called once, but has 1 WillOnce() "
      "and a WillRepeatedly().",
      output);  // #5
674
675
676
677
678
679
680
681
682
683
684
}

// Tests that Google Mock warns on having too few actions in an
// expectation compared to its cardinality.
TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
  MockB b;

  EXPECT_CALL(b, DoB())
      .Times(Between(2, 3))
      .WillOnce(Return(1));

685
  CaptureStdout();
686
  b.DoB();
687
  const std::string output = GetCapturedStdout();
688
689
690
691
692
693
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
      "Expected to be called between 2 and 3 times, "
      "but has only 1 WillOnce().",
      output);
694
695
696
  b.DoB();
}

697
TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
Abseil Team's avatar
Abseil Team committed
698
  int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);
699

Abseil Team's avatar
Abseil Team committed
700
  GMOCK_FLAG_SET(default_mock_behavior, kAllow);
701
702
703
704
705
706
707
708
  CaptureStdout();
  {
    MockA a;
    a.DoA(0);
  }
  std::string output = GetCapturedStdout();
  EXPECT_TRUE(output.empty()) << output;

Abseil Team's avatar
Abseil Team committed
709
  GMOCK_FLAG_SET(default_mock_behavior, kWarn);
710
711
712
713
714
715
716
  CaptureStdout();
  {
    MockA a;
    a.DoA(0);
  }
  std::string warning_output = GetCapturedStdout();
  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
717
718
  EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
                      warning_output);
719

Abseil Team's avatar
Abseil Team committed
720
  GMOCK_FLAG_SET(default_mock_behavior, kFail);
721
722
723
  EXPECT_NONFATAL_FAILURE({
    MockA a;
    a.DoA(0);
724
  }, "Uninteresting mock function call");
725

Alyssa Wilk's avatar
Alyssa Wilk committed
726
  // Out of bounds values are converted to kWarn
Abseil Team's avatar
Abseil Team committed
727
  GMOCK_FLAG_SET(default_mock_behavior, -1);
Alyssa Wilk's avatar
Alyssa Wilk committed
728
729
730
731
732
733
734
  CaptureStdout();
  {
    MockA a;
    a.DoA(0);
  }
  warning_output = GetCapturedStdout();
  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
735
736
  EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
                      warning_output);
Abseil Team's avatar
Abseil Team committed
737
  GMOCK_FLAG_SET(default_mock_behavior, 3);
Alyssa Wilk's avatar
Alyssa Wilk committed
738
739
740
741
742
743
744
  CaptureStdout();
  {
    MockA a;
    a.DoA(0);
  }
  warning_output = GetCapturedStdout();
  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
745
746
  EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
                      warning_output);
Alyssa Wilk's avatar
Alyssa Wilk committed
747

Abseil Team's avatar
Abseil Team committed
748
  GMOCK_FLAG_SET(default_mock_behavior, original_behavior);
749
750
}

751
#endif  // GTEST_HAS_STREAM_REDIRECTION
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

// Tests the semantics of ON_CALL().

// Tests that the built-in default action is taken when no ON_CALL()
// is specified.
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
  MockB b;
  EXPECT_CALL(b, DoB());

  EXPECT_EQ(0, b.DoB());
}

// Tests that the built-in default action is taken when no ON_CALL()
// matches the invocation.
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
  MockB b;
  ON_CALL(b, DoB(1))
      .WillByDefault(Return(1));
  EXPECT_CALL(b, DoB(_));

  EXPECT_EQ(0, b.DoB(2));
}

// Tests that the last matching ON_CALL() action is taken.
TEST(OnCallTest, PicksLastMatchingOnCall) {
  MockB b;
  ON_CALL(b, DoB(_))
      .WillByDefault(Return(3));
  ON_CALL(b, DoB(2))
      .WillByDefault(Return(2));
  ON_CALL(b, DoB(1))
      .WillByDefault(Return(1));
  EXPECT_CALL(b, DoB(_));

  EXPECT_EQ(2, b.DoB(2));
}

// Tests the semantics of EXPECT_CALL().

// Tests that any call is allowed when no EXPECT_CALL() is specified.
TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
  MockB b;
  EXPECT_CALL(b, DoB());
  // There is no expectation on DoB(int).

  b.DoB();

  // DoB(int) can be called any number of times.
  b.DoB(1);
  b.DoB(2);
}

// Tests that the last matching EXPECT_CALL() fires.
TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
  MockB b;
  EXPECT_CALL(b, DoB(_))
      .WillRepeatedly(Return(2));
  EXPECT_CALL(b, DoB(1))
      .WillRepeatedly(Return(1));

  EXPECT_EQ(1, b.DoB(1));
}

// Tests lower-bound violation.
TEST(ExpectCallTest, CatchesTooFewCalls) {
  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB(5))
        .Times(AtLeast(2));

    b.DoB(5);
823
  }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
     "         Expected: to be called at least twice\n"
     "           Actual: called once - unsatisfied and active");
}

// Tests that the cardinality can be inferred when no Times(...) is
// specified.
TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
  {
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillOnce(Return(2));

    EXPECT_EQ(1, b.DoB());
    EXPECT_EQ(2, b.DoB());
  }

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillOnce(Return(2));

    EXPECT_EQ(1, b.DoB());
  }, "to be called twice");

  {  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillOnce(Return(2));

    EXPECT_EQ(1, b.DoB());
    EXPECT_EQ(2, b.DoB());
    EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
  }
}

TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
  {
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));

    EXPECT_EQ(1, b.DoB());
  }

  {  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));

    EXPECT_EQ(1, b.DoB());
    EXPECT_EQ(2, b.DoB());
    EXPECT_EQ(2, b.DoB());
  }

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    MockB b;
    EXPECT_CALL(b, DoB())
        .WillOnce(Return(1))
        .WillRepeatedly(Return(2));
  }, "to be called at least once");
}

// Tests that the n-th action is taken for the n-th matching
// invocation.
TEST(ExpectCallTest, NthMatchTakesNthAction) {
  MockB b;
  EXPECT_CALL(b, DoB())
      .WillOnce(Return(1))
      .WillOnce(Return(2))
      .WillOnce(Return(3));

  EXPECT_EQ(1, b.DoB());
  EXPECT_EQ(2, b.DoB());
  EXPECT_EQ(3, b.DoB());
}

905
906
907
908
909
910
911
912
913
914
915
916
917
// Tests that the WillRepeatedly() action is taken when the WillOnce(...)
// list is exhausted.
TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
  MockB b;
  EXPECT_CALL(b, DoB())
      .WillOnce(Return(1))
      .WillRepeatedly(Return(2));

  EXPECT_EQ(1, b.DoB());
  EXPECT_EQ(2, b.DoB());
  EXPECT_EQ(2, b.DoB());
}

918
#if GTEST_HAS_STREAM_REDIRECTION
919
920
921
922
923
924
925
926
927
928
929
930

// Tests that the default action is taken when the WillOnce(...) list is
// exhausted and there is no WillRepeatedly().
TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
  MockB b;
  EXPECT_CALL(b, DoB(_))
      .Times(1);
  EXPECT_CALL(b, DoB())
      .Times(AnyNumber())
      .WillOnce(Return(1))
      .WillOnce(Return(2));

931
  CaptureStdout();
932
933
934
935
  EXPECT_EQ(0, b.DoB(1));  // Shouldn't generate a warning as the
                           // expectation has no action clause at all.
  EXPECT_EQ(1, b.DoB());
  EXPECT_EQ(2, b.DoB());
936
  const std::string output1 = GetCapturedStdout();
937
  EXPECT_STREQ("", output1.c_str());
938

939
  CaptureStdout();
940
941
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB());
942
  const std::string output2 = GetCapturedStdout();
943
944
945
946
947
948
949
950
  EXPECT_THAT(output2.c_str(),
              HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
                        "Called 3 times, but only 2 WillOnce()s are specified"
                        " - returning default value."));
  EXPECT_THAT(output2.c_str(),
              HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
                        "Called 4 times, but only 2 WillOnce()s are specified"
                        " - returning default value."));
951
952
}

953
TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
954
  MockB b;
955
956
  std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
  EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
957
958

  EXPECT_EQ(1, b.DoB());
959
960
961

  CaptureStdout();
  EXPECT_EQ(0, b.DoB());
962
  const std::string output = GetCapturedStdout();
963
964
  // The warning message should contain the call location.
  EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
965
966
}

967
TEST(FunctionMockerMessageTest,
968
     ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
969
970
971
  std::string on_call_location;
  CaptureStdout();
  {
972
    NaggyMock<MockB> b;
973
974
975
976
977
978
979
980
981
    on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
    ON_CALL(b, DoB(_)).WillByDefault(Return(0));
    b.DoB(0);
  }
  EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
}

#endif  // GTEST_HAS_STREAM_REDIRECTION

982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
// Tests that an uninteresting call performs the default action.
TEST(UninterestingCallTest, DoesDefaultAction) {
  // When there is an ON_CALL() statement, the action specified by it
  // should be taken.
  MockA a;
  ON_CALL(a, Binary(_, _))
      .WillByDefault(Return(true));
  EXPECT_TRUE(a.Binary(1, 2));

  // When there is no ON_CALL(), the default value for the return type
  // should be returned.
  MockB b;
  EXPECT_EQ(0, b.DoB());
}

// Tests that an unexpected call performs the default action.
TEST(UnexpectedCallTest, DoesDefaultAction) {
  // When there is an ON_CALL() statement, the action specified by it
  // should be taken.
  MockA a;
  ON_CALL(a, Binary(_, _))
      .WillByDefault(Return(true));
  EXPECT_CALL(a, Binary(0, 0));
  a.Binary(0, 0);
  bool result = false;
  EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
                          "Unexpected mock function call");
  EXPECT_TRUE(result);

  // When there is no ON_CALL(), the default value for the return type
  // should be returned.
  MockB b;
  EXPECT_CALL(b, DoB(0))
      .Times(0);
  int n = -1;
  EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
                          "Unexpected mock function call");
  EXPECT_EQ(0, n);
}

// Tests that when an unexpected void function generates the right
// failure message.
TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
  // First, tests the message when there is only one EXPECT_CALL().
  MockA a1;
  EXPECT_CALL(a1, DoA(1));
  a1.DoA(1);
  // Ideally we should match the failure message against a regex, but
  // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
  // multiple sub-strings instead.
  EXPECT_NONFATAL_FAILURE(
      a1.DoA(9),
      "Unexpected mock function call - returning directly.\n"
      "    Function call: DoA(9)\n"
      "Google Mock tried the following 1 expectation, but it didn't match:");
  EXPECT_NONFATAL_FAILURE(
      a1.DoA(9),
      "  Expected arg #0: is equal to 1\n"
      "           Actual: 9\n"
      "         Expected: to be called once\n"
      "           Actual: called once - saturated and active");

  // Next, tests the message when there are more than one EXPECT_CALL().
  MockA a2;
  EXPECT_CALL(a2, DoA(1));
  EXPECT_CALL(a2, DoA(3));
  a2.DoA(1);
  EXPECT_NONFATAL_FAILURE(
      a2.DoA(2),
      "Unexpected mock function call - returning directly.\n"
      "    Function call: DoA(2)\n"
      "Google Mock tried the following 2 expectations, but none matched:");
  EXPECT_NONFATAL_FAILURE(
      a2.DoA(2),
1056
      "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1057
1058
1059
1060
1061
1062
      "  Expected arg #0: is equal to 1\n"
      "           Actual: 2\n"
      "         Expected: to be called once\n"
      "           Actual: called once - saturated and active");
  EXPECT_NONFATAL_FAILURE(
      a2.DoA(2),
1063
      "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
      "  Expected arg #0: is equal to 3\n"
      "           Actual: 2\n"
      "         Expected: to be called once\n"
      "           Actual: never called - unsatisfied and active");
  a2.DoA(3);
}

// Tests that an unexpected non-void function generates the right
// failure message.
TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
  MockB b1;
  EXPECT_CALL(b1, DoB(1));
  b1.DoB(1);
  EXPECT_NONFATAL_FAILURE(
      b1.DoB(2),
      "Unexpected mock function call - returning default value.\n"
      "    Function call: DoB(2)\n"
      "          Returns: 0\n"
      "Google Mock tried the following 1 expectation, but it didn't match:");
  EXPECT_NONFATAL_FAILURE(
      b1.DoB(2),
      "  Expected arg #0: is equal to 1\n"
      "           Actual: 2\n"
      "         Expected: to be called once\n"
      "           Actual: called once - saturated and active");
}

// Tests that Google Mock explains that an retired expectation doesn't
// match the call.
TEST(UnexpectedCallTest, RetiredExpectation) {
  MockB b;
  EXPECT_CALL(b, DoB(1))
      .RetiresOnSaturation();

  b.DoB(1);
  EXPECT_NONFATAL_FAILURE(
      b.DoB(1),
      "         Expected: the expectation is active\n"
      "           Actual: it is retired");
}

// Tests that Google Mock explains that an expectation that doesn't
// match the arguments doesn't match the call.
TEST(UnexpectedCallTest, UnmatchedArguments) {
  MockB b;
  EXPECT_CALL(b, DoB(1));

  EXPECT_NONFATAL_FAILURE(
      b.DoB(2),
      "  Expected arg #0: is equal to 1\n"
      "           Actual: 2\n");
  b.DoB(1);
}

// Tests that Google Mock explains that an expectation with
// unsatisfied pre-requisites doesn't match the call.
TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
  Sequence s1, s2;
  MockB b;
  EXPECT_CALL(b, DoB(1))
      .InSequence(s1);
  EXPECT_CALL(b, DoB(2))
      .Times(AnyNumber())
      .InSequence(s1);
  EXPECT_CALL(b, DoB(3))
      .InSequence(s2);
  EXPECT_CALL(b, DoB(4))
      .InSequence(s1, s2);

  ::testing::TestPartResultArray failures;
  {
    ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
    b.DoB(4);
    // Now 'failures' contains the Google Test failures generated by
    // the above statement.
  }

  // There should be one non-fatal failure.
  ASSERT_EQ(1, failures.size());
  const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
zhanyong.wan's avatar
zhanyong.wan committed
1144
  EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1145
1146
1147

  // Verifies that the failure message contains the two unsatisfied
  // pre-requisites but not the satisfied one.
1148
1149
#if GTEST_USES_PCRE
  EXPECT_THAT(r.message(), ContainsRegex(
1150
1151
1152
1153
      // PCRE has trouble using (.|\n) to match any character, but
      // supports the (?s) prefix for using . to match any character.
      "(?s)the following immediate pre-requisites are not satisfied:\n"
      ".*: pre-requisite #0\n"
1154
1155
1156
      ".*: pre-requisite #1"));
#elif GTEST_USES_POSIX_RE
  EXPECT_THAT(r.message(), ContainsRegex(
1157
1158
1159
1160
      // POSIX RE doesn't understand the (?s) prefix, but has no trouble
      // with (.|\n).
      "the following immediate pre-requisites are not satisfied:\n"
      "(.|\n)*: pre-requisite #0\n"
1161
1162
1163
1164
1165
1166
1167
1168
      "(.|\n)*: pre-requisite #1"));
#else
  // We can only use Google Test's own simple regex.
  EXPECT_THAT(r.message(), ContainsRegex(
      "the following immediate pre-requisites are not satisfied:"));
  EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
  EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
#endif  // GTEST_USES_PCRE
1169
1170
1171
1172
1173
1174

  b.DoB(1);
  b.DoB(3);
  b.DoB(4);
}

1175
1176
TEST(UndefinedReturnValueTest,
     ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1177
  MockA a;
Gennadiy Civil's avatar
 
Gennadiy Civil committed
1178
  // FIXME: We should really verify the output message,
1179
1180
  // but we cannot yet due to that EXPECT_DEATH only captures stderr
  // while Google Mock logs to stdout.
1181
#if GTEST_HAS_EXCEPTIONS
1182
  EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1183
#else
1184
  EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1185
#endif
1186
1187
}

1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
// Tests that an excessive call (one whose arguments match the
// matchers but is called too many times) performs the default action.
TEST(ExcessiveCallTest, DoesDefaultAction) {
  // When there is an ON_CALL() statement, the action specified by it
  // should be taken.
  MockA a;
  ON_CALL(a, Binary(_, _))
      .WillByDefault(Return(true));
  EXPECT_CALL(a, Binary(0, 0));
  a.Binary(0, 0);
  bool result = false;
  EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
                          "Mock function called more times than expected");
  EXPECT_TRUE(result);

  // When there is no ON_CALL(), the default value for the return type
  // should be returned.
  MockB b;
  EXPECT_CALL(b, DoB(0))
      .Times(0);
  int n = -1;
  EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
                          "Mock function called more times than expected");
  EXPECT_EQ(0, n);
}

// Tests that when a void function is called too many times,
// the failure message contains the argument values.
TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
  MockA a;
  EXPECT_CALL(a, DoA(_))
      .Times(0);
  EXPECT_NONFATAL_FAILURE(
      a.DoA(9),
      "Mock function called more times than expected - returning directly.\n"
      "    Function call: DoA(9)\n"
      "         Expected: to be never called\n"
      "           Actual: called once - over-saturated and active");
}

// Tests that when a non-void function is called too many times, the
// failure message contains the argument values and the return value.
TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
  MockB b;
  EXPECT_CALL(b, DoB(_));
  b.DoB(1);
  EXPECT_NONFATAL_FAILURE(
      b.DoB(2),
      "Mock function called more times than expected - "
      "returning default value.\n"
      "    Function call: DoB(2)\n"
      "          Returns: 0\n"
      "         Expected: to be called once\n"
      "           Actual: called twice - over-saturated and active");
}

// Tests using sequences.

TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
  MockA a;
  {
    InSequence dummy;

    EXPECT_CALL(a, DoA(1));
    EXPECT_CALL(a, DoA(2));
  }

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    a.DoA(2);
  }, "Unexpected mock function call");

  a.DoA(1);
  a.DoA(2);
}

TEST(InSequenceTest, NestedInSequence) {
  MockA a;
  {
    InSequence dummy;

    EXPECT_CALL(a, DoA(1));
    {
      InSequence dummy2;

      EXPECT_CALL(a, DoA(2));
      EXPECT_CALL(a, DoA(3));
    }
  }

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    a.DoA(1);
    a.DoA(3);
  }, "Unexpected mock function call");

  a.DoA(2);
  a.DoA(3);
}

TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
  MockA a;
  {
    InSequence dummy;

    EXPECT_CALL(a, DoA(1));
    EXPECT_CALL(a, DoA(2));
  }
  EXPECT_CALL(a, DoA(3));

  EXPECT_NONFATAL_FAILURE({  // NOLINT
    a.DoA(2);
  }, "Unexpected mock function call");

  a.DoA(3);
  a.DoA(1);
  a.DoA(2);
}

// Tests that any order is allowed when no sequence is used.
TEST(SequenceTest, AnyOrderIsOkByDefault) {
  {
    MockA a;
    MockB b;

    EXPECT_CALL(a, DoA(1));
    EXPECT_CALL(b, DoB())
        .Times(AnyNumber());

    a.DoA(1);
    b.DoB();
  }

  {  // NOLINT
    MockA a;
    MockB b;

    EXPECT_CALL(a, DoA(1));
    EXPECT_CALL(b, DoB())
        .Times(AnyNumber());

    b.DoB();
    a.DoA(1);
  }
}

// Tests that the calls must be in strict order when a complete order
// is specified.
1334
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1335
  MockA a;
1336
1337
  ON_CALL(a, ReturnResult(_))
      .WillByDefault(Return(Result()));
1338

1339
  Sequence s;
1340
  EXPECT_CALL(a, ReturnResult(1))
1341
      .InSequence(s);
1342
  EXPECT_CALL(a, ReturnResult(2))
1343
      .InSequence(s);
1344
  EXPECT_CALL(a, ReturnResult(3))
1345
      .InSequence(s);
1346

1347
  a.ReturnResult(1);
1348

1349
1350
  // May only be called after a.ReturnResult(2).
  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1351
1352
1353
1354
1355

  a.ReturnResult(2);
  a.ReturnResult(3);
}

1356
1357
1358
// Tests that the calls must be in strict order when a complete order
// is specified.
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1359
  MockA a;
1360
1361
  ON_CALL(a, ReturnResult(_))
      .WillByDefault(Return(Result()));
1362

1363
  Sequence s;
1364
  EXPECT_CALL(a, ReturnResult(1))
1365
1366
1367
      .InSequence(s);
  EXPECT_CALL(a, ReturnResult(2))
      .InSequence(s);
1368

1369
1370
  // May only be called after a.ReturnResult(1).
  EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1371

1372
1373
1374
  a.ReturnResult(1);
  a.ReturnResult(2);
}
1375

1376
1377
1378
1379
1380
1381
// Tests specifying a DAG using multiple sequences.
class PartialOrderTest : public testing::Test {
 protected:
  PartialOrderTest() {
    ON_CALL(a_, ReturnResult(_))
        .WillByDefault(Return(Result()));
1382

1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
    // Specifies this partial ordering:
    //
    // a.ReturnResult(1) ==>
    //                       a.ReturnResult(2) * n  ==>  a.ReturnResult(3)
    // b.DoB() * 2       ==>
    Sequence x, y;
    EXPECT_CALL(a_, ReturnResult(1))
        .InSequence(x);
    EXPECT_CALL(b_, DoB())
        .Times(2)
        .InSequence(y);
    EXPECT_CALL(a_, ReturnResult(2))
        .Times(AnyNumber())
        .InSequence(x, y);
    EXPECT_CALL(a_, ReturnResult(3))
        .InSequence(x);
  }
1400

1401
1402
1403
  MockA a_;
  MockB b_;
};
1404

1405
1406
1407
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
  a_.ReturnResult(1);
  b_.DoB();
1408

1409
1410
  // May only be called after the second DoB().
  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1411

1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
  b_.DoB();
  a_.ReturnResult(3);
}

TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
  // May only be called after ReturnResult(1).
  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");

  a_.ReturnResult(1);
  b_.DoB();
  b_.DoB();
  a_.ReturnResult(3);
}

TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
  // May only be called last.
  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");

  a_.ReturnResult(1);
  b_.DoB();
  b_.DoB();
  a_.ReturnResult(3);
}

TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
  a_.ReturnResult(1);
  b_.DoB();
  b_.DoB();
  a_.ReturnResult(3);

  // May only be called before ReturnResult(3).
  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
}

TEST(SequenceTest, Retirement) {
  MockA a;
  Sequence s;

  EXPECT_CALL(a, DoA(1))
      .InSequence(s);
  EXPECT_CALL(a, DoA(_))
      .InSequence(s)
      .RetiresOnSaturation();
  EXPECT_CALL(a, DoA(1))
      .InSequence(s);

  a.DoA(1);
  a.DoA(2);
  a.DoA(1);
}

1463
1464
1465
1466
1467
// Tests Expectation.

TEST(ExpectationTest, ConstrutorsWork) {
  MockA a;
  Expectation e1;  // Default ctor.
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482

  // Ctor from various forms of EXPECT_CALL.
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
  {
    Sequence s;
    Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
    Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
  }
  Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
  Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
  Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
  Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();

  Expectation e10 = e2;  // Copy ctor.
1483
1484

  EXPECT_THAT(e1, Ne(e2));
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
  EXPECT_THAT(e2, Eq(e10));

  a.DoA(2);
  a.DoA(3);
  a.DoA(4);
  a.DoA(5);
  a.DoA(6);
  a.DoA(7);
  a.DoA(8);
  a.DoA(9);
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
}

TEST(ExpectationTest, AssignmentWorks) {
  MockA a;
  Expectation e1;
  Expectation e2 = EXPECT_CALL(a, DoA(1));

  EXPECT_THAT(e1, Ne(e2));

  e1 = e2;
  EXPECT_THAT(e1, Eq(e2));

  a.DoA(1);
}

// Tests ExpectationSet.

TEST(ExpectationSetTest, MemberTypesAreCorrect) {
  ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
}

TEST(ExpectationSetTest, ConstructorsWork) {
  MockA a;

  Expectation e1;
  const Expectation e2;
  ExpectationSet es1;  // Default ctor.
  ExpectationSet es2 = EXPECT_CALL(a, DoA(1));  // Ctor from EXPECT_CALL.
  ExpectationSet es3 = e1;  // Ctor from Expectation.
  ExpectationSet es4(e1);   // Ctor from Expectation; alternative syntax.
  ExpectationSet es5 = e2;  // Ctor from const Expectation.
  ExpectationSet es6(e2);   // Ctor from const Expectation; alternative syntax.
  ExpectationSet es7 = es2;  // Copy ctor.

  EXPECT_EQ(0, es1.size());
  EXPECT_EQ(1, es2.size());
  EXPECT_EQ(1, es3.size());
  EXPECT_EQ(1, es4.size());
  EXPECT_EQ(1, es5.size());
  EXPECT_EQ(1, es6.size());
  EXPECT_EQ(1, es7.size());

  EXPECT_THAT(es3, Ne(es2));
  EXPECT_THAT(es4, Eq(es3));
  EXPECT_THAT(es5, Eq(es4));
  EXPECT_THAT(es6, Eq(es5));
  EXPECT_THAT(es7, Eq(es2));
  a.DoA(1);
}

TEST(ExpectationSetTest, AssignmentWorks) {
  ExpectationSet es1;
  ExpectationSet es2 = Expectation();

  es1 = es2;
  EXPECT_EQ(1, es1.size());
  EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
  EXPECT_THAT(es1, Eq(es2));
}

TEST(ExpectationSetTest, InsertionWorks) {
  ExpectationSet es1;
  Expectation e1;
  es1 += e1;
  EXPECT_EQ(1, es1.size());
  EXPECT_THAT(*(es1.begin()), Eq(e1));

  MockA a;
  Expectation e2 = EXPECT_CALL(a, DoA(1));
  es1 += e2;
  EXPECT_EQ(2, es1.size());

  ExpectationSet::const_iterator it1 = es1.begin();
  ExpectationSet::const_iterator it2 = it1;
  ++it2;
  EXPECT_TRUE(*it1 == e1 || *it2 == e1);  // e1 must be in the set.
  EXPECT_TRUE(*it1 == e2 || *it2 == e2);  // e2 must be in the set too.
  a.DoA(1);
}

TEST(ExpectationSetTest, SizeWorks) {
  ExpectationSet es;
  EXPECT_EQ(0, es.size());

  es += Expectation();
  EXPECT_EQ(1, es.size());

  MockA a;
  es += EXPECT_CALL(a, DoA(1));
  EXPECT_EQ(2, es.size());

  a.DoA(1);
}

TEST(ExpectationSetTest, IsEnumerable) {
  ExpectationSet es;
1591
  EXPECT_TRUE(es.begin() == es.end());
1592
1593
1594

  es += Expectation();
  ExpectationSet::const_iterator it = es.begin();
1595
  EXPECT_TRUE(it != es.end());
1596
1597
  EXPECT_THAT(*it, Eq(Expectation()));
  ++it;
1598
  EXPECT_TRUE(it== es.end());
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
}

// Tests the .After() clause.

TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
  MockA a;
  ExpectationSet es;
  es += EXPECT_CALL(a, DoA(1));
  es += EXPECT_CALL(a, DoA(2));
  EXPECT_CALL(a, DoA(3))
      .After(es);

  a.DoA(1);
  a.DoA(2);
  a.DoA(3);
}

TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
  MockA a;
  MockB b;
  // The following also verifies that const Expectation objects work
  // too.  Do not remove the const modifiers.
  const Expectation e1 = EXPECT_CALL(a, DoA(1));
  const Expectation e2 = EXPECT_CALL(b, DoB())
      .Times(2)
      .After(e1);
  EXPECT_CALL(a, DoA(2)).After(e2);

  a.DoA(1);
  b.DoB();
  b.DoB();
  a.DoA(2);
}

1633
1634
// Calls must be in strict order when specified so using .After().
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1635
1636
  MockA a;
  MockB b;
1637
1638
1639

  // Define ordering:
  //   a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1640
1641
1642
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(b, DoB())
      .After(e1);
1643
1644
  EXPECT_CALL(a, DoA(2))
      .After(e2);
1645
1646

  a.DoA(1);
1647
1648
1649

  // May only be called after DoB().
  EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1650
1651

  b.DoB();
1652
1653
1654
1655
1656
1657
1658
  a.DoA(2);
}

// Calls must be in strict order when specified so using .After().
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
  MockA a;
  MockB b;
1659

1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
  // Define ordering:
  //   a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(b, DoB())
      .Times(2)
      .After(e1);
  EXPECT_CALL(a, DoA(2))
      .After(e2);

  a.DoA(1);
1670
  b.DoB();
1671
1672
1673
1674
1675
1676

  // May only be called after the second DoB().
  EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");

  b.DoB();
  a.DoA(2);
1677
1678
1679
}

// Calls must satisfy the partial order when specified so.
1680
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1681
  MockA a;
1682
1683
1684
1685
1686
1687
  ON_CALL(a, ReturnResult(_))
      .WillByDefault(Return(Result()));

  // Define ordering:
  //   a.DoA(1) ==>
  //   a.DoA(2) ==> a.ReturnResult(3)
1688
1689
1690
  Expectation e = EXPECT_CALL(a, DoA(1));
  const ExpectationSet es = EXPECT_CALL(a, DoA(2));
  EXPECT_CALL(a, ReturnResult(3))
1691
      .After(e, es);
1692

1693
1694
  // May only be called last.
  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1695
1696
1697
1698
1699
1700

  a.DoA(2);
  a.DoA(1);
  a.ReturnResult(3);
}

1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
// Calls must satisfy the partial order when specified so.
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
  MockA a;

  // Define ordering:
  //   a.DoA(1) ==>
  //   a.DoA(2) ==> a.DoA(3)
  Expectation e = EXPECT_CALL(a, DoA(1));
  const ExpectationSet es = EXPECT_CALL(a, DoA(2));
  EXPECT_CALL(a, DoA(3))
      .After(e, es);

  a.DoA(2);

  // May only be called last.
  EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");

  a.DoA(1);
  a.DoA(3);
}

1722
// .After() can be combined with .InSequence().
1723
TEST(AfterTest, CanBeUsedWithInSequence) {
1724
1725
1726
1727
  MockA a;
  Sequence s;
  Expectation e = EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(2)).InSequence(s);
1728
1729
1730
  EXPECT_CALL(a, DoA(3))
      .InSequence(s)
      .After(e);
1731
1732

  a.DoA(1);
1733
1734
1735

  // May only be after DoA(2).
  EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1736
1737

  a.DoA(2);
1738
  a.DoA(3);
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
}

// .After() can be called multiple times.
TEST(AfterTest, CanBeCalledManyTimes) {
  MockA a;
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  Expectation e3 = EXPECT_CALL(a, DoA(3));
  EXPECT_CALL(a, DoA(4))
      .After(e1)
      .After(e2)
      .After(e3);

  a.DoA(3);
  a.DoA(1);
  a.DoA(2);
  a.DoA(4);
}

// .After() accepts up to 5 arguments.
TEST(AfterTest, AcceptsUpToFiveArguments) {
  MockA a;
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  Expectation e3 = EXPECT_CALL(a, DoA(3));
  ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
  ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
  EXPECT_CALL(a, DoA(6))
      .After(e1, e2, e3, es1, es2);

  a.DoA(5);
  a.DoA(2);
  a.DoA(4);
  a.DoA(1);
  a.DoA(3);
  a.DoA(6);
}

// .After() allows input to contain duplicated Expectations.
TEST(AfterTest, AcceptsDuplicatedInput) {
  MockA a;
1780
1781
1782
1783
1784
1785
  ON_CALL(a, ReturnResult(_))
      .WillByDefault(Return(Result()));

  // Define ordering:
  //   DoA(1) ==>
  //   DoA(2) ==> ReturnResult(3)
1786
1787
1788
1789
1790
1791
  Expectation e1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  ExpectationSet es;
  es += e1;
  es += e2;
  EXPECT_CALL(a, ReturnResult(3))
1792
      .After(e1, e2, es, e1);
1793
1794

  a.DoA(1);
1795
1796
1797

  // May only be after DoA(2).
  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817

  a.DoA(2);
  a.ReturnResult(3);
}

// An Expectation added to an ExpectationSet after it has been used in
// an .After() has no effect.
TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
  MockA a;
  ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
  Expectation e2 = EXPECT_CALL(a, DoA(2));
  EXPECT_CALL(a, DoA(3))
      .After(es1);
  es1 += e2;

  a.DoA(1);
  a.DoA(3);
  a.DoA(2);
}

1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
// Tests that Google Mock correctly handles calls to mock functions
// after a mock object owning one of their pre-requisites has died.

// Tests that calls that satisfy the original spec are successful.
TEST(DeletingMockEarlyTest, Success1) {
  MockB* const b1 = new MockB;
  MockA* const a = new MockA;
  MockB* const b2 = new MockB;

  {
    InSequence dummy;
    EXPECT_CALL(*b1, DoB(_))
        .WillOnce(Return(1));
    EXPECT_CALL(*a, Binary(_, _))
        .Times(AnyNumber())
        .WillRepeatedly(Return(true));
    EXPECT_CALL(*b2, DoB(_))
        .Times(AnyNumber())
        .WillRepeatedly(Return(2));
  }

  EXPECT_EQ(1, b1->DoB(1));
  delete b1;
  // a's pre-requisite has died.
  EXPECT_TRUE(a->Binary(0, 1));
  delete b2;
  // a's successor has died.
  EXPECT_TRUE(a->Binary(1, 2));
  delete a;
}

// Tests that calls that satisfy the original spec are successful.
TEST(DeletingMockEarlyTest, Success2) {
  MockB* const b1 = new MockB;
  MockA* const a = new MockA;
  MockB* const b2 = new MockB;

  {
    InSequence dummy;
    EXPECT_CALL(*b1, DoB(_))
        .WillOnce(Return(1));
    EXPECT_CALL(*a, Binary(_, _))
        .Times(AnyNumber());
    EXPECT_CALL(*b2, DoB(_))
        .Times(AnyNumber())
        .WillRepeatedly(Return(2));
  }

  delete a;  // a is trivially satisfied.
  EXPECT_EQ(1, b1->DoB(1));
  EXPECT_EQ(2, b2->DoB(2));
  delete b1;
  delete b2;
}

1873
1874
// Tests that it's OK to delete a mock object itself in its action.

1875
1876
1877
// Suppresses warning on unreferenced formal parameter in MSVC with
// -W4.
#ifdef _MSC_VER
1878
1879
# pragma warning(push)
# pragma warning(disable:4100)
1880
1881
#endif

1882
1883
ACTION_P(Delete, ptr) { delete ptr; }

1884
#ifdef _MSC_VER
1885
# pragma warning(pop)
1886
1887
#endif

1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
  MockA* const a = new MockA;
  EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
  a->DoA(42);  // This will cause a to be deleted.
}

TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
  MockA* const a = new MockA;
  EXPECT_CALL(*a, ReturnResult(_))
      .WillOnce(DoAll(Delete(a), Return(Result())));
  a->ReturnResult(42);  // This will cause a to be deleted.
}

// Tests that calls that violate the original spec yield failures.
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
TEST(DeletingMockEarlyTest, Failure1) {
  MockB* const b1 = new MockB;
  MockA* const a = new MockA;
  MockB* const b2 = new MockB;

  {
    InSequence dummy;
    EXPECT_CALL(*b1, DoB(_))
        .WillOnce(Return(1));
    EXPECT_CALL(*a, Binary(_, _))
        .Times(AnyNumber());
    EXPECT_CALL(*b2, DoB(_))
        .Times(AnyNumber())
        .WillRepeatedly(Return(2));
  }

  delete a;  // a is trivially satisfied.
  EXPECT_NONFATAL_FAILURE({
    b2->DoB(2);
  }, "Unexpected mock function call");
  EXPECT_EQ(1, b1->DoB(1));
  delete b1;
  delete b2;
}

1927
// Tests that calls that violate the original spec yield failures.
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
TEST(DeletingMockEarlyTest, Failure2) {
  MockB* const b1 = new MockB;
  MockA* const a = new MockA;
  MockB* const b2 = new MockB;

  {
    InSequence dummy;
    EXPECT_CALL(*b1, DoB(_));
    EXPECT_CALL(*a, Binary(_, _))
        .Times(AnyNumber());
    EXPECT_CALL(*b2, DoB(_))
        .Times(AnyNumber());
  }

  EXPECT_NONFATAL_FAILURE(delete b1,
                          "Actual: never called");
  EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
                          "Unexpected mock function call");
  EXPECT_NONFATAL_FAILURE(b2->DoB(1),
                          "Unexpected mock function call");
  delete a;
  delete b2;
}

class EvenNumberCardinality : public CardinalityInterface {
 public:
1954
1955
  // Returns true if and only if call_count calls will satisfy this
  // cardinality.
Abseil Team's avatar
Abseil Team committed
1956
  bool IsSatisfiedByCallCount(int call_count) const override {
1957
1958
1959
    return call_count % 2 == 0;
  }

1960
1961
  // Returns true if and only if call_count calls will saturate this
  // cardinality.
Abseil Team's avatar
Abseil Team committed
1962
  bool IsSaturatedByCallCount(int /* call_count */) const override {
1963
1964
    return false;
  }
1965
1966

  // Describes self to an ostream.
Abseil Team's avatar
Abseil Team committed
1967
  void DescribeTo(::std::ostream* os) const override {
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
    *os << "called even number of times";
  }
};

Cardinality EvenNumber() {
  return Cardinality(new EvenNumberCardinality);
}

TEST(ExpectationBaseTest,
     AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
  MockA* a = new MockA;
  Sequence s;

  EXPECT_CALL(*a, DoA(1))
      .Times(EvenNumber())
      .InSequence(s);
  EXPECT_CALL(*a, DoA(2))
      .Times(AnyNumber())
      .InSequence(s);
  EXPECT_CALL(*a, DoA(3))
      .Times(AnyNumber());

  a->DoA(3);
  a->DoA(1);
  EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
  EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
}

// The following tests verify the message generated when a mock
// function is called.

struct Printable {
};

inline void operator<<(::std::ostream& os, const Printable&) {
  os << "Printable";
}

struct Unprintable {
  Unprintable() : value(0) {}
  int value;
};

class MockC {
 public:
2013
2014
  MockC() {}

2015
  MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
2016
2017
                                const Printable& x, Unprintable y));
  MOCK_METHOD0(NonVoidMethod, int());  // NOLINT
2018
2019
2020

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
2021
2022
};

2023
2024
2025
class VerboseFlagPreservingFixture : public testing::Test {
 protected:
  VerboseFlagPreservingFixture()
Abseil Team's avatar
Abseil Team committed
2026
      : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}
2027

Abseil Team's avatar
Abseil Team committed
2028
  ~VerboseFlagPreservingFixture() override {
Abseil Team's avatar
Abseil Team committed
2029
    GMOCK_FLAG_SET(verbose, saved_verbose_flag_);
Abseil Team's avatar
Abseil Team committed
2030
  }
2031
2032

 private:
2033
  const std::string saved_verbose_flag_;
2034
2035
2036
2037

  GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
};

2038
#if GTEST_HAS_STREAM_REDIRECTION
2039

2040
// Tests that an uninteresting mock function call on a naggy mock
2041
2042
// generates a warning without the stack trace when
// --gmock_verbose=warning is specified.
2043
TEST(FunctionCallMessageTest,
2044
     UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
Abseil Team's avatar
Abseil Team committed
2045
  GMOCK_FLAG_SET(verbose, kWarningVerbosity);
2046
2047
  NaggyMock<MockC> c;
  CaptureStdout();
2048
  c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
  const std::string output = GetCapturedStdout();
  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
  EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
}

// Tests that an uninteresting mock function call on a naggy mock
// generates a warning containing the stack trace when
// --gmock_verbose=info is specified.
TEST(FunctionCallMessageTest,
     UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
Abseil Team's avatar
Abseil Team committed
2059
  GMOCK_FLAG_SET(verbose, kInfoVerbosity);
2060
  NaggyMock<MockC> c;
2061
  CaptureStdout();
2062
  c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
2063
  const std::string output = GetCapturedStdout();
2064
2065
  EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
  EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
2066
2067
2068

# ifndef NDEBUG

2069
2070
2071
2072
2073
  // We check the stack trace content in dbg-mode only, as opt-mode
  // may inline the call we are interested in seeing.

  // Verifies that a void mock function's name appears in the stack
  // trace.
2074
  EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
2075
2076
2077

  // Verifies that a non-void mock function's name appears in the
  // stack trace.
2078
  CaptureStdout();
2079
  c.NonVoidMethod();
2080
  const std::string output2 = GetCapturedStdout();
2081
  EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
2082
2083

# endif  // NDEBUG
2084
2085
}

2086
2087
2088
2089
// Tests that an uninteresting mock function call on a naggy mock
// causes the function arguments and return value to be printed.
TEST(FunctionCallMessageTest,
     UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
2090
  // A non-void mock function.
2091
  NaggyMock<MockB> b;
2092
  CaptureStdout();
2093
  b.DoB();
2094
  const std::string output1 = GetCapturedStdout();
2095
2096
2097
2098
  EXPECT_PRED_FORMAT2(
      IsSubstring,
      "Uninteresting mock function call - returning default value.\n"
      "    Function call: DoB()\n"
2099
      "          Returns: 0\n", output1.c_str());
2100
2101
2102
  // Makes sure the return value is printed.

  // A void mock function.
2103
  NaggyMock<MockC> c;
2104
  CaptureStdout();
2105
  c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
2106
  const std::string output2 = GetCapturedStdout();
2107
2108
2109
2110
2111
  EXPECT_THAT(output2.c_str(),
              ContainsRegex(
                  "Uninteresting mock function call - returning directly\\.\n"
                  "    Function call: VoidMethod"
                  "\\(false, 5, \"Hi\", NULL, @.+ "
zhanyong.wan's avatar
zhanyong.wan committed
2112
                  "Printable, 4-byte object <00-00 00-00>\\)"));
2113
2114
2115
2116
2117
  // A void function has no return value to print.
}

// Tests how the --gmock_verbose flag affects Google Mock's output.

2118
class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
2119
2120
2121
2122
2123
 public:
  // Verifies that the given Google Mock output is correct.  (When
  // should_print is true, the output should match the given regex and
  // contain the given function name in the stack trace.  When it's
  // false, the output should be empty.)
2124
  void VerifyOutput(const std::string& output, bool should_print,
2125
2126
                    const std::string& expected_substring,
                    const std::string& function_name) {
2127
    if (should_print) {
2128
      EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2129
# ifndef NDEBUG
2130
2131
      // We check the stack trace content in dbg-mode only, as opt-mode
      // may inline the call we are interested in seeing.
2132
      EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2133
# else
2134
2135
      // Suppresses 'unused function parameter' warnings.
      static_cast<void>(function_name);
2136
# endif  // NDEBUG
2137
    } else {
2138
      EXPECT_STREQ("", output.c_str());
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
    }
  }

  // Tests how the flag affects expected calls.
  void TestExpectedCall(bool should_print) {
    MockA a;
    EXPECT_CALL(a, DoA(5));
    EXPECT_CALL(a, Binary(_, 1))
        .WillOnce(Return(true));

    // A void-returning function.
2150
    CaptureStdout();
2151
2152
    a.DoA(5);
    VerifyOutput(
2153
        GetCapturedStdout(),
2154
        should_print,
2155
2156
2157
2158
        "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
        "    Function call: DoA(5)\n"
        "Stack trace:\n",
        "DoA");
2159
2160

    // A non-void-returning function.
2161
    CaptureStdout();
2162
2163
    a.Binary(2, 1);
    VerifyOutput(
2164
        GetCapturedStdout(),
2165
        should_print,
2166
2167
        "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
        "    Function call: Binary(2, 1)\n"
2168
        "          Returns: true\n"
2169
2170
        "Stack trace:\n",
        "Binary");
2171
2172
  }

2173
2174
2175
  // Tests how the flag affects uninteresting calls on a naggy mock.
  void TestUninterestingCallOnNaggyMock(bool should_print) {
    NaggyMock<MockA> a;
2176
    const std::string note =
2177
2178
2179
        "NOTE: You can safely ignore the above warning unless this "
        "call should not happen.  Do not suppress it by blindly adding "
        "an EXPECT_CALL() if you don't mean to enforce the call.  "
Gennadiy Civil's avatar
 
Gennadiy Civil committed
2180
        "See "
Abseil Team's avatar
Abseil Team committed
2181
2182
        "https://github.com/google/googletest/blob/master/docs/"
        "gmock_cook_book.md#"
2183
        "knowing-when-to-expect for details.";
2184
2185

    // A void-returning function.
2186
    CaptureStdout();
2187
2188
    a.DoA(5);
    VerifyOutput(
2189
        GetCapturedStdout(),
2190
2191
        should_print,
        "\nGMOCK WARNING:\n"
2192
        "Uninteresting mock function call - returning directly.\n"
2193
        "    Function call: DoA(5)\n" +
2194
        note,
2195
        "DoA");
2196
2197

    // A non-void-returning function.
2198
    CaptureStdout();
2199
2200
    a.Binary(2, 1);
    VerifyOutput(
2201
        GetCapturedStdout(),
2202
2203
        should_print,
        "\nGMOCK WARNING:\n"
2204
2205
        "Uninteresting mock function call - returning default value.\n"
        "    Function call: Binary(2, 1)\n"
2206
        "          Returns: false\n" +
2207
        note,
2208
        "Binary");
2209
2210
2211
2212
2213
2214
  }
};

// Tests that --gmock_verbose=info causes both expected and
// uninteresting calls to be reported.
TEST_F(GMockVerboseFlagTest, Info) {
Abseil Team's avatar
Abseil Team committed
2215
  GMOCK_FLAG_SET(verbose, kInfoVerbosity);
2216
  TestExpectedCall(true);
2217
  TestUninterestingCallOnNaggyMock(true);
2218
2219
2220
2221
2222
}

// Tests that --gmock_verbose=warning causes uninteresting calls to be
// reported.
TEST_F(GMockVerboseFlagTest, Warning) {
Abseil Team's avatar
Abseil Team committed
2223
  GMOCK_FLAG_SET(verbose, kWarningVerbosity);
2224
  TestExpectedCall(false);
2225
  TestUninterestingCallOnNaggyMock(true);
2226
2227
2228
2229
2230
}

// Tests that --gmock_verbose=warning causes neither expected nor
// uninteresting calls to be reported.
TEST_F(GMockVerboseFlagTest, Error) {
Abseil Team's avatar
Abseil Team committed
2231
  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2232
  TestExpectedCall(false);
2233
  TestUninterestingCallOnNaggyMock(false);
2234
2235
2236
2237
2238
}

// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
// as --gmock_verbose=warning.
TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
Abseil Team's avatar
Abseil Team committed
2239
  GMOCK_FLAG_SET(verbose, "invalid");  // Treated as "warning".
2240
  TestExpectedCall(false);
2241
  TestUninterestingCallOnNaggyMock(true);
2242
2243
}

2244
#endif  // GTEST_HAS_STREAM_REDIRECTION
2245

2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
// A helper class that generates a failure when printed.  We use it to
// ensure that Google Mock doesn't print a value (even to an internal
// buffer) when it is not supposed to do so.
class PrintMeNot {};

void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
  ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
                << "printed even to an internal buffer.";
}

class LogTestHelper {
 public:
2258
2259
  LogTestHelper() {}

2260
  MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2261
2262
2263

 private:
  GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
2264
2265
};

2266
class GMockLogTest : public VerboseFlagPreservingFixture {
2267
2268
2269
2270
2271
 protected:
  LogTestHelper helper_;
};

TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
Abseil Team's avatar
Abseil Team committed
2272
  GMOCK_FLAG_SET(verbose, kWarningVerbosity);
2273
2274
2275
2276
2277
2278
  EXPECT_CALL(helper_, Foo(_))
      .WillOnce(Return(PrintMeNot()));
  helper_.Foo(PrintMeNot());  // This is an expected call.
}

TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
Abseil Team's avatar
Abseil Team committed
2279
  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2280
2281
2282
2283
2284
2285
  EXPECT_CALL(helper_, Foo(_))
      .WillOnce(Return(PrintMeNot()));
  helper_.Foo(PrintMeNot());  // This is an expected call.
}

TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
Abseil Team's avatar
Abseil Team committed
2286
  GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2287
2288
2289
2290
2291
2292
2293
  ON_CALL(helper_, Foo(_))
      .WillByDefault(Return(PrintMeNot()));
  helper_.Foo(PrintMeNot());  // This should generate a warning.
}

// Tests Mock::AllowLeak().

2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
  MockA* a = new MockA;
  Mock::AllowLeak(a);
}

TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
  MockA* a = new MockA;
  Mock::AllowLeak(a);
  ON_CALL(*a, DoA(_)).WillByDefault(Return());
  a->DoA(0);
}

TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
  MockA* a = new MockA;
  ON_CALL(*a, DoA(_)).WillByDefault(Return());
  Mock::AllowLeak(a);
}

TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
  MockA* a = new MockA;
  Mock::AllowLeak(a);
  EXPECT_CALL(*a, DoA(_));
  a->DoA(0);
}

TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
  MockA* a = new MockA;
  EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
  Mock::AllowLeak(a);
}

TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
  MockA* a = new MockA;
  ON_CALL(*a, DoA(_)).WillByDefault(Return());
  EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
  Mock::AllowLeak(a);
}
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366

// Tests that we can verify and clear a mock object's expectations
// when none of its methods has expectations.
TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
  MockB b;
  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that we can verify and clear a mock object's expectations
// when some, but not all, of its methods have expectations *and* the
// verification succeeds.
TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
  MockB b;
  EXPECT_CALL(b, DoB())
      .WillOnce(Return(1));
  b.DoB();
  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that we can verify and clear a mock object's expectations
// when some, but not all, of its methods have expectations *and* the
// verification fails.
TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
  MockB b;
  EXPECT_CALL(b, DoB())
      .WillOnce(Return(1));
2367
  bool result = true;
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
                          "Actual: never called");
  ASSERT_FALSE(result);

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that we can verify and clear a mock object's expectations
// when all of its methods have expectations.
TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
  MockB b;
  EXPECT_CALL(b, DoB())
      .WillOnce(Return(1));
  EXPECT_CALL(b, DoB(_))
      .WillOnce(Return(2));
  b.DoB();
  b.DoB(1);
  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that we can verify and clear a mock object's expectations
// when a method has more than one expectation.
TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
  MockB b;
  EXPECT_CALL(b, DoB(0))
      .WillOnce(Return(1));
  EXPECT_CALL(b, DoB(_))
      .WillOnce(Return(2));
  b.DoB(1);
2405
  bool result = true;
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
                          "Actual: never called");
  ASSERT_FALSE(result);

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that we can call VerifyAndClearExpectations() on the same
// mock object multiple times.
TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
  MockB b;
  EXPECT_CALL(b, DoB());
  b.DoB();
  Mock::VerifyAndClearExpectations(&b);

  EXPECT_CALL(b, DoB(_))
      .WillOnce(Return(1));
  b.DoB(1);
  Mock::VerifyAndClearExpectations(&b);
  Mock::VerifyAndClearExpectations(&b);

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that we can clear a mock object's default actions when none
// of its methods has default actions.
TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
  MockB b;
  // If this crashes or generates a failure, the test will catch it.
  Mock::VerifyAndClear(&b);
  EXPECT_EQ(0, b.DoB());
}

// Tests that we can clear a mock object's default actions when some,
// but not all of its methods have default actions.
TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
  MockB b;
  ON_CALL(b, DoB())
      .WillByDefault(Return(1));

  Mock::VerifyAndClear(&b);

  // Verifies that the default action of int DoB() was removed.
  EXPECT_EQ(0, b.DoB());
}

// Tests that we can clear a mock object's default actions when all of
// its methods have default actions.
TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
  MockB b;
  ON_CALL(b, DoB())
      .WillByDefault(Return(1));
  ON_CALL(b, DoB(_))
      .WillByDefault(Return(2));

  Mock::VerifyAndClear(&b);

  // Verifies that the default action of int DoB() was removed.
  EXPECT_EQ(0, b.DoB());

  // Verifies that the default action of int DoB(int) was removed.
  EXPECT_EQ(0, b.DoB(0));
}

// Tests that we can clear a mock object's default actions when a
// method has more than one ON_CALL() set on it.
TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
  MockB b;
  ON_CALL(b, DoB(0))
      .WillByDefault(Return(1));
  ON_CALL(b, DoB(_))
      .WillByDefault(Return(2));

  Mock::VerifyAndClear(&b);

  // Verifies that the default actions (there are two) of int DoB(int)
  // were removed.
  EXPECT_EQ(0, b.DoB(0));
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that we can call VerifyAndClear() on a mock object multiple
// times.
TEST(VerifyAndClearTest, CanCallManyTimes) {
  MockB b;
  ON_CALL(b, DoB())
      .WillByDefault(Return(1));
  Mock::VerifyAndClear(&b);
  Mock::VerifyAndClear(&b);

  ON_CALL(b, DoB(_))
      .WillByDefault(Return(1));
  Mock::VerifyAndClear(&b);

  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that VerifyAndClear() works when the verification succeeds.
TEST(VerifyAndClearTest, Success) {
  MockB b;
  ON_CALL(b, DoB())
      .WillByDefault(Return(1));
  EXPECT_CALL(b, DoB(1))
      .WillOnce(Return(2));

  b.DoB();
  b.DoB(1);
  ASSERT_TRUE(Mock::VerifyAndClear(&b));

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that VerifyAndClear() works when the verification fails.
TEST(VerifyAndClearTest, Failure) {
  MockB b;
  ON_CALL(b, DoB(_))
      .WillByDefault(Return(1));
  EXPECT_CALL(b, DoB())
      .WillOnce(Return(2));

  b.DoB(1);
2537
  bool result = true;
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
                          "Actual: never called");
  ASSERT_FALSE(result);

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that VerifyAndClear() works when the default actions and
// expectations are set on a const mock object.
TEST(VerifyAndClearTest, Const) {
  MockB b;
  ON_CALL(Const(b), DoB())
      .WillByDefault(Return(1));

  EXPECT_CALL(Const(b), DoB())
      .WillOnce(DoDefault())
      .WillOnce(Return(2));

  b.DoB();
  b.DoB();
  ASSERT_TRUE(Mock::VerifyAndClear(&b));

  // There should be no expectations on the methods now, so we can
  // freely call them.
  EXPECT_EQ(0, b.DoB());
  EXPECT_EQ(0, b.DoB(1));
}

// Tests that we can set default actions and expectations on a mock
// object after VerifyAndClear() has been called on it.
TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
  MockB b;
  ON_CALL(b, DoB())
      .WillByDefault(Return(1));
  EXPECT_CALL(b, DoB(_))
      .WillOnce(Return(2));
  b.DoB(1);

  Mock::VerifyAndClear(&b);

  EXPECT_CALL(b, DoB())
      .WillOnce(Return(3));
  ON_CALL(b, DoB(_))
      .WillByDefault(Return(4));

  EXPECT_EQ(3, b.DoB());
  EXPECT_EQ(4, b.DoB(1));
}

// Tests that calling VerifyAndClear() on one mock object does not
// affect other mock objects (either of the same type or not).
TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
  MockA a;
  MockB b1;
  MockB b2;

  ON_CALL(a, Binary(_, _))
      .WillByDefault(Return(true));
  EXPECT_CALL(a, Binary(_, _))
      .WillOnce(DoDefault())
      .WillOnce(Return(false));

  ON_CALL(b1, DoB())
      .WillByDefault(Return(1));
  EXPECT_CALL(b1, DoB(_))
      .WillOnce(Return(2));

  ON_CALL(b2, DoB())
      .WillByDefault(Return(3));
  EXPECT_CALL(b2, DoB(_));

  b2.DoB(0);
  Mock::VerifyAndClear(&b2);

  // Verifies that the default actions and expectations of a and b1
  // are still in effect.
  EXPECT_TRUE(a.Binary(0, 0));
  EXPECT_FALSE(a.Binary(0, 0));

  EXPECT_EQ(1, b1.DoB());
  EXPECT_EQ(2, b1.DoB(0));
}

2624
2625
TEST(VerifyAndClearTest,
     DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
misterg's avatar
misterg committed
2626
  std::shared_ptr<MockA> a(new MockA);
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
  ReferenceHoldingMock test_mock;

  // EXPECT_CALL stores a reference to a inside test_mock.
  EXPECT_CALL(test_mock, AcceptReference(_))
      .WillRepeatedly(SetArgPointee<0>(a));

  // Throw away the reference to the mock that we have in a. After this, the
  // only reference to it is stored by test_mock.
  a.reset();

  // When test_mock goes out of scope, it destroys the last remaining reference
  // to the mock object originally pointed to by a. This will cause the MockA
  // destructor to be called from inside the ReferenceHoldingMock destructor.
  // The state of all mocks is protected by a single global lock, but there
  // should be no deadlock.
}

TEST(VerifyAndClearTest,
     DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
misterg's avatar
misterg committed
2646
  std::shared_ptr<MockA> a(new MockA);
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
  ReferenceHoldingMock test_mock;

  // ON_CALL stores a reference to a inside test_mock.
  ON_CALL(test_mock, AcceptReference(_))
      .WillByDefault(SetArgPointee<0>(a));

  // Throw away the reference to the mock that we have in a. After this, the
  // only reference to it is stored by test_mock.
  a.reset();

  // When test_mock goes out of scope, it destroys the last remaining reference
  // to the mock object originally pointed to by a. This will cause the MockA
  // destructor to be called from inside the ReferenceHoldingMock destructor.
  // The state of all mocks is protected by a single global lock, but there
  // should be no deadlock.
}

2664
2665
2666
2667
2668
// Tests that a mock function's action can call a mock function
// (either the same function or a different one) either as an explicit
// action or as a default action without causing a dead lock.  It
// verifies that the action is not performed inside the critical
// section.
vladlosev's avatar
vladlosev committed
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
TEST(SynchronizationTest, CanCallMockMethodInAction) {
  MockA a;
  MockC c;
  ON_CALL(a, DoA(_))
      .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
                                                    &MockC::NonVoidMethod)));
  EXPECT_CALL(a, DoA(1));
  EXPECT_CALL(a, DoA(1))
      .WillOnce(Invoke(&a, &MockA::DoA))
      .RetiresOnSaturation();
  EXPECT_CALL(c, NonVoidMethod());
2680

vladlosev's avatar
vladlosev committed
2681
2682
2683
2684
2685
  a.DoA(1);
  // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
  // which will in turn match the first EXPECT_CALL() and trigger a call to
  // c.NonVoidMethod() that was specified by the ON_CALL() since the first
  // EXPECT_CALL() did not specify an action.
2686
2687
}

2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
  MockA a;
  int do_a_arg0 = 0;
  ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
  int do_a_47_arg0 = 0;
  ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));

  a.DoA(17);
  EXPECT_THAT(do_a_arg0, 17);
  EXPECT_THAT(do_a_47_arg0, 0);
  a.DoA(47);
  EXPECT_THAT(do_a_arg0, 17);
  EXPECT_THAT(do_a_47_arg0, 47);

  ON_CALL(a, Binary).WillByDefault(Return(true));
  ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
  EXPECT_THAT(a.Binary(14, 17), true);
  EXPECT_THAT(a.Binary(17, 14), false);
}

TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
  MockB b;
  ON_CALL(b, DoB()).WillByDefault(Return(9));
  ON_CALL(b, DoB(5)).WillByDefault(Return(11));

  EXPECT_THAT(b.DoB(), 9);
  EXPECT_THAT(b.DoB(1), 0);  // default value
  EXPECT_THAT(b.DoB(5), 11);
}

struct MockWithConstMethods {
 public:
  MOCK_CONST_METHOD1(Foo, int(int));
  MOCK_CONST_METHOD2(Bar, int(int, const char*));
};

TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
  MockWithConstMethods mock;
  ON_CALL(mock, Foo).WillByDefault(Return(7));
  ON_CALL(mock, Bar).WillByDefault(Return(33));

  EXPECT_THAT(mock.Foo(17), 7);
  EXPECT_THAT(mock.Bar(27, "purple"), 33);
}

class MockConstOverload {
 public:
  MOCK_METHOD1(Overloaded, int(int));
  MOCK_CONST_METHOD1(Overloaded, int(int));
};

TEST(ParameterlessExpectationsTest,
     CanSetExpectationsForConstOverloadedMethods) {
  MockConstOverload mock;
  ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
  ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
  ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
  ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));

  EXPECT_THAT(mock.Overloaded(1), 7);
  EXPECT_THAT(mock.Overloaded(5), 9);
  EXPECT_THAT(mock.Overloaded(7), 7);

  const MockConstOverload& const_mock = mock;
  EXPECT_THAT(const_mock.Overloaded(1), 0);
  EXPECT_THAT(const_mock.Overloaded(5), 11);
  EXPECT_THAT(const_mock.Overloaded(7), 13);
}

2757
}  // namespace
2758

2759
// Allows the user to define their own main and then invoke gmock_main
2760
2761
2762
2763
2764
// from it. This might be necessary on some platforms which require
// specific setup and teardown.
#if GMOCK_RENAME_MAIN
int gmock_main(int argc, char **argv) {
#else
2765
int main(int argc, char **argv) {
2766
#endif  // GMOCK_RENAME_MAIN
2767
2768
2769
  testing::InitGoogleMock(&argc, argv);
  // Ensures that the tests pass no matter what value of
  // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
Abseil Team's avatar
Abseil Team committed
2770
2771
  GMOCK_FLAG_SET(catch_leaked_mocks, true);
  GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);
2772
2773
2774

  return RUN_ALL_TESTS();
}