1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
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
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.
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.
31 // Google Mock - a framework for writing C++ mock classes.
33 // This file tests the spec builder syntax.
35 #include "gmock/gmock-spec-builders.h"
38 #include <ostream> // NOLINT
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"
51 // Helper class for testing the Expectation class template.
52 class ExpectationTester {
54 // Sets the call count of the given expectation to the given number.
55 void SetCallCount(int n, ExpectationBase* exp) {
60 } // namespace internal
61 } // namespace 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;
73 using testing::ContainsRegex;
75 using testing::DoDefault;
77 using testing::Expectation;
78 using testing::ExpectationSet;
79 using testing::GMOCK_FLAG(verbose);
81 using testing::IgnoreResult;
82 using testing::InSequence;
83 using testing::Invoke;
84 using testing::InvokeWithoutArgs;
85 using testing::IsNotSubstring;
86 using testing::IsSubstring;
88 using testing::Message;
90 using testing::NaggyMock;
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;
105 #if GTEST_HAS_STREAM_REDIRECTION
106 using testing::HasSubstr;
107 using testing::internal::CaptureStdout;
108 using testing::internal::GetCapturedStdout;
113 class MockIncomplete {
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));
120 // Tells Google Mock how to print a value of type Incomplete.
121 void PrintTo(const Incomplete& x, ::std::ostream* os);
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
128 MockIncomplete incomplete;
129 EXPECT_CALL(incomplete, ByRefFunc(_))
133 // The definition of the printer for the argument type doesn't have to
134 // be visible where the mock is used.
135 void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
141 // A type that's not default constructible.
142 class NonDefaultConstructible {
144 explicit NonDefaultConstructible(int /* dummy */) {}
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));
158 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
165 MOCK_CONST_METHOD0(DoB, int()); // NOLINT
166 MOCK_METHOD1(DoB, int(int n)); // NOLINT
169 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
172 class ReferenceHoldingMock {
174 ReferenceHoldingMock() {}
176 MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
179 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
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.
187 #define Method MethodW
192 virtual int Method() = 0;
194 class MockCC : public CC {
198 MOCK_METHOD0(Method, int());
201 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
204 // Tests that a method with expanded name compiles.
205 TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
207 ON_CALL(cc, Method());
210 // Tests that the method with expanded name not only compiles but runs
211 // and returns a correct value, too.
212 TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
214 ON_CALL(cc, Method()).WillByDefault(Return(42));
215 EXPECT_EQ(42, cc.Method());
218 // Tests that a method with expanded name compiles.
219 TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
221 EXPECT_CALL(cc, Method());
225 // Tests that it works, too.
226 TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
228 EXPECT_CALL(cc, Method()).WillOnce(Return(42));
229 EXPECT_EQ(42, cc.Method());
232 #undef Method // Done with macro redefinition tests.
234 // Tests that ON_CALL evaluates its arguments exactly once as promised
236 TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
240 ON_CALL(*pa++, DoA(_));
241 EXPECT_EQ(&a + 1, pa);
244 TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
248 ON_CALL(a, DoA(n++));
252 // Tests that the syntax of ON_CALL() is enforced at run time.
254 TEST(OnCallSyntaxTest, WithIsOptional) {
258 .WillByDefault(Return());
261 .WillByDefault(Return());
264 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
267 EXPECT_NONFATAL_FAILURE({ // NOLINT
268 ON_CALL(a, ReturnResult(_))
271 .WillByDefault(Return(Result()));
272 }, ".With() cannot appear more than once in an ON_CALL()");
275 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
278 EXPECT_DEATH_IF_SUPPORTED({
284 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
287 EXPECT_NONFATAL_FAILURE({ // NOLINT
289 .WillByDefault(Return())
290 .WillByDefault(Return());
291 }, ".WillByDefault() must appear exactly once in an ON_CALL()");
294 // Tests that EXPECT_CALL evaluates its arguments exactly once as
295 // promised by Google Mock.
296 TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
300 EXPECT_CALL(*pa++, DoA(_));
302 EXPECT_EQ(&a + 1, pa);
305 TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
309 EXPECT_CALL(a, DoA(n++));
314 // Tests that the syntax of EXPECT_CALL() is enforced at run time.
316 TEST(ExpectCallSyntaxTest, WithIsOptional) {
319 EXPECT_CALL(a, DoA(5))
321 EXPECT_CALL(a, DoA(6))
326 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
329 EXPECT_NONFATAL_FAILURE({ // NOLINT
330 EXPECT_CALL(a, DoA(6))
333 }, ".With() cannot appear more than once in an EXPECT_CALL()");
338 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
341 EXPECT_NONFATAL_FAILURE({ // NOLINT
342 EXPECT_CALL(a, DoA(1))
345 }, ".With() must be the first clause in an EXPECT_CALL()");
349 EXPECT_NONFATAL_FAILURE({ // NOLINT
350 EXPECT_CALL(a, DoA(2))
353 }, ".With() must be the first clause in an EXPECT_CALL()");
358 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
361 EXPECT_CALL(a, DoA(1))
364 EXPECT_CALL(a, DoA(2))
366 .WillRepeatedly(Return());
373 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
376 EXPECT_NONFATAL_FAILURE({ // NOLINT
377 EXPECT_CALL(a, DoA(1))
380 }, ".Times() cannot appear more than once in an EXPECT_CALL()");
386 TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
390 EXPECT_NONFATAL_FAILURE({ // NOLINT
391 EXPECT_CALL(a, DoA(1))
394 }, ".Times() cannot appear after ");
399 TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
403 EXPECT_CALL(a, DoA(1));
404 EXPECT_CALL(a, DoA(2))
411 TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
415 EXPECT_CALL(a, DoA(1))
422 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
426 Expectation e = EXPECT_CALL(a, DoA(1))
428 EXPECT_NONFATAL_FAILURE({ // NOLINT
429 EXPECT_CALL(a, DoA(2))
432 }, ".InSequence() cannot appear after ");
437 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
441 EXPECT_NONFATAL_FAILURE({ // NOLINT
442 EXPECT_CALL(a, DoA(1))
445 }, ".InSequence() cannot appear after ");
450 TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
453 Expectation e = EXPECT_CALL(a, DoA(1));
454 EXPECT_NONFATAL_FAILURE({
455 EXPECT_CALL(a, DoA(2))
458 }, ".After() cannot appear after ");
464 TEST(ExpectCallSyntaxTest, WillIsOptional) {
467 EXPECT_CALL(a, DoA(1));
468 EXPECT_CALL(a, DoA(2))
475 TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
478 EXPECT_CALL(a, DoA(1))
485 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
488 EXPECT_NONFATAL_FAILURE({ // NOLINT
489 EXPECT_CALL(a, DoA(1))
490 .WillRepeatedly(Return())
492 }, ".WillOnce() cannot appear after ");
497 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
500 EXPECT_CALL(a, DoA(1))
502 EXPECT_CALL(a, DoA(2))
504 .WillRepeatedly(Return());
511 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
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 "
522 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
525 EXPECT_NONFATAL_FAILURE({ // NOLINT
526 EXPECT_CALL(a, DoA(1))
527 .RetiresOnSaturation()
528 .WillRepeatedly(Return());
529 }, ".WillRepeatedly() cannot appear after ");
532 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
535 EXPECT_CALL(a, DoA(1));
536 EXPECT_CALL(a, DoA(1))
537 .RetiresOnSaturation();
543 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
546 EXPECT_NONFATAL_FAILURE({ // NOLINT
547 EXPECT_CALL(a, DoA(1))
548 .RetiresOnSaturation()
549 .RetiresOnSaturation();
550 }, ".RetiresOnSaturation() cannot appear more than once");
555 TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
558 EXPECT_CALL(a, DoA(1));
561 EXPECT_NONFATAL_FAILURE({ // NOLINT
563 EXPECT_CALL(a, DoA(1));
564 }, "to be called once");
565 EXPECT_NONFATAL_FAILURE({ // NOLINT
567 EXPECT_CALL(a, DoA(1));
570 }, "to be called once");
573 #if GTEST_HAS_STREAM_REDIRECTION
575 // Tests that Google Mock doesn't print a warning when the number of
576 // WillOnce() is adequate.
577 TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
582 // It's always fine to omit WillOnce() entirely.
583 EXPECT_CALL(b, DoB())
585 EXPECT_CALL(b, DoB(1))
587 EXPECT_CALL(b, DoB(2))
589 .WillRepeatedly(Return(1));
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))
595 .WillOnce(Return(2));
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))
602 .WillRepeatedly(Return(2));
604 // Satisfies the above expectations.
608 EXPECT_STREQ("", GetCapturedStdout().c_str());
611 // Tests that Google Mock warns on having too many actions in an
612 // expectation compared to its cardinality.
613 TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
618 // Warns when the number of WillOnce()s is larger than the upper bound.
619 EXPECT_CALL(b, DoB())
621 .WillOnce(Return(1)); // #1
622 EXPECT_CALL(b, DoB())
625 .WillOnce(Return(2)); // #2
626 EXPECT_CALL(b, DoB(1))
630 .RetiresOnSaturation(); // #3
632 // Warns when the number of WillOnce()s equals the upper bound and
633 // there is a WillRepeatedly().
634 EXPECT_CALL(b, DoB())
636 .WillRepeatedly(Return(1)); // #4
637 EXPECT_CALL(b, DoB(2))
640 .WillRepeatedly(Return(2)); // #5
642 // Satisfies the above expectations.
646 const std::string output = GetCapturedStdout();
649 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
650 "Expected to be never called, but has 1 WillOnce().",
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.",
660 "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
661 "Expected to be called once, but has 2 WillOnce()s.",
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().",
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().",
677 // Tests that Google Mock warns on having too few actions in an
678 // expectation compared to its cardinality.
679 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
682 EXPECT_CALL(b, DoB())
683 .Times(Between(2, 3))
684 .WillOnce(Return(1));
688 const std::string output = GetCapturedStdout();
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().",
698 TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
699 int original_behavior = testing::GMOCK_FLAG(default_mock_behavior);
701 testing::GMOCK_FLAG(default_mock_behavior) = kAllow;
707 std::string output = GetCapturedStdout();
708 EXPECT_TRUE(output.empty()) << output;
710 testing::GMOCK_FLAG(default_mock_behavior) = kWarn;
716 std::string warning_output = GetCapturedStdout();
717 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
718 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
721 testing::GMOCK_FLAG(default_mock_behavior) = kFail;
722 EXPECT_NONFATAL_FAILURE({
725 }, "Uninteresting mock function call");
727 // Out of bounds values are converted to kWarn
728 testing::GMOCK_FLAG(default_mock_behavior) = -1;
734 warning_output = GetCapturedStdout();
735 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
736 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
738 testing::GMOCK_FLAG(default_mock_behavior) = 3;
744 warning_output = GetCapturedStdout();
745 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
746 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
749 testing::GMOCK_FLAG(default_mock_behavior) = original_behavior;
752 #endif // GTEST_HAS_STREAM_REDIRECTION
754 // Tests the semantics of ON_CALL().
756 // Tests that the built-in default action is taken when no ON_CALL()
758 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
760 EXPECT_CALL(b, DoB());
762 EXPECT_EQ(0, b.DoB());
765 // Tests that the built-in default action is taken when no ON_CALL()
766 // matches the invocation.
767 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
770 .WillByDefault(Return(1));
771 EXPECT_CALL(b, DoB(_));
773 EXPECT_EQ(0, b.DoB(2));
776 // Tests that the last matching ON_CALL() action is taken.
777 TEST(OnCallTest, PicksLastMatchingOnCall) {
780 .WillByDefault(Return(3));
782 .WillByDefault(Return(2));
784 .WillByDefault(Return(1));
785 EXPECT_CALL(b, DoB(_));
787 EXPECT_EQ(2, b.DoB(2));
790 // Tests the semantics of EXPECT_CALL().
792 // Tests that any call is allowed when no EXPECT_CALL() is specified.
793 TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
795 EXPECT_CALL(b, DoB());
796 // There is no expectation on DoB(int).
800 // DoB(int) can be called any number of times.
805 // Tests that the last matching EXPECT_CALL() fires.
806 TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
808 EXPECT_CALL(b, DoB(_))
809 .WillRepeatedly(Return(2));
810 EXPECT_CALL(b, DoB(1))
811 .WillRepeatedly(Return(1));
813 EXPECT_EQ(1, b.DoB(1));
816 // Tests lower-bound violation.
817 TEST(ExpectCallTest, CatchesTooFewCalls) {
818 EXPECT_NONFATAL_FAILURE({ // NOLINT
820 EXPECT_CALL(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");
829 // Tests that the cardinality can be inferred when no Times(...) is
831 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
834 EXPECT_CALL(b, DoB())
836 .WillOnce(Return(2));
838 EXPECT_EQ(1, b.DoB());
839 EXPECT_EQ(2, b.DoB());
842 EXPECT_NONFATAL_FAILURE({ // NOLINT
844 EXPECT_CALL(b, DoB())
846 .WillOnce(Return(2));
848 EXPECT_EQ(1, b.DoB());
849 }, "to be called twice");
853 EXPECT_CALL(b, DoB())
855 .WillOnce(Return(2));
857 EXPECT_EQ(1, b.DoB());
858 EXPECT_EQ(2, b.DoB());
859 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
863 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
866 EXPECT_CALL(b, DoB())
868 .WillRepeatedly(Return(2));
870 EXPECT_EQ(1, b.DoB());
875 EXPECT_CALL(b, DoB())
877 .WillRepeatedly(Return(2));
879 EXPECT_EQ(1, b.DoB());
880 EXPECT_EQ(2, b.DoB());
881 EXPECT_EQ(2, b.DoB());
884 EXPECT_NONFATAL_FAILURE({ // NOLINT
886 EXPECT_CALL(b, DoB())
888 .WillRepeatedly(Return(2));
889 }, "to be called at least once");
892 // Tests that the n-th action is taken for the n-th matching
894 TEST(ExpectCallTest, NthMatchTakesNthAction) {
896 EXPECT_CALL(b, DoB())
899 .WillOnce(Return(3));
901 EXPECT_EQ(1, b.DoB());
902 EXPECT_EQ(2, b.DoB());
903 EXPECT_EQ(3, b.DoB());
906 // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
907 // list is exhausted.
908 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
910 EXPECT_CALL(b, DoB())
912 .WillRepeatedly(Return(2));
914 EXPECT_EQ(1, b.DoB());
915 EXPECT_EQ(2, b.DoB());
916 EXPECT_EQ(2, b.DoB());
919 #if GTEST_HAS_STREAM_REDIRECTION
921 // Tests that the default action is taken when the WillOnce(...) list is
922 // exhausted and there is no WillRepeatedly().
923 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
925 EXPECT_CALL(b, DoB(_))
927 EXPECT_CALL(b, DoB())
930 .WillOnce(Return(2));
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());
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."));
954 TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
956 std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
957 EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
959 EXPECT_EQ(1, b.DoB());
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);
968 TEST(FunctionMockerMessageTest,
969 ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
970 std::string on_call_location;
974 on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
975 ON_CALL(b, DoB(_)).WillByDefault(Return(0));
978 EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
981 #endif // GTEST_HAS_STREAM_REDIRECTION
983 // Tests that an uninteresting call performs the default action.
984 TEST(UninterestingCallTest, DoesDefaultAction) {
985 // When there is an ON_CALL() statement, the action specified by it
988 ON_CALL(a, Binary(_, _))
989 .WillByDefault(Return(true));
990 EXPECT_TRUE(a.Binary(1, 2));
992 // When there is no ON_CALL(), the default value for the return type
993 // should be returned.
995 EXPECT_EQ(0, b.DoB());
998 // Tests that an unexpected call performs the default action.
999 TEST(UnexpectedCallTest, DoesDefaultAction) {
1000 // When there is an ON_CALL() statement, the action specified by it
1003 ON_CALL(a, Binary(_, _))
1004 .WillByDefault(Return(true));
1005 EXPECT_CALL(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);
1012 // When there is no ON_CALL(), the default value for the return type
1013 // should be returned.
1015 EXPECT_CALL(b, DoB(0))
1018 EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
1019 "Unexpected mock function call");
1023 // Tests that when an unexpected void function generates the right
1025 TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
1026 // First, tests the message when there is only one EXPECT_CALL().
1028 EXPECT_CALL(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(
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(
1040 " Expected arg #0: is equal to 1\n"
1042 " Expected: to be called once\n"
1043 " Actual: called once - saturated and active");
1045 // Next, tests the message when there are more than one EXPECT_CALL().
1047 EXPECT_CALL(a2, DoA(1));
1048 EXPECT_CALL(a2, DoA(3));
1050 EXPECT_NONFATAL_FAILURE(
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(
1057 "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1058 " Expected arg #0: is equal to 1\n"
1060 " Expected: to be called once\n"
1061 " Actual: called once - saturated and active");
1062 EXPECT_NONFATAL_FAILURE(
1064 "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1065 " Expected arg #0: is equal to 3\n"
1067 " Expected: to be called once\n"
1068 " Actual: never called - unsatisfied and active");
1072 // Tests that an unexpected non-void function generates the right
1074 TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1076 EXPECT_CALL(b1, DoB(1));
1078 EXPECT_NONFATAL_FAILURE(
1080 "Unexpected mock function call - returning default value.\n"
1081 " Function call: DoB(2)\n"
1083 "Google Mock tried the following 1 expectation, but it didn't match:");
1084 EXPECT_NONFATAL_FAILURE(
1086 " Expected arg #0: is equal to 1\n"
1088 " Expected: to be called once\n"
1089 " Actual: called once - saturated and active");
1092 // Tests that Google Mock explains that an retired expectation doesn't
1094 TEST(UnexpectedCallTest, RetiredExpectation) {
1096 EXPECT_CALL(b, DoB(1))
1097 .RetiresOnSaturation();
1100 EXPECT_NONFATAL_FAILURE(
1102 " Expected: the expectation is active\n"
1103 " Actual: it is retired");
1106 // Tests that Google Mock explains that an expectation that doesn't
1107 // match the arguments doesn't match the call.
1108 TEST(UnexpectedCallTest, UnmatchedArguments) {
1110 EXPECT_CALL(b, DoB(1));
1112 EXPECT_NONFATAL_FAILURE(
1114 " Expected arg #0: is equal to 1\n"
1119 // Tests that Google Mock explains that an expectation with
1120 // unsatisfied pre-requisites doesn't match the call.
1121 TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1124 EXPECT_CALL(b, DoB(1))
1126 EXPECT_CALL(b, DoB(2))
1129 EXPECT_CALL(b, DoB(3))
1131 EXPECT_CALL(b, DoB(4))
1132 .InSequence(s1, s2);
1134 ::testing::TestPartResultArray failures;
1136 ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1138 // Now 'failures' contains the Google Test failures generated by
1139 // the above statement.
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());
1147 // Verifies that the failure message contains the two unsatisfied
1148 // pre-requisites but not the satisfied one.
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
1160 "the following immediate pre-requisites are not satisfied:\n"
1161 "(.|\n)*: pre-requisite #0\n"
1162 "(.|\n)*: pre-requisite #1"));
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
1176 TEST(UndefinedReturnValueTest,
1177 ReturnValueIsMandatoryWhenNotDefaultConstructible) {
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());
1185 EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1189 // Tests that an excessive call (one whose arguments match the
1190 // matchers but is called too many times) performs the default action.
1191 TEST(ExcessiveCallTest, DoesDefaultAction) {
1192 // When there is an ON_CALL() statement, the action specified by it
1195 ON_CALL(a, Binary(_, _))
1196 .WillByDefault(Return(true));
1197 EXPECT_CALL(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);
1204 // When there is no ON_CALL(), the default value for the return type
1205 // should be returned.
1207 EXPECT_CALL(b, DoB(0))
1210 EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1211 "Mock function called more times than expected");
1215 // Tests that when a void function is called too many times,
1216 // the failure message contains the argument values.
1217 TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1219 EXPECT_CALL(a, DoA(_))
1221 EXPECT_NONFATAL_FAILURE(
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");
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.
1231 TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1233 EXPECT_CALL(b, DoB(_));
1235 EXPECT_NONFATAL_FAILURE(
1237 "Mock function called more times than expected - "
1238 "returning default value.\n"
1239 " Function call: DoB(2)\n"
1241 " Expected: to be called once\n"
1242 " Actual: called twice - over-saturated and active");
1245 // Tests using sequences.
1247 TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1252 EXPECT_CALL(a, DoA(1));
1253 EXPECT_CALL(a, DoA(2));
1256 EXPECT_NONFATAL_FAILURE({ // NOLINT
1258 }, "Unexpected mock function call");
1264 TEST(InSequenceTest, NestedInSequence) {
1269 EXPECT_CALL(a, DoA(1));
1273 EXPECT_CALL(a, DoA(2));
1274 EXPECT_CALL(a, DoA(3));
1278 EXPECT_NONFATAL_FAILURE({ // NOLINT
1281 }, "Unexpected mock function call");
1287 TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1292 EXPECT_CALL(a, DoA(1));
1293 EXPECT_CALL(a, DoA(2));
1295 EXPECT_CALL(a, DoA(3));
1297 EXPECT_NONFATAL_FAILURE({ // NOLINT
1299 }, "Unexpected mock function call");
1306 // Tests that any order is allowed when no sequence is used.
1307 TEST(SequenceTest, AnyOrderIsOkByDefault) {
1312 EXPECT_CALL(a, DoA(1));
1313 EXPECT_CALL(b, DoB())
1314 .Times(AnyNumber());
1324 EXPECT_CALL(a, DoA(1));
1325 EXPECT_CALL(b, DoB())
1326 .Times(AnyNumber());
1333 // Tests that the calls must be in strict order when a complete order
1335 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1337 ON_CALL(a, ReturnResult(_))
1338 .WillByDefault(Return(Result()));
1341 EXPECT_CALL(a, ReturnResult(1))
1343 EXPECT_CALL(a, ReturnResult(2))
1345 EXPECT_CALL(a, ReturnResult(3))
1350 // May only be called after a.ReturnResult(2).
1351 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1357 // Tests that the calls must be in strict order when a complete order
1359 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1361 ON_CALL(a, ReturnResult(_))
1362 .WillByDefault(Return(Result()));
1365 EXPECT_CALL(a, ReturnResult(1))
1367 EXPECT_CALL(a, ReturnResult(2))
1370 // May only be called after a.ReturnResult(1).
1371 EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1377 // Tests specifying a DAG using multiple sequences.
1378 class PartialOrderTest : public testing::Test {
1380 PartialOrderTest() {
1381 ON_CALL(a_, ReturnResult(_))
1382 .WillByDefault(Return(Result()));
1384 // Specifies this partial ordering:
1386 // a.ReturnResult(1) ==>
1387 // a.ReturnResult(2) * n ==> a.ReturnResult(3)
1390 EXPECT_CALL(a_, ReturnResult(1))
1392 EXPECT_CALL(b_, DoB())
1395 EXPECT_CALL(a_, ReturnResult(2))
1398 EXPECT_CALL(a_, ReturnResult(3))
1406 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
1410 // May only be called after the second DoB().
1411 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1417 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
1418 // May only be called after ReturnResult(1).
1419 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1427 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
1428 // May only be called last.
1429 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
1437 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
1443 // May only be called before ReturnResult(3).
1444 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1447 TEST(SequenceTest, Retirement) {
1451 EXPECT_CALL(a, DoA(1))
1453 EXPECT_CALL(a, DoA(_))
1455 .RetiresOnSaturation();
1456 EXPECT_CALL(a, DoA(1))
1464 // Tests Expectation.
1466 TEST(ExpectationTest, ConstrutorsWork) {
1468 Expectation e1; // Default ctor.
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(_);
1475 Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1476 Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
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();
1483 Expectation e10 = e2; // Copy ctor.
1485 EXPECT_THAT(e1, Ne(e2));
1486 EXPECT_THAT(e2, Eq(e10));
1498 TEST(ExpectationTest, AssignmentWorks) {
1501 Expectation e2 = EXPECT_CALL(a, DoA(1));
1503 EXPECT_THAT(e1, Ne(e2));
1506 EXPECT_THAT(e1, Eq(e2));
1511 // Tests ExpectationSet.
1513 TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1514 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1517 TEST(ExpectationSetTest, ConstructorsWork) {
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.
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());
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));
1546 TEST(ExpectationSetTest, AssignmentWorks) {
1548 ExpectationSet es2 = Expectation();
1551 EXPECT_EQ(1, es1.size());
1552 EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1553 EXPECT_THAT(es1, Eq(es2));
1556 TEST(ExpectationSetTest, InsertionWorks) {
1560 EXPECT_EQ(1, es1.size());
1561 EXPECT_THAT(*(es1.begin()), Eq(e1));
1564 Expectation e2 = EXPECT_CALL(a, DoA(1));
1566 EXPECT_EQ(2, es1.size());
1568 ExpectationSet::const_iterator it1 = es1.begin();
1569 ExpectationSet::const_iterator it2 = it1;
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.
1576 TEST(ExpectationSetTest, SizeWorks) {
1578 EXPECT_EQ(0, es.size());
1580 es += Expectation();
1581 EXPECT_EQ(1, es.size());
1584 es += EXPECT_CALL(a, DoA(1));
1585 EXPECT_EQ(2, es.size());
1590 TEST(ExpectationSetTest, IsEnumerable) {
1592 EXPECT_TRUE(es.begin() == es.end());
1594 es += Expectation();
1595 ExpectationSet::const_iterator it = es.begin();
1596 EXPECT_TRUE(it != es.end());
1597 EXPECT_THAT(*it, Eq(Expectation()));
1599 EXPECT_TRUE(it== es.end());
1602 // Tests the .After() clause.
1604 TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1607 es += EXPECT_CALL(a, DoA(1));
1608 es += EXPECT_CALL(a, DoA(2));
1609 EXPECT_CALL(a, DoA(3))
1617 TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
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())
1626 EXPECT_CALL(a, DoA(2)).After(e2);
1634 // Calls must be in strict order when specified so using .After().
1635 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1640 // a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1641 Expectation e1 = EXPECT_CALL(a, DoA(1));
1642 Expectation e2 = EXPECT_CALL(b, DoB())
1644 EXPECT_CALL(a, DoA(2))
1649 // May only be called after DoB().
1650 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1656 // Calls must be in strict order when specified so using .After().
1657 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
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())
1667 EXPECT_CALL(a, DoA(2))
1673 // May only be called after the second DoB().
1674 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1680 // Calls must satisfy the partial order when specified so.
1681 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1683 ON_CALL(a, ReturnResult(_))
1684 .WillByDefault(Return(Result()));
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))
1694 // May only be called last.
1695 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1702 // Calls must satisfy the partial order when specified so.
1703 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
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))
1716 // May only be called last.
1717 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1723 // .After() can be combined with .InSequence().
1724 TEST(AfterTest, CanBeUsedWithInSequence) {
1727 Expectation e = EXPECT_CALL(a, DoA(1));
1728 EXPECT_CALL(a, DoA(2)).InSequence(s);
1729 EXPECT_CALL(a, DoA(3))
1735 // May only be after DoA(2).
1736 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1742 // .After() can be called multiple times.
1743 TEST(AfterTest, CanBeCalledManyTimes) {
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))
1759 // .After() accepts up to 5 arguments.
1760 TEST(AfterTest, AcceptsUpToFiveArguments) {
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);
1778 // .After() allows input to contain duplicated Expectations.
1779 TEST(AfterTest, AcceptsDuplicatedInput) {
1781 ON_CALL(a, ReturnResult(_))
1782 .WillByDefault(Return(Result()));
1786 // DoA(2) ==> ReturnResult(3)
1787 Expectation e1 = EXPECT_CALL(a, DoA(1));
1788 Expectation e2 = EXPECT_CALL(a, DoA(2));
1792 EXPECT_CALL(a, ReturnResult(3))
1793 .After(e1, e2, es, e1);
1797 // May only be after DoA(2).
1798 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1804 // An Expectation added to an ExpectationSet after it has been used in
1805 // an .After() has no effect.
1806 TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1808 ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1809 Expectation e2 = EXPECT_CALL(a, DoA(2));
1810 EXPECT_CALL(a, DoA(3))
1819 // Tests that Google Mock correctly handles calls to mock functions
1820 // after a mock object owning one of their pre-requisites has died.
1822 // Tests that calls that satisfy the original spec are successful.
1823 TEST(DeletingMockEarlyTest, Success1) {
1824 MockB* const b1 = new MockB;
1825 MockA* const a = new MockA;
1826 MockB* const b2 = new MockB;
1830 EXPECT_CALL(*b1, DoB(_))
1831 .WillOnce(Return(1));
1832 EXPECT_CALL(*a, Binary(_, _))
1834 .WillRepeatedly(Return(true));
1835 EXPECT_CALL(*b2, DoB(_))
1837 .WillRepeatedly(Return(2));
1840 EXPECT_EQ(1, b1->DoB(1));
1842 // a's pre-requisite has died.
1843 EXPECT_TRUE(a->Binary(0, 1));
1845 // a's successor has died.
1846 EXPECT_TRUE(a->Binary(1, 2));
1850 // Tests that calls that satisfy the original spec are successful.
1851 TEST(DeletingMockEarlyTest, Success2) {
1852 MockB* const b1 = new MockB;
1853 MockA* const a = new MockA;
1854 MockB* const b2 = new MockB;
1858 EXPECT_CALL(*b1, DoB(_))
1859 .WillOnce(Return(1));
1860 EXPECT_CALL(*a, Binary(_, _))
1861 .Times(AnyNumber());
1862 EXPECT_CALL(*b2, DoB(_))
1864 .WillRepeatedly(Return(2));
1867 delete a; // a is trivially satisfied.
1868 EXPECT_EQ(1, b1->DoB(1));
1869 EXPECT_EQ(2, b2->DoB(2));
1874 // Tests that it's OK to delete a mock object itself in its action.
1876 // Suppresses warning on unreferenced formal parameter in MSVC with
1879 # pragma warning(push)
1880 # pragma warning(disable:4100)
1883 ACTION_P(Delete, ptr) { delete ptr; }
1886 # pragma warning(pop)
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.
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.
1902 // Tests that calls that violate the original spec yield failures.
1903 TEST(DeletingMockEarlyTest, Failure1) {
1904 MockB* const b1 = new MockB;
1905 MockA* const a = new MockA;
1906 MockB* const b2 = new MockB;
1910 EXPECT_CALL(*b1, DoB(_))
1911 .WillOnce(Return(1));
1912 EXPECT_CALL(*a, Binary(_, _))
1913 .Times(AnyNumber());
1914 EXPECT_CALL(*b2, DoB(_))
1916 .WillRepeatedly(Return(2));
1919 delete a; // a is trivially satisfied.
1920 EXPECT_NONFATAL_FAILURE({
1922 }, "Unexpected mock function call");
1923 EXPECT_EQ(1, b1->DoB(1));
1928 // Tests that calls that violate the original spec yield failures.
1929 TEST(DeletingMockEarlyTest, Failure2) {
1930 MockB* const b1 = new MockB;
1931 MockA* const a = new MockA;
1932 MockB* const b2 = new MockB;
1936 EXPECT_CALL(*b1, DoB(_));
1937 EXPECT_CALL(*a, Binary(_, _))
1938 .Times(AnyNumber());
1939 EXPECT_CALL(*b2, DoB(_))
1940 .Times(AnyNumber());
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");
1953 class EvenNumberCardinality : public CardinalityInterface {
1955 // Returns true if and only if call_count calls will satisfy this
1957 bool IsSatisfiedByCallCount(int call_count) const override {
1958 return call_count % 2 == 0;
1961 // Returns true if and only if call_count calls will saturate this
1963 bool IsSaturatedByCallCount(int /* call_count */) const override {
1967 // Describes self to an ostream.
1968 void DescribeTo(::std::ostream* os) const override {
1969 *os << "called even number of times";
1973 Cardinality EvenNumber() {
1974 return Cardinality(new EvenNumberCardinality);
1977 TEST(ExpectationBaseTest,
1978 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1979 MockA* a = new MockA;
1982 EXPECT_CALL(*a, DoA(1))
1983 .Times(EvenNumber())
1985 EXPECT_CALL(*a, DoA(2))
1988 EXPECT_CALL(*a, DoA(3))
1989 .Times(AnyNumber());
1993 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1994 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1997 // The following tests verify the message generated when a mock
1998 // function is called.
2003 inline void operator<<(::std::ostream& os, const Printable&) {
2007 struct Unprintable {
2008 Unprintable() : value(0) {}
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
2021 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
2024 class VerboseFlagPreservingFixture : public testing::Test {
2026 VerboseFlagPreservingFixture()
2027 : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
2029 ~VerboseFlagPreservingFixture() override {
2030 GMOCK_FLAG(verbose) = saved_verbose_flag_;
2034 const std::string saved_verbose_flag_;
2036 GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
2039 #if GTEST_HAS_STREAM_REDIRECTION
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.
2044 TEST(FunctionCallMessageTest,
2045 UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
2046 GMOCK_FLAG(verbose) = kWarningVerbosity;
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);
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.
2058 TEST(FunctionCallMessageTest,
2059 UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
2060 GMOCK_FLAG(verbose) = kInfoVerbosity;
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);
2070 // We check the stack trace content in dbg-mode only, as opt-mode
2071 // may inline the call we are interested in seeing.
2073 // Verifies that a void mock function's name appears in the stack
2075 EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
2077 // Verifies that a non-void mock function's name appears in the
2081 const std::string output2 = GetCapturedStdout();
2082 EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
2087 // Tests that an uninteresting mock function call on a naggy mock
2088 // causes the function arguments and return value to be printed.
2089 TEST(FunctionCallMessageTest,
2090 UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
2091 // A non-void mock function.
2095 const std::string output1 = GetCapturedStdout();
2096 EXPECT_PRED_FORMAT2(
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.
2103 // A void mock function.
2106 c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
2107 const std::string output2 = GetCapturedStdout();
2108 EXPECT_THAT(output2.c_str(),
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.
2117 // Tests how the --gmock_verbose flag affects Google Mock's output.
2119 class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
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) {
2129 EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
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));
2135 // Suppresses 'unused function parameter' warnings.
2136 static_cast<void>(function_name);
2139 EXPECT_STREQ("", output.c_str());
2143 // Tests how the flag affects expected calls.
2144 void TestExpectedCall(bool should_print) {
2146 EXPECT_CALL(a, DoA(5));
2147 EXPECT_CALL(a, Binary(_, 1))
2148 .WillOnce(Return(true));
2150 // A void-returning function.
2154 GetCapturedStdout(),
2156 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2157 " Function call: DoA(5)\n"
2161 // A non-void-returning function.
2165 GetCapturedStdout(),
2167 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2168 " Function call: Binary(2, 1)\n"
2174 // Tests how the flag affects uninteresting calls on a naggy mock.
2175 void TestUninterestingCallOnNaggyMock(bool should_print) {
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. "
2182 "https://github.com/google/googletest/blob/master/docs/"
2183 "gmock_cook_book.md#"
2184 "knowing-when-to-expect for details.";
2186 // A void-returning function.
2190 GetCapturedStdout(),
2192 "\nGMOCK WARNING:\n"
2193 "Uninteresting mock function call - returning directly.\n"
2194 " Function call: DoA(5)\n" +
2198 // A non-void-returning function.
2202 GetCapturedStdout(),
2204 "\nGMOCK WARNING:\n"
2205 "Uninteresting mock function call - returning default value.\n"
2206 " Function call: Binary(2, 1)\n"
2207 " Returns: false\n" +
2213 // Tests that --gmock_verbose=info causes both expected and
2214 // uninteresting calls to be reported.
2215 TEST_F(GMockVerboseFlagTest, Info) {
2216 GMOCK_FLAG(verbose) = kInfoVerbosity;
2217 TestExpectedCall(true);
2218 TestUninterestingCallOnNaggyMock(true);
2221 // Tests that --gmock_verbose=warning causes uninteresting calls to be
2223 TEST_F(GMockVerboseFlagTest, Warning) {
2224 GMOCK_FLAG(verbose) = kWarningVerbosity;
2225 TestExpectedCall(false);
2226 TestUninterestingCallOnNaggyMock(true);
2229 // Tests that --gmock_verbose=warning causes neither expected nor
2230 // uninteresting calls to be reported.
2231 TEST_F(GMockVerboseFlagTest, Error) {
2232 GMOCK_FLAG(verbose) = kErrorVerbosity;
2233 TestExpectedCall(false);
2234 TestUninterestingCallOnNaggyMock(false);
2237 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2238 // as --gmock_verbose=warning.
2239 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2240 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
2241 TestExpectedCall(false);
2242 TestUninterestingCallOnNaggyMock(true);
2245 #endif // GTEST_HAS_STREAM_REDIRECTION
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.
2250 class PrintMeNot {};
2252 void 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.";
2257 class LogTestHelper {
2261 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2264 GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
2267 class GMockLogTest : public VerboseFlagPreservingFixture {
2269 LogTestHelper helper_;
2272 TEST_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.
2279 TEST_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.
2286 TEST_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.
2293 // Tests Mock::AllowLeak().
2295 TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2296 MockA* a = new MockA;
2300 TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2301 MockA* a = new MockA;
2303 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2307 TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2308 MockA* a = new MockA;
2309 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2313 TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2314 MockA* a = new MockA;
2316 EXPECT_CALL(*a, DoA(_));
2320 TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2321 MockA* a = new MockA;
2322 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2326 TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2327 MockA* a = new MockA;
2328 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2329 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2333 // Tests that we can verify and clear a mock object's expectations
2334 // when none of its methods has expectations.
2335 TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2337 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
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));
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.
2348 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2350 EXPECT_CALL(b, DoB())
2351 .WillOnce(Return(1));
2353 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
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));
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.
2364 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2366 EXPECT_CALL(b, DoB())
2367 .WillOnce(Return(1));
2369 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2370 "Actual: never called");
2371 ASSERT_FALSE(result);
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));
2379 // Tests that we can verify and clear a mock object's expectations
2380 // when all of its methods have expectations.
2381 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2383 EXPECT_CALL(b, DoB())
2384 .WillOnce(Return(1));
2385 EXPECT_CALL(b, DoB(_))
2386 .WillOnce(Return(2));
2389 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
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));
2397 // Tests that we can verify and clear a mock object's expectations
2398 // when a method has more than one expectation.
2399 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2401 EXPECT_CALL(b, DoB(0))
2402 .WillOnce(Return(1));
2403 EXPECT_CALL(b, DoB(_))
2404 .WillOnce(Return(2));
2407 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2408 "Actual: never called");
2409 ASSERT_FALSE(result);
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));
2417 // Tests that we can call VerifyAndClearExpectations() on the same
2418 // mock object multiple times.
2419 TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2421 EXPECT_CALL(b, DoB());
2423 Mock::VerifyAndClearExpectations(&b);
2425 EXPECT_CALL(b, DoB(_))
2426 .WillOnce(Return(1));
2428 Mock::VerifyAndClearExpectations(&b);
2429 Mock::VerifyAndClearExpectations(&b);
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));
2437 // Tests that we can clear a mock object's default actions when none
2438 // of its methods has default actions.
2439 TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2441 // If this crashes or generates a failure, the test will catch it.
2442 Mock::VerifyAndClear(&b);
2443 EXPECT_EQ(0, b.DoB());
2446 // Tests that we can clear a mock object's default actions when some,
2447 // but not all of its methods have default actions.
2448 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2451 .WillByDefault(Return(1));
2453 Mock::VerifyAndClear(&b);
2455 // Verifies that the default action of int DoB() was removed.
2456 EXPECT_EQ(0, b.DoB());
2459 // Tests that we can clear a mock object's default actions when all of
2460 // its methods have default actions.
2461 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2464 .WillByDefault(Return(1));
2466 .WillByDefault(Return(2));
2468 Mock::VerifyAndClear(&b);
2470 // Verifies that the default action of int DoB() was removed.
2471 EXPECT_EQ(0, b.DoB());
2473 // Verifies that the default action of int DoB(int) was removed.
2474 EXPECT_EQ(0, b.DoB(0));
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.
2479 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2482 .WillByDefault(Return(1));
2484 .WillByDefault(Return(2));
2486 Mock::VerifyAndClear(&b);
2488 // Verifies that the default actions (there are two) of int DoB(int)
2490 EXPECT_EQ(0, b.DoB(0));
2491 EXPECT_EQ(0, b.DoB(1));
2494 // Tests that we can call VerifyAndClear() on a mock object multiple
2496 TEST(VerifyAndClearTest, CanCallManyTimes) {
2499 .WillByDefault(Return(1));
2500 Mock::VerifyAndClear(&b);
2501 Mock::VerifyAndClear(&b);
2504 .WillByDefault(Return(1));
2505 Mock::VerifyAndClear(&b);
2507 EXPECT_EQ(0, b.DoB());
2508 EXPECT_EQ(0, b.DoB(1));
2511 // Tests that VerifyAndClear() works when the verification succeeds.
2512 TEST(VerifyAndClearTest, Success) {
2515 .WillByDefault(Return(1));
2516 EXPECT_CALL(b, DoB(1))
2517 .WillOnce(Return(2));
2521 ASSERT_TRUE(Mock::VerifyAndClear(&b));
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));
2529 // Tests that VerifyAndClear() works when the verification fails.
2530 TEST(VerifyAndClearTest, Failure) {
2533 .WillByDefault(Return(1));
2534 EXPECT_CALL(b, DoB())
2535 .WillOnce(Return(2));
2539 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2540 "Actual: never called");
2541 ASSERT_FALSE(result);
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));
2549 // Tests that VerifyAndClear() works when the default actions and
2550 // expectations are set on a const mock object.
2551 TEST(VerifyAndClearTest, Const) {
2553 ON_CALL(Const(b), DoB())
2554 .WillByDefault(Return(1));
2556 EXPECT_CALL(Const(b), DoB())
2557 .WillOnce(DoDefault())
2558 .WillOnce(Return(2));
2562 ASSERT_TRUE(Mock::VerifyAndClear(&b));
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));
2570 // Tests that we can set default actions and expectations on a mock
2571 // object after VerifyAndClear() has been called on it.
2572 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2575 .WillByDefault(Return(1));
2576 EXPECT_CALL(b, DoB(_))
2577 .WillOnce(Return(2));
2580 Mock::VerifyAndClear(&b);
2582 EXPECT_CALL(b, DoB())
2583 .WillOnce(Return(3));
2585 .WillByDefault(Return(4));
2587 EXPECT_EQ(3, b.DoB());
2588 EXPECT_EQ(4, b.DoB(1));
2591 // Tests that calling VerifyAndClear() on one mock object does not
2592 // affect other mock objects (either of the same type or not).
2593 TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2598 ON_CALL(a, Binary(_, _))
2599 .WillByDefault(Return(true));
2600 EXPECT_CALL(a, Binary(_, _))
2601 .WillOnce(DoDefault())
2602 .WillOnce(Return(false));
2605 .WillByDefault(Return(1));
2606 EXPECT_CALL(b1, DoB(_))
2607 .WillOnce(Return(2));
2610 .WillByDefault(Return(3));
2611 EXPECT_CALL(b2, DoB(_));
2614 Mock::VerifyAndClear(&b2);
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));
2621 EXPECT_EQ(1, b1.DoB());
2622 EXPECT_EQ(2, b1.DoB(0));
2625 TEST(VerifyAndClearTest,
2626 DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2627 std::shared_ptr<MockA> a(new MockA);
2628 ReferenceHoldingMock test_mock;
2630 // EXPECT_CALL stores a reference to a inside test_mock.
2631 EXPECT_CALL(test_mock, AcceptReference(_))
2632 .WillRepeatedly(SetArgPointee<0>(a));
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.
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.
2645 TEST(VerifyAndClearTest,
2646 DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2647 std::shared_ptr<MockA> a(new MockA);
2648 ReferenceHoldingMock test_mock;
2650 // ON_CALL stores a reference to a inside test_mock.
2651 ON_CALL(test_mock, AcceptReference(_))
2652 .WillByDefault(SetArgPointee<0>(a));
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.
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.
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
2670 TEST(SynchronizationTest, CanCallMockMethodInAction) {
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());
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.
2689 TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
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));
2697 EXPECT_THAT(do_a_arg0, 17);
2698 EXPECT_THAT(do_a_47_arg0, 0);
2700 EXPECT_THAT(do_a_arg0, 17);
2701 EXPECT_THAT(do_a_47_arg0, 47);
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);
2709 TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
2711 ON_CALL(b, DoB()).WillByDefault(Return(9));
2712 ON_CALL(b, DoB(5)).WillByDefault(Return(11));
2714 EXPECT_THAT(b.DoB(), 9);
2715 EXPECT_THAT(b.DoB(1), 0); // default value
2716 EXPECT_THAT(b.DoB(5), 11);
2719 struct MockWithConstMethods {
2721 MOCK_CONST_METHOD1(Foo, int(int));
2722 MOCK_CONST_METHOD2(Bar, int(int, const char*));
2725 TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
2726 MockWithConstMethods mock;
2727 ON_CALL(mock, Foo).WillByDefault(Return(7));
2728 ON_CALL(mock, Bar).WillByDefault(Return(33));
2730 EXPECT_THAT(mock.Foo(17), 7);
2731 EXPECT_THAT(mock.Bar(27, "purple"), 33);
2734 class MockConstOverload {
2736 MOCK_METHOD1(Overloaded, int(int));
2737 MOCK_CONST_METHOD1(Overloaded, int(int));
2740 TEST(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));
2748 EXPECT_THAT(mock.Overloaded(1), 7);
2749 EXPECT_THAT(mock.Overloaded(5), 9);
2750 EXPECT_THAT(mock.Overloaded(7), 7);
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);
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
2764 int gmock_main(int argc, char **argv) {
2766 int 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;
2774 return RUN_ALL_TESTS();