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
48namespace testing {
49namespace internal {
50
51// Helper class for testing the Expectation class template.
52class ExpectationTester {
53 public:
54 // Sets the call count of the given expectation to the given number.
55 void SetCallCount(int n, ExpectationBase* exp) {
56 exp->call_count_ = n;
57 }
58};
59
60} // namespace internal
61} // namespace testing
62
63namespace {
64
65using testing::_;
66using testing::AnyNumber;
67using testing::AtLeast;
68using testing::AtMost;
69using testing::Between;
70using testing::Cardinality;
71using testing::CardinalityInterface;
72using testing::ContainsRegex;
73using testing::Const;
74using testing::DoAll;
75using testing::DoDefault;
76using testing::Eq;
77using testing::Expectation;
78using testing::ExpectationSet;
79using testing::GMOCK_FLAG(verbose);
80using testing::Gt;
81using testing::IgnoreResult;
82using testing::InSequence;
83using testing::Invoke;
84using testing::InvokeWithoutArgs;
85using testing::IsNotSubstring;
86using testing::IsSubstring;
87using testing::Lt;
88using testing::Message;
89using testing::Mock;
90using testing::NaggyMock;
91using testing::Ne;
92using testing::Return;
93using testing::SaveArg;
94using testing::Sequence;
95using testing::SetArgPointee;
96using testing::internal::ExpectationTester;
97using testing::internal::FormatFileLocation;
98using testing::internal::kAllow;
99using testing::internal::kErrorVerbosity;
100using testing::internal::kFail;
101using testing::internal::kInfoVerbosity;
102using testing::internal::kWarn;
103using testing::internal::kWarningVerbosity;
104
105#if GTEST_HAS_STREAM_REDIRECTION
106using testing::HasSubstr;
107using testing::internal::CaptureStdout;
108using testing::internal::GetCapturedStdout;
109#endif
110
111class Incomplete;
112
113class 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.
121void PrintTo(const Incomplete& x, ::std::ostream* os);
122
123TEST(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.
135void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
136 *os << "incomplete";
137}
138
139class Result {};
140
141// A type that's not default constructible.
142class NonDefaultConstructible {
143 public:
144 explicit NonDefaultConstructible(int /* dummy */) {}
145};
146
147class MockA {
148 public:
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
161class MockB {
162 public:
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
172class ReferenceHoldingMock {
173 public:
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
189class CC {
190 public:
191 virtual ~CC() {}
192 virtual int Method() = 0;
193};
194class MockCC : public CC {
195 public:
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.
205TEST(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.
212TEST(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.
219TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
220 MockCC cc;
221 EXPECT_CALL(cc, Method());
222 cc.Method();
223}
224
225// Tests that it works, too.
226TEST(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.
236TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
237 MockA a;
238 MockA* pa = &a;
239
240 ON_CALL(*pa++, DoA(_));
241 EXPECT_EQ(&a + 1, pa);
242}
243
244TEST(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
254TEST(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
264TEST(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
275TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
276 MockA a;
277
278 EXPECT_DEATH_IF_SUPPORTED({
279 ON_CALL(a, DoA(5));
280 a.DoA(5);
281 }, "");
282}
283
284TEST(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.
296TEST(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
305TEST(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
316TEST(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
326TEST(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
338TEST(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
358TEST(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
373TEST(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
386TEST(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
399TEST(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
411TEST(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
422TEST(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
437TEST(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
450TEST(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
464TEST(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
475TEST(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
485TEST(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
497TEST(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
511TEST(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
522TEST(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
532TEST(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
543TEST(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
555TEST(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.
577TEST(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.
613TEST(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.
679TEST(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
698TEST(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.
758TEST(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.
767TEST(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.
777TEST(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.
793TEST(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.
806TEST(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.
817TEST(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.
831TEST(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
863TEST(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.
894TEST(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.
908TEST(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().
923TEST(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
954TEST(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
968TEST(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.
984TEST(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.
999TEST(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.
1025TEST(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.
1074TEST(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.
1094TEST(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.
1108TEST(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.
1121TEST(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
1176TEST(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.
1191TEST(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.
1217TEST(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.
1231TEST(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
1247TEST(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
1264TEST(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
1287TEST(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.
1307TEST(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.
1335TEST(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.
1359TEST(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.
1378class PartialOrderTest : public testing::Test {
1379 protected:
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
1406TEST_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
1417TEST_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
1427TEST_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
1437TEST_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
1447TEST(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
1466TEST(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
1498TEST(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
1513TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1514 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1515}
1516
1517TEST(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
1546TEST(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
1556TEST(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
1576TEST(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
1590TEST(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
1604TEST(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
1617TEST(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().
1635TEST(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().
1657TEST(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.
1681TEST(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.
1703TEST(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().
1724TEST(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.
1743TEST(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.
1760TEST(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.
1779TEST(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.
1806TEST(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.
1823TEST(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.
1851TEST(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
1883ACTION_P(Delete, ptr) { delete ptr; }
1884
1885#ifdef _MSC_VER
1886# pragma warning(pop)
1887#endif
1888
1889TEST(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
1895TEST(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.
1903TEST(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.
1929TEST(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
1953class EvenNumberCardinality : public CardinalityInterface {
1954 public:
1955 // Returns true if and only if call_count calls will satisfy this
1956 // cardinality.
1957 bool IsSatisfiedByCallCount(int call_count) const override {
1958 return call_count % 2 == 0;
1959 }
1960
1961 // Returns true if and only if call_count calls will saturate this
1962 // cardinality.
1963 bool IsSaturatedByCallCount(int /* call_count */) const override {
1964 return false;
1965 }
1966
1967 // Describes self to an ostream.
1968 void DescribeTo(::std::ostream* os) const override {
1969 *os << "called even number of times";
1970 }
1971};
1972
1973Cardinality EvenNumber() {
1974 return Cardinality(new EvenNumberCardinality);
1975}
1976
1977TEST(ExpectationBaseTest,
1978 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1979 MockA* a = new MockA;
1980 Sequence s;
1981
1982 EXPECT_CALL(*a, DoA(1))
1983 .Times(EvenNumber())
1984 .InSequence(s);
1985 EXPECT_CALL(*a, DoA(2))
1986 .Times(AnyNumber())
1987 .InSequence(s);
1988 EXPECT_CALL(*a, DoA(3))
1989 .Times(AnyNumber());
1990
1991 a->DoA(3);
1992 a->DoA(1);
1993 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1994 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1995}
1996
1997// The following tests verify the message generated when a mock
1998// function is called.
1999
2000struct Printable {
2001};
2002
2003inline void operator<<(::std::ostream& os, const Printable&) {
2004 os << "Printable";
2005}
2006
2007struct Unprintable {
2008 Unprintable() : value(0) {}
2009 int value;
2010};
2011
2012class MockC {
2013 public:
2014 MockC() {}
2015
2016 MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
2017 const Printable& x, Unprintable y));
2018 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
2019
2020 private:
2021 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
2022};
2023
2024class VerboseFlagPreservingFixture : public testing::Test {
2025 protected:
2026 VerboseFlagPreservingFixture()
2027 : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
2028
2029 ~VerboseFlagPreservingFixture() override {
2030 GMOCK_FLAG(verbose) = saved_verbose_flag_;
2031 }
2032
2033 private:
2034 const std::string saved_verbose_flag_;
2035
2036 GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
2037};
2038
2039#if GTEST_HAS_STREAM_REDIRECTION
2040
2041// Tests that an uninteresting mock function call on a naggy mock
2042// generates a warning without the stack trace when
2043// --gmock_verbose=warning is specified.
2044TEST(FunctionCallMessageTest,
2045 UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
2046 GMOCK_FLAG(verbose) = kWarningVerbosity;
2047 NaggyMock<MockC> c;
2048 CaptureStdout();
2049 c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
2050 const std::string output = GetCapturedStdout();
2051 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2052 EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
2053}
2054
2055// Tests that an uninteresting mock function call on a naggy mock
2056// generates a warning containing the stack trace when
2057// --gmock_verbose=info is specified.
2058TEST(FunctionCallMessageTest,
2059 UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
2060 GMOCK_FLAG(verbose) = kInfoVerbosity;
2061 NaggyMock<MockC> c;
2062 CaptureStdout();
2063 c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
2064 const std::string output = GetCapturedStdout();
2065 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2066 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
2067
2068# ifndef NDEBUG
2069
2070 // We check the stack trace content in dbg-mode only, as opt-mode
2071 // may inline the call we are interested in seeing.
2072
2073 // Verifies that a void mock function's name appears in the stack
2074 // trace.
2075 EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
2076
2077 // Verifies that a non-void mock function's name appears in the
2078 // stack trace.
2079 CaptureStdout();
2080 c.NonVoidMethod();
2081 const std::string output2 = GetCapturedStdout();
2082 EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
2083
2084# endif // NDEBUG
2085}
2086
2087// Tests that an uninteresting mock function call on a naggy mock
2088// causes the function arguments and return value to be printed.
2089TEST(FunctionCallMessageTest,
2090 UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
2091 // A non-void mock function.
2092 NaggyMock<MockB> b;
2093 CaptureStdout();
2094 b.DoB();
2095 const std::string output1 = GetCapturedStdout();
2096 EXPECT_PRED_FORMAT2(
2097 IsSubstring,
2098 "Uninteresting mock function call - returning default value.\n"
2099 " Function call: DoB()\n"
2100 " Returns: 0\n", output1.c_str());
2101 // Makes sure the return value is printed.
2102
2103 // A void mock function.
2104 NaggyMock<MockC> c;
2105 CaptureStdout();
2106 c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
2107 const std::string output2 = GetCapturedStdout();
2108 EXPECT_THAT(output2.c_str(),
2109 ContainsRegex(
2110 "Uninteresting mock function call - returning directly\\.\n"
2111 " Function call: VoidMethod"
2112 "\\(false, 5, \"Hi\", NULL, @.+ "
2113 "Printable, 4-byte object <00-00 00-00>\\)"));
2114 // A void function has no return value to print.
2115}
2116
2117// Tests how the --gmock_verbose flag affects Google Mock's output.
2118
2119class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
2120 public:
2121 // Verifies that the given Google Mock output is correct. (When
2122 // should_print is true, the output should match the given regex and
2123 // contain the given function name in the stack trace. When it's
2124 // false, the output should be empty.)
2125 void VerifyOutput(const std::string& output, bool should_print,
2126 const std::string& expected_substring,
2127 const std::string& function_name) {
2128 if (should_print) {
2129 EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2130# ifndef NDEBUG
2131 // We check the stack trace content in dbg-mode only, as opt-mode
2132 // may inline the call we are interested in seeing.
2133 EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2134# else
2135 // Suppresses 'unused function parameter' warnings.
2136 static_cast<void>(function_name);
2137# endif // NDEBUG
2138 } else {
2139 EXPECT_STREQ("", output.c_str());
2140 }
2141 }
2142
2143 // Tests how the flag affects expected calls.
2144 void TestExpectedCall(bool should_print) {
2145 MockA a;
2146 EXPECT_CALL(a, DoA(5));
2147 EXPECT_CALL(a, Binary(_, 1))
2148 .WillOnce(Return(true));
2149
2150 // A void-returning function.
2151 CaptureStdout();
2152 a.DoA(5);
2153 VerifyOutput(
2154 GetCapturedStdout(),
2155 should_print,
2156 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2157 " Function call: DoA(5)\n"
2158 "Stack trace:\n",
2159 "DoA");
2160
2161 // A non-void-returning function.
2162 CaptureStdout();
2163 a.Binary(2, 1);
2164 VerifyOutput(
2165 GetCapturedStdout(),
2166 should_print,
2167 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2168 " Function call: Binary(2, 1)\n"
2169 " Returns: true\n"
2170 "Stack trace:\n",
2171 "Binary");
2172 }
2173
2174 // Tests how the flag affects uninteresting calls on a naggy mock.
2175 void TestUninterestingCallOnNaggyMock(bool should_print) {
2176 NaggyMock<MockA> a;
2177 const std::string note =
2178 "NOTE: You can safely ignore the above warning unless this "
2179 "call should not happen. Do not suppress it by blindly adding "
2180 "an EXPECT_CALL() if you don't mean to enforce the call. "
2181 "See "
2182 "https://github.com/google/googletest/blob/master/googlemock/docs/"
2183 "cook_book.md#"
2184 "knowing-when-to-expect for details.";
2185
2186 // A void-returning function.
2187 CaptureStdout();
2188 a.DoA(5);
2189 VerifyOutput(
2190 GetCapturedStdout(),
2191 should_print,
2192 "\nGMOCK WARNING:\n"
2193 "Uninteresting mock function call - returning directly.\n"
2194 " Function call: DoA(5)\n" +
2195 note,
2196 "DoA");
2197
2198 // A non-void-returning function.
2199 CaptureStdout();
2200 a.Binary(2, 1);
2201 VerifyOutput(
2202 GetCapturedStdout(),
2203 should_print,
2204 "\nGMOCK WARNING:\n"
2205 "Uninteresting mock function call - returning default value.\n"
2206 " Function call: Binary(2, 1)\n"
2207 " Returns: false\n" +
2208 note,
2209 "Binary");
2210 }
2211};
2212
2213// Tests that --gmock_verbose=info causes both expected and
2214// uninteresting calls to be reported.
2215TEST_F(GMockVerboseFlagTest, Info) {
2216 GMOCK_FLAG(verbose) = kInfoVerbosity;
2217 TestExpectedCall(true);
2218 TestUninterestingCallOnNaggyMock(true);
2219}
2220
2221// Tests that --gmock_verbose=warning causes uninteresting calls to be
2222// reported.
2223TEST_F(GMockVerboseFlagTest, Warning) {
2224 GMOCK_FLAG(verbose) = kWarningVerbosity;
2225 TestExpectedCall(false);
2226 TestUninterestingCallOnNaggyMock(true);
2227}
2228
2229// Tests that --gmock_verbose=warning causes neither expected nor
2230// uninteresting calls to be reported.
2231TEST_F(GMockVerboseFlagTest, Error) {
2232 GMOCK_FLAG(verbose) = kErrorVerbosity;
2233 TestExpectedCall(false);
2234 TestUninterestingCallOnNaggyMock(false);
2235}
2236
2237// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2238// as --gmock_verbose=warning.
2239TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2240 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
2241 TestExpectedCall(false);
2242 TestUninterestingCallOnNaggyMock(true);
2243}
2244
2245#endif // GTEST_HAS_STREAM_REDIRECTION
2246
2247// A helper class that generates a failure when printed. We use it to
2248// ensure that Google Mock doesn't print a value (even to an internal
2249// buffer) when it is not supposed to do so.
2250class PrintMeNot {};
2251
2252void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2253 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2254 << "printed even to an internal buffer.";
2255}
2256
2257class LogTestHelper {
2258 public:
2259 LogTestHelper() {}
2260
2261 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2262
2263 private:
2264 GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
2265};
2266
2267class GMockLogTest : public VerboseFlagPreservingFixture {
2268 protected:
2269 LogTestHelper helper_;
2270};
2271
2272TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2273 GMOCK_FLAG(verbose) = kWarningVerbosity;
2274 EXPECT_CALL(helper_, Foo(_))
2275 .WillOnce(Return(PrintMeNot()));
2276 helper_.Foo(PrintMeNot()); // This is an expected call.
2277}
2278
2279TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2280 GMOCK_FLAG(verbose) = kErrorVerbosity;
2281 EXPECT_CALL(helper_, Foo(_))
2282 .WillOnce(Return(PrintMeNot()));
2283 helper_.Foo(PrintMeNot()); // This is an expected call.
2284}
2285
2286TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2287 GMOCK_FLAG(verbose) = kErrorVerbosity;
2288 ON_CALL(helper_, Foo(_))
2289 .WillByDefault(Return(PrintMeNot()));
2290 helper_.Foo(PrintMeNot()); // This should generate a warning.
2291}
2292
2293// Tests Mock::AllowLeak().
2294
2295TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2296 MockA* a = new MockA;
2297 Mock::AllowLeak(a);
2298}
2299
2300TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2301 MockA* a = new MockA;
2302 Mock::AllowLeak(a);
2303 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2304 a->DoA(0);
2305}
2306
2307TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2308 MockA* a = new MockA;
2309 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2310 Mock::AllowLeak(a);
2311}
2312
2313TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2314 MockA* a = new MockA;
2315 Mock::AllowLeak(a);
2316 EXPECT_CALL(*a, DoA(_));
2317 a->DoA(0);
2318}
2319
2320TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2321 MockA* a = new MockA;
2322 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2323 Mock::AllowLeak(a);
2324}
2325
2326TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2327 MockA* a = new MockA;
2328 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2329 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2330 Mock::AllowLeak(a);
2331}
2332
2333// Tests that we can verify and clear a mock object's expectations
2334// when none of its methods has expectations.
2335TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2336 MockB b;
2337 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2338
2339 // There should be no expectations on the methods now, so we can
2340 // freely call them.
2341 EXPECT_EQ(0, b.DoB());
2342 EXPECT_EQ(0, b.DoB(1));
2343}
2344
2345// Tests that we can verify and clear a mock object's expectations
2346// when some, but not all, of its methods have expectations *and* the
2347// verification succeeds.
2348TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2349 MockB b;
2350 EXPECT_CALL(b, DoB())
2351 .WillOnce(Return(1));
2352 b.DoB();
2353 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2354
2355 // There should be no expectations on the methods now, so we can
2356 // freely call them.
2357 EXPECT_EQ(0, b.DoB());
2358 EXPECT_EQ(0, b.DoB(1));
2359}
2360
2361// Tests that we can verify and clear a mock object's expectations
2362// when some, but not all, of its methods have expectations *and* the
2363// verification fails.
2364TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2365 MockB b;
2366 EXPECT_CALL(b, DoB())
2367 .WillOnce(Return(1));
2368 bool result = true;
2369 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2370 "Actual: never called");
2371 ASSERT_FALSE(result);
2372
2373 // There should be no expectations on the methods now, so we can
2374 // freely call them.
2375 EXPECT_EQ(0, b.DoB());
2376 EXPECT_EQ(0, b.DoB(1));
2377}
2378
2379// Tests that we can verify and clear a mock object's expectations
2380// when all of its methods have expectations.
2381TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2382 MockB b;
2383 EXPECT_CALL(b, DoB())
2384 .WillOnce(Return(1));
2385 EXPECT_CALL(b, DoB(_))
2386 .WillOnce(Return(2));
2387 b.DoB();
2388 b.DoB(1);
2389 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2390
2391 // There should be no expectations on the methods now, so we can
2392 // freely call them.
2393 EXPECT_EQ(0, b.DoB());
2394 EXPECT_EQ(0, b.DoB(1));
2395}
2396
2397// Tests that we can verify and clear a mock object's expectations
2398// when a method has more than one expectation.
2399TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2400 MockB b;
2401 EXPECT_CALL(b, DoB(0))
2402 .WillOnce(Return(1));
2403 EXPECT_CALL(b, DoB(_))
2404 .WillOnce(Return(2));
2405 b.DoB(1);
2406 bool result = true;
2407 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2408 "Actual: never called");
2409 ASSERT_FALSE(result);
2410
2411 // There should be no expectations on the methods now, so we can
2412 // freely call them.
2413 EXPECT_EQ(0, b.DoB());
2414 EXPECT_EQ(0, b.DoB(1));
2415}
2416
2417// Tests that we can call VerifyAndClearExpectations() on the same
2418// mock object multiple times.
2419TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2420 MockB b;
2421 EXPECT_CALL(b, DoB());
2422 b.DoB();
2423 Mock::VerifyAndClearExpectations(&b);
2424
2425 EXPECT_CALL(b, DoB(_))
2426 .WillOnce(Return(1));
2427 b.DoB(1);
2428 Mock::VerifyAndClearExpectations(&b);
2429 Mock::VerifyAndClearExpectations(&b);
2430
2431 // There should be no expectations on the methods now, so we can
2432 // freely call them.
2433 EXPECT_EQ(0, b.DoB());
2434 EXPECT_EQ(0, b.DoB(1));
2435}
2436
2437// Tests that we can clear a mock object's default actions when none
2438// of its methods has default actions.
2439TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2440 MockB b;
2441 // If this crashes or generates a failure, the test will catch it.
2442 Mock::VerifyAndClear(&b);
2443 EXPECT_EQ(0, b.DoB());
2444}
2445
2446// Tests that we can clear a mock object's default actions when some,
2447// but not all of its methods have default actions.
2448TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2449 MockB b;
2450 ON_CALL(b, DoB())
2451 .WillByDefault(Return(1));
2452
2453 Mock::VerifyAndClear(&b);
2454
2455 // Verifies that the default action of int DoB() was removed.
2456 EXPECT_EQ(0, b.DoB());
2457}
2458
2459// Tests that we can clear a mock object's default actions when all of
2460// its methods have default actions.
2461TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2462 MockB b;
2463 ON_CALL(b, DoB())
2464 .WillByDefault(Return(1));
2465 ON_CALL(b, DoB(_))
2466 .WillByDefault(Return(2));
2467
2468 Mock::VerifyAndClear(&b);
2469
2470 // Verifies that the default action of int DoB() was removed.
2471 EXPECT_EQ(0, b.DoB());
2472
2473 // Verifies that the default action of int DoB(int) was removed.
2474 EXPECT_EQ(0, b.DoB(0));
2475}
2476
2477// Tests that we can clear a mock object's default actions when a
2478// method has more than one ON_CALL() set on it.
2479TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2480 MockB b;
2481 ON_CALL(b, DoB(0))
2482 .WillByDefault(Return(1));
2483 ON_CALL(b, DoB(_))
2484 .WillByDefault(Return(2));
2485
2486 Mock::VerifyAndClear(&b);
2487
2488 // Verifies that the default actions (there are two) of int DoB(int)
2489 // were removed.
2490 EXPECT_EQ(0, b.DoB(0));
2491 EXPECT_EQ(0, b.DoB(1));
2492}
2493
2494// Tests that we can call VerifyAndClear() on a mock object multiple
2495// times.
2496TEST(VerifyAndClearTest, CanCallManyTimes) {
2497 MockB b;
2498 ON_CALL(b, DoB())
2499 .WillByDefault(Return(1));
2500 Mock::VerifyAndClear(&b);
2501 Mock::VerifyAndClear(&b);
2502
2503 ON_CALL(b, DoB(_))
2504 .WillByDefault(Return(1));
2505 Mock::VerifyAndClear(&b);
2506
2507 EXPECT_EQ(0, b.DoB());
2508 EXPECT_EQ(0, b.DoB(1));
2509}
2510
2511// Tests that VerifyAndClear() works when the verification succeeds.
2512TEST(VerifyAndClearTest, Success) {
2513 MockB b;
2514 ON_CALL(b, DoB())
2515 .WillByDefault(Return(1));
2516 EXPECT_CALL(b, DoB(1))
2517 .WillOnce(Return(2));
2518
2519 b.DoB();
2520 b.DoB(1);
2521 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2522
2523 // There should be no expectations on the methods now, so we can
2524 // freely call them.
2525 EXPECT_EQ(0, b.DoB());
2526 EXPECT_EQ(0, b.DoB(1));
2527}
2528
2529// Tests that VerifyAndClear() works when the verification fails.
2530TEST(VerifyAndClearTest, Failure) {
2531 MockB b;
2532 ON_CALL(b, DoB(_))
2533 .WillByDefault(Return(1));
2534 EXPECT_CALL(b, DoB())
2535 .WillOnce(Return(2));
2536
2537 b.DoB(1);
2538 bool result = true;
2539 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2540 "Actual: never called");
2541 ASSERT_FALSE(result);
2542
2543 // There should be no expectations on the methods now, so we can
2544 // freely call them.
2545 EXPECT_EQ(0, b.DoB());
2546 EXPECT_EQ(0, b.DoB(1));
2547}
2548
2549// Tests that VerifyAndClear() works when the default actions and
2550// expectations are set on a const mock object.
2551TEST(VerifyAndClearTest, Const) {
2552 MockB b;
2553 ON_CALL(Const(b), DoB())
2554 .WillByDefault(Return(1));
2555
2556 EXPECT_CALL(Const(b), DoB())
2557 .WillOnce(DoDefault())
2558 .WillOnce(Return(2));
2559
2560 b.DoB();
2561 b.DoB();
2562 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2563
2564 // There should be no expectations on the methods now, so we can
2565 // freely call them.
2566 EXPECT_EQ(0, b.DoB());
2567 EXPECT_EQ(0, b.DoB(1));
2568}
2569
2570// Tests that we can set default actions and expectations on a mock
2571// object after VerifyAndClear() has been called on it.
2572TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2573 MockB b;
2574 ON_CALL(b, DoB())
2575 .WillByDefault(Return(1));
2576 EXPECT_CALL(b, DoB(_))
2577 .WillOnce(Return(2));
2578 b.DoB(1);
2579
2580 Mock::VerifyAndClear(&b);
2581
2582 EXPECT_CALL(b, DoB())
2583 .WillOnce(Return(3));
2584 ON_CALL(b, DoB(_))
2585 .WillByDefault(Return(4));
2586
2587 EXPECT_EQ(3, b.DoB());
2588 EXPECT_EQ(4, b.DoB(1));
2589}
2590
2591// Tests that calling VerifyAndClear() on one mock object does not
2592// affect other mock objects (either of the same type or not).
2593TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2594 MockA a;
2595 MockB b1;
2596 MockB b2;
2597
2598 ON_CALL(a, Binary(_, _))
2599 .WillByDefault(Return(true));
2600 EXPECT_CALL(a, Binary(_, _))
2601 .WillOnce(DoDefault())
2602 .WillOnce(Return(false));
2603
2604 ON_CALL(b1, DoB())
2605 .WillByDefault(Return(1));
2606 EXPECT_CALL(b1, DoB(_))
2607 .WillOnce(Return(2));
2608
2609 ON_CALL(b2, DoB())
2610 .WillByDefault(Return(3));
2611 EXPECT_CALL(b2, DoB(_));
2612
2613 b2.DoB(0);
2614 Mock::VerifyAndClear(&b2);
2615
2616 // Verifies that the default actions and expectations of a and b1
2617 // are still in effect.
2618 EXPECT_TRUE(a.Binary(0, 0));
2619 EXPECT_FALSE(a.Binary(0, 0));
2620
2621 EXPECT_EQ(1, b1.DoB());
2622 EXPECT_EQ(2, b1.DoB(0));
2623}
2624
2625TEST(VerifyAndClearTest,
2626 DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2627 std::shared_ptr<MockA> a(new MockA);
2628 ReferenceHoldingMock test_mock;
2629
2630 // EXPECT_CALL stores a reference to a inside test_mock.
2631 EXPECT_CALL(test_mock, AcceptReference(_))
2632 .WillRepeatedly(SetArgPointee<0>(a));
2633
2634 // Throw away the reference to the mock that we have in a. After this, the
2635 // only reference to it is stored by test_mock.
2636 a.reset();
2637
2638 // When test_mock goes out of scope, it destroys the last remaining reference
2639 // to the mock object originally pointed to by a. This will cause the MockA
2640 // destructor to be called from inside the ReferenceHoldingMock destructor.
2641 // The state of all mocks is protected by a single global lock, but there
2642 // should be no deadlock.
2643}
2644
2645TEST(VerifyAndClearTest,
2646 DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2647 std::shared_ptr<MockA> a(new MockA);
2648 ReferenceHoldingMock test_mock;
2649
2650 // ON_CALL stores a reference to a inside test_mock.
2651 ON_CALL(test_mock, AcceptReference(_))
2652 .WillByDefault(SetArgPointee<0>(a));
2653
2654 // Throw away the reference to the mock that we have in a. After this, the
2655 // only reference to it is stored by test_mock.
2656 a.reset();
2657
2658 // When test_mock goes out of scope, it destroys the last remaining reference
2659 // to the mock object originally pointed to by a. This will cause the MockA
2660 // destructor to be called from inside the ReferenceHoldingMock destructor.
2661 // The state of all mocks is protected by a single global lock, but there
2662 // should be no deadlock.
2663}
2664
2665// Tests that a mock function's action can call a mock function
2666// (either the same function or a different one) either as an explicit
2667// action or as a default action without causing a dead lock. It
2668// verifies that the action is not performed inside the critical
2669// section.
2670TEST(SynchronizationTest, CanCallMockMethodInAction) {
2671 MockA a;
2672 MockC c;
2673 ON_CALL(a, DoA(_))
2674 .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
2675 &MockC::NonVoidMethod)));
2676 EXPECT_CALL(a, DoA(1));
2677 EXPECT_CALL(a, DoA(1))
2678 .WillOnce(Invoke(&a, &MockA::DoA))
2679 .RetiresOnSaturation();
2680 EXPECT_CALL(c, NonVoidMethod());
2681
2682 a.DoA(1);
2683 // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2684 // which will in turn match the first EXPECT_CALL() and trigger a call to
2685 // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2686 // EXPECT_CALL() did not specify an action.
2687}
2688
2689TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
2690 MockA a;
2691 int do_a_arg0 = 0;
2692 ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
2693 int do_a_47_arg0 = 0;
2694 ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
2695
2696 a.DoA(17);
2697 EXPECT_THAT(do_a_arg0, 17);
2698 EXPECT_THAT(do_a_47_arg0, 0);
2699 a.DoA(47);
2700 EXPECT_THAT(do_a_arg0, 17);
2701 EXPECT_THAT(do_a_47_arg0, 47);
2702
2703 ON_CALL(a, Binary).WillByDefault(Return(true));
2704 ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
2705 EXPECT_THAT(a.Binary(14, 17), true);
2706 EXPECT_THAT(a.Binary(17, 14), false);
2707}
2708
2709TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
2710 MockB b;
2711 ON_CALL(b, DoB()).WillByDefault(Return(9));
2712 ON_CALL(b, DoB(5)).WillByDefault(Return(11));
2713
2714 EXPECT_THAT(b.DoB(), 9);
2715 EXPECT_THAT(b.DoB(1), 0); // default value
2716 EXPECT_THAT(b.DoB(5), 11);
2717}
2718
2719struct MockWithConstMethods {
2720 public:
2721 MOCK_CONST_METHOD1(Foo, int(int));
2722 MOCK_CONST_METHOD2(Bar, int(int, const char*));
2723};
2724
2725TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
2726 MockWithConstMethods mock;
2727 ON_CALL(mock, Foo).WillByDefault(Return(7));
2728 ON_CALL(mock, Bar).WillByDefault(Return(33));
2729
2730 EXPECT_THAT(mock.Foo(17), 7);
2731 EXPECT_THAT(mock.Bar(27, "purple"), 33);
2732}
2733
2734class MockConstOverload {
2735 public:
2736 MOCK_METHOD1(Overloaded, int(int));
2737 MOCK_CONST_METHOD1(Overloaded, int(int));
2738};
2739
2740TEST(ParameterlessExpectationsTest,
2741 CanSetExpectationsForConstOverloadedMethods) {
2742 MockConstOverload mock;
2743 ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
2744 ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
2745 ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
2746 ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
2747
2748 EXPECT_THAT(mock.Overloaded(1), 7);
2749 EXPECT_THAT(mock.Overloaded(5), 9);
2750 EXPECT_THAT(mock.Overloaded(7), 7);
2751
2752 const MockConstOverload& const_mock = mock;
2753 EXPECT_THAT(const_mock.Overloaded(1), 0);
2754 EXPECT_THAT(const_mock.Overloaded(5), 11);
2755 EXPECT_THAT(const_mock.Overloaded(7), 13);
2756}
2757
2758} // namespace
2759
2760// Allows the user to define their own main and then invoke gmock_main
2761// from it. This might be necessary on some platforms which require
2762// specific setup and teardown.
2763#if GMOCK_RENAME_MAIN
2764int gmock_main(int argc, char **argv) {
2765#else
2766int main(int argc, char **argv) {
2767#endif // GMOCK_RENAME_MAIN
2768 testing::InitGoogleMock(&argc, argv);
2769 // Ensures that the tests pass no matter what value of
2770 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2771 testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2772 testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2773
2774 return RUN_ALL_TESTS();
2775}
2776