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