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"
37 #include <ostream> // NOLINT
41 #include "gmock/gmock.h"
42 #include "gmock/internal/gmock-port.h"
43 #include "gtest/gtest.h"
44 #include "gtest/gtest-spi.h"
45 #include "gtest/internal/gtest-port.h"
50 // Helper class for testing the Expectation class template.
51 class ExpectationTester {
53 // Sets the call count of the given expectation to the given number.
54 void SetCallCount(int n, ExpectationBase* exp) {
59 } // namespace internal
60 } // namespace testing
65 using testing::AnyNumber;
66 using testing::AtLeast;
67 using testing::AtMost;
68 using testing::Between;
69 using testing::Cardinality;
70 using testing::CardinalityInterface;
71 using testing::ContainsRegex;
74 using testing::DoDefault;
76 using testing::Expectation;
77 using testing::ExpectationSet;
78 using testing::GMOCK_FLAG(verbose);
80 using testing::InSequence;
81 using testing::Invoke;
82 using testing::InvokeWithoutArgs;
83 using testing::IsNotSubstring;
84 using testing::IsSubstring;
86 using testing::Message;
88 using testing::NaggyMock;
90 using testing::Return;
91 using testing::SaveArg;
92 using testing::Sequence;
93 using testing::SetArgPointee;
94 using testing::internal::ExpectationTester;
95 using testing::internal::FormatFileLocation;
96 using testing::internal::kAllow;
97 using testing::internal::kErrorVerbosity;
98 using testing::internal::kFail;
99 using testing::internal::kInfoVerbosity;
100 using testing::internal::kWarn;
101 using testing::internal::kWarningVerbosity;
102 using testing::internal::linked_ptr;
104 #if GTEST_HAS_STREAM_REDIRECTION
105 using testing::HasSubstr;
106 using testing::internal::CaptureStdout;
107 using testing::internal::GetCapturedStdout;
112 class MockIncomplete {
114 // This line verifies that a mock method can take a by-reference
115 // argument of an incomplete type.
116 MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
119 // Tells Google Mock how to print a value of type Incomplete.
120 void PrintTo(const Incomplete& x, ::std::ostream* os);
122 TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
123 // Even though this mock class contains a mock method that takes
124 // by-reference an argument whose type is incomplete, we can still
125 // use the mock, as long as Google Mock knows how to print the
127 MockIncomplete incomplete;
128 EXPECT_CALL(incomplete, ByRefFunc(_))
132 // The definition of the printer for the argument type doesn't have to
133 // be visible where the mock is used.
134 void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
140 // A type that's not default constructible.
141 class NonDefaultConstructible {
143 explicit NonDefaultConstructible(int /* dummy */) {}
150 MOCK_METHOD1(DoA, void(int n));
151 MOCK_METHOD1(ReturnResult, Result(int n));
152 MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
153 MOCK_METHOD2(Binary, bool(int x, int y));
154 MOCK_METHOD2(ReturnInt, int(int x, int y));
157 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
164 MOCK_CONST_METHOD0(DoB, int()); // NOLINT
165 MOCK_METHOD1(DoB, int(int n)); // NOLINT
168 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
171 class ReferenceHoldingMock {
173 ReferenceHoldingMock() {}
175 MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
178 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
181 // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
182 // redefining a mock method name. This could happen, for example, when
183 // the tested code #includes Win32 API headers which define many APIs
184 // as macros, e.g. #define TextOut TextOutW.
186 #define Method MethodW
191 virtual int Method() = 0;
193 class MockCC : public CC {
197 MOCK_METHOD0(Method, int());
200 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
203 // Tests that a method with expanded name compiles.
204 TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
206 ON_CALL(cc, Method());
209 // Tests that the method with expanded name not only compiles but runs
210 // and returns a correct value, too.
211 TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
213 ON_CALL(cc, Method()).WillByDefault(Return(42));
214 EXPECT_EQ(42, cc.Method());
217 // Tests that a method with expanded name compiles.
218 TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
220 EXPECT_CALL(cc, Method());
224 // Tests that it works, too.
225 TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
227 EXPECT_CALL(cc, Method()).WillOnce(Return(42));
228 EXPECT_EQ(42, cc.Method());
231 #undef Method // Done with macro redefinition tests.
233 // Tests that ON_CALL evaluates its arguments exactly once as promised
235 TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
239 ON_CALL(*pa++, DoA(_));
240 EXPECT_EQ(&a + 1, pa);
243 TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
247 ON_CALL(a, DoA(n++));
251 // Tests that the syntax of ON_CALL() is enforced at run time.
253 TEST(OnCallSyntaxTest, WithIsOptional) {
257 .WillByDefault(Return());
260 .WillByDefault(Return());
263 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
266 EXPECT_NONFATAL_FAILURE({ // NOLINT
267 ON_CALL(a, ReturnResult(_))
270 .WillByDefault(Return(Result()));
271 }, ".With() cannot appear more than once in an ON_CALL()");
274 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
277 EXPECT_DEATH_IF_SUPPORTED({
283 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
286 EXPECT_NONFATAL_FAILURE({ // NOLINT
288 .WillByDefault(Return())
289 .WillByDefault(Return());
290 }, ".WillByDefault() must appear exactly once in an ON_CALL()");
293 // Tests that EXPECT_CALL evaluates its arguments exactly once as
294 // promised by Google Mock.
295 TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
299 EXPECT_CALL(*pa++, DoA(_));
301 EXPECT_EQ(&a + 1, pa);
304 TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
308 EXPECT_CALL(a, DoA(n++));
313 // Tests that the syntax of EXPECT_CALL() is enforced at run time.
315 TEST(ExpectCallSyntaxTest, WithIsOptional) {
318 EXPECT_CALL(a, DoA(5))
320 EXPECT_CALL(a, DoA(6))
325 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
328 EXPECT_NONFATAL_FAILURE({ // NOLINT
329 EXPECT_CALL(a, DoA(6))
332 }, ".With() cannot appear more than once in an EXPECT_CALL()");
337 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
340 EXPECT_NONFATAL_FAILURE({ // NOLINT
341 EXPECT_CALL(a, DoA(1))
344 }, ".With() must be the first clause in an EXPECT_CALL()");
348 EXPECT_NONFATAL_FAILURE({ // NOLINT
349 EXPECT_CALL(a, DoA(2))
352 }, ".With() must be the first clause in an EXPECT_CALL()");
357 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
360 EXPECT_CALL(a, DoA(1))
363 EXPECT_CALL(a, DoA(2))
365 .WillRepeatedly(Return());
372 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
375 EXPECT_NONFATAL_FAILURE({ // NOLINT
376 EXPECT_CALL(a, DoA(1))
379 }, ".Times() cannot appear more than once in an EXPECT_CALL()");
385 TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
389 EXPECT_NONFATAL_FAILURE({ // NOLINT
390 EXPECT_CALL(a, DoA(1))
393 }, ".Times() cannot appear after ");
398 TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
402 EXPECT_CALL(a, DoA(1));
403 EXPECT_CALL(a, DoA(2))
410 TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
414 EXPECT_CALL(a, DoA(1))
421 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
425 Expectation e = EXPECT_CALL(a, DoA(1))
427 EXPECT_NONFATAL_FAILURE({ // NOLINT
428 EXPECT_CALL(a, DoA(2))
431 }, ".InSequence() cannot appear after ");
436 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
440 EXPECT_NONFATAL_FAILURE({ // NOLINT
441 EXPECT_CALL(a, DoA(1))
444 }, ".InSequence() cannot appear after ");
449 TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
452 Expectation e = EXPECT_CALL(a, DoA(1));
453 EXPECT_NONFATAL_FAILURE({
454 EXPECT_CALL(a, DoA(2))
457 }, ".After() cannot appear after ");
463 TEST(ExpectCallSyntaxTest, WillIsOptional) {
466 EXPECT_CALL(a, DoA(1));
467 EXPECT_CALL(a, DoA(2))
474 TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
477 EXPECT_CALL(a, DoA(1))
484 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
487 EXPECT_NONFATAL_FAILURE({ // NOLINT
488 EXPECT_CALL(a, DoA(1))
489 .WillRepeatedly(Return())
491 }, ".WillOnce() cannot appear after ");
496 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
499 EXPECT_CALL(a, DoA(1))
501 EXPECT_CALL(a, DoA(2))
503 .WillRepeatedly(Return());
510 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
513 EXPECT_NONFATAL_FAILURE({ // NOLINT
514 EXPECT_CALL(a, DoA(1))
515 .WillRepeatedly(Return())
516 .WillRepeatedly(Return());
517 }, ".WillRepeatedly() cannot appear more than once in an "
521 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
524 EXPECT_NONFATAL_FAILURE({ // NOLINT
525 EXPECT_CALL(a, DoA(1))
526 .RetiresOnSaturation()
527 .WillRepeatedly(Return());
528 }, ".WillRepeatedly() cannot appear after ");
531 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
534 EXPECT_CALL(a, DoA(1));
535 EXPECT_CALL(a, DoA(1))
536 .RetiresOnSaturation();
542 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
545 EXPECT_NONFATAL_FAILURE({ // NOLINT
546 EXPECT_CALL(a, DoA(1))
547 .RetiresOnSaturation()
548 .RetiresOnSaturation();
549 }, ".RetiresOnSaturation() cannot appear more than once");
554 TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
557 EXPECT_CALL(a, DoA(1));
560 EXPECT_NONFATAL_FAILURE({ // NOLINT
562 EXPECT_CALL(a, DoA(1));
563 }, "to be called once");
564 EXPECT_NONFATAL_FAILURE({ // NOLINT
566 EXPECT_CALL(a, DoA(1));
569 }, "to be called once");
572 #if GTEST_HAS_STREAM_REDIRECTION
574 // Tests that Google Mock doesn't print a warning when the number of
575 // WillOnce() is adequate.
576 TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
581 // It's always fine to omit WillOnce() entirely.
582 EXPECT_CALL(b, DoB())
584 EXPECT_CALL(b, DoB(1))
586 EXPECT_CALL(b, DoB(2))
588 .WillRepeatedly(Return(1));
590 // It's fine for the number of WillOnce()s to equal the upper bound.
591 EXPECT_CALL(b, DoB(3))
592 .Times(Between(1, 2))
594 .WillOnce(Return(2));
596 // It's fine for the number of WillOnce()s to be smaller than the
597 // upper bound when there is a WillRepeatedly().
598 EXPECT_CALL(b, DoB(4))
601 .WillRepeatedly(Return(2));
603 // Satisfies the above expectations.
607 EXPECT_STREQ("", GetCapturedStdout().c_str());
610 // Tests that Google Mock warns on having too many actions in an
611 // expectation compared to its cardinality.
612 TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
617 // Warns when the number of WillOnce()s is larger than the upper bound.
618 EXPECT_CALL(b, DoB())
620 .WillOnce(Return(1)); // #1
621 EXPECT_CALL(b, DoB())
624 .WillOnce(Return(2)); // #2
625 EXPECT_CALL(b, DoB(1))
629 .RetiresOnSaturation(); // #3
631 // Warns when the number of WillOnce()s equals the upper bound and
632 // there is a WillRepeatedly().
633 EXPECT_CALL(b, DoB())
635 .WillRepeatedly(Return(1)); // #4
636 EXPECT_CALL(b, DoB(2))
639 .WillRepeatedly(Return(2)); // #5
641 // Satisfies the above expectations.
645 const std::string output = GetCapturedStdout();
648 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
649 "Expected to be never called, but has 1 WillOnce().",
653 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
654 "Expected to be called at most once, "
655 "but has 2 WillOnce()s.",
659 "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
660 "Expected to be called once, but has 2 WillOnce()s.",
664 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
665 "Expected to be never called, but has 0 WillOnce()s "
666 "and a WillRepeatedly().",
670 "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
671 "Expected to be called once, but has 1 WillOnce() "
672 "and a WillRepeatedly().",
676 // Tests that Google Mock warns on having too few actions in an
677 // expectation compared to its cardinality.
678 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
681 EXPECT_CALL(b, DoB())
682 .Times(Between(2, 3))
683 .WillOnce(Return(1));
687 const std::string output = GetCapturedStdout();
690 "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
691 "Expected to be called between 2 and 3 times, "
692 "but has only 1 WillOnce().",
697 TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
698 int original_behavior = testing::GMOCK_FLAG(default_mock_behavior);
700 testing::GMOCK_FLAG(default_mock_behavior) = kAllow;
706 std::string output = GetCapturedStdout();
707 EXPECT_TRUE(output.empty()) << output;
709 testing::GMOCK_FLAG(default_mock_behavior) = kWarn;
715 std::string warning_output = GetCapturedStdout();
716 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
717 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
720 testing::GMOCK_FLAG(default_mock_behavior) = kFail;
721 EXPECT_NONFATAL_FAILURE({
724 }, "Uninteresting mock function call");
726 // Out of bounds values are converted to kWarn
727 testing::GMOCK_FLAG(default_mock_behavior) = -1;
733 warning_output = GetCapturedStdout();
734 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
735 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
737 testing::GMOCK_FLAG(default_mock_behavior) = 3;
743 warning_output = GetCapturedStdout();
744 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
745 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
748 testing::GMOCK_FLAG(default_mock_behavior) = original_behavior;
751 #endif // GTEST_HAS_STREAM_REDIRECTION
753 // Tests the semantics of ON_CALL().
755 // Tests that the built-in default action is taken when no ON_CALL()
757 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
759 EXPECT_CALL(b, DoB());
761 EXPECT_EQ(0, b.DoB());
764 // Tests that the built-in default action is taken when no ON_CALL()
765 // matches the invocation.
766 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
769 .WillByDefault(Return(1));
770 EXPECT_CALL(b, DoB(_));
772 EXPECT_EQ(0, b.DoB(2));
775 // Tests that the last matching ON_CALL() action is taken.
776 TEST(OnCallTest, PicksLastMatchingOnCall) {
779 .WillByDefault(Return(3));
781 .WillByDefault(Return(2));
783 .WillByDefault(Return(1));
784 EXPECT_CALL(b, DoB(_));
786 EXPECT_EQ(2, b.DoB(2));
789 // Tests the semantics of EXPECT_CALL().
791 // Tests that any call is allowed when no EXPECT_CALL() is specified.
792 TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
794 EXPECT_CALL(b, DoB());
795 // There is no expectation on DoB(int).
799 // DoB(int) can be called any number of times.
804 // Tests that the last matching EXPECT_CALL() fires.
805 TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
807 EXPECT_CALL(b, DoB(_))
808 .WillRepeatedly(Return(2));
809 EXPECT_CALL(b, DoB(1))
810 .WillRepeatedly(Return(1));
812 EXPECT_EQ(1, b.DoB(1));
815 // Tests lower-bound violation.
816 TEST(ExpectCallTest, CatchesTooFewCalls) {
817 EXPECT_NONFATAL_FAILURE({ // NOLINT
819 EXPECT_CALL(b, DoB(5))
823 }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
824 " Expected: to be called at least twice\n"
825 " Actual: called once - unsatisfied and active");
828 // Tests that the cardinality can be inferred when no Times(...) is
830 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
833 EXPECT_CALL(b, DoB())
835 .WillOnce(Return(2));
837 EXPECT_EQ(1, b.DoB());
838 EXPECT_EQ(2, b.DoB());
841 EXPECT_NONFATAL_FAILURE({ // NOLINT
843 EXPECT_CALL(b, DoB())
845 .WillOnce(Return(2));
847 EXPECT_EQ(1, b.DoB());
848 }, "to be called twice");
852 EXPECT_CALL(b, DoB())
854 .WillOnce(Return(2));
856 EXPECT_EQ(1, b.DoB());
857 EXPECT_EQ(2, b.DoB());
858 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
862 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
865 EXPECT_CALL(b, DoB())
867 .WillRepeatedly(Return(2));
869 EXPECT_EQ(1, b.DoB());
874 EXPECT_CALL(b, DoB())
876 .WillRepeatedly(Return(2));
878 EXPECT_EQ(1, b.DoB());
879 EXPECT_EQ(2, b.DoB());
880 EXPECT_EQ(2, b.DoB());
883 EXPECT_NONFATAL_FAILURE({ // NOLINT
885 EXPECT_CALL(b, DoB())
887 .WillRepeatedly(Return(2));
888 }, "to be called at least once");
891 // Tests that the n-th action is taken for the n-th matching
893 TEST(ExpectCallTest, NthMatchTakesNthAction) {
895 EXPECT_CALL(b, DoB())
898 .WillOnce(Return(3));
900 EXPECT_EQ(1, b.DoB());
901 EXPECT_EQ(2, b.DoB());
902 EXPECT_EQ(3, b.DoB());
905 // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
906 // list is exhausted.
907 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
909 EXPECT_CALL(b, DoB())
911 .WillRepeatedly(Return(2));
913 EXPECT_EQ(1, b.DoB());
914 EXPECT_EQ(2, b.DoB());
915 EXPECT_EQ(2, b.DoB());
918 #if GTEST_HAS_STREAM_REDIRECTION
920 // Tests that the default action is taken when the WillOnce(...) list is
921 // exhausted and there is no WillRepeatedly().
922 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
924 EXPECT_CALL(b, DoB(_))
926 EXPECT_CALL(b, DoB())
929 .WillOnce(Return(2));
932 EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
933 // expectation has no action clause at all.
934 EXPECT_EQ(1, b.DoB());
935 EXPECT_EQ(2, b.DoB());
936 const std::string output1 = GetCapturedStdout();
937 EXPECT_STREQ("", output1.c_str());
940 EXPECT_EQ(0, b.DoB());
941 EXPECT_EQ(0, b.DoB());
942 const std::string output2 = GetCapturedStdout();
943 EXPECT_THAT(output2.c_str(),
944 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
945 "Called 3 times, but only 2 WillOnce()s are specified"
946 " - returning default value."));
947 EXPECT_THAT(output2.c_str(),
948 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
949 "Called 4 times, but only 2 WillOnce()s are specified"
950 " - returning default value."));
953 TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
955 std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
956 EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
958 EXPECT_EQ(1, b.DoB());
961 EXPECT_EQ(0, b.DoB());
962 const std::string output = GetCapturedStdout();
963 // The warning message should contain the call location.
964 EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
967 TEST(FunctionMockerMessageTest,
968 ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
969 std::string on_call_location;
973 on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
974 ON_CALL(b, DoB(_)).WillByDefault(Return(0));
977 EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
980 #endif // GTEST_HAS_STREAM_REDIRECTION
982 // Tests that an uninteresting call performs the default action.
983 TEST(UninterestingCallTest, DoesDefaultAction) {
984 // When there is an ON_CALL() statement, the action specified by it
987 ON_CALL(a, Binary(_, _))
988 .WillByDefault(Return(true));
989 EXPECT_TRUE(a.Binary(1, 2));
991 // When there is no ON_CALL(), the default value for the return type
992 // should be returned.
994 EXPECT_EQ(0, b.DoB());
997 // Tests that an unexpected call performs the default action.
998 TEST(UnexpectedCallTest, DoesDefaultAction) {
999 // When there is an ON_CALL() statement, the action specified by it
1002 ON_CALL(a, Binary(_, _))
1003 .WillByDefault(Return(true));
1004 EXPECT_CALL(a, Binary(0, 0));
1006 bool result = false;
1007 EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
1008 "Unexpected mock function call");
1009 EXPECT_TRUE(result);
1011 // When there is no ON_CALL(), the default value for the return type
1012 // should be returned.
1014 EXPECT_CALL(b, DoB(0))
1017 EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
1018 "Unexpected mock function call");
1022 // Tests that when an unexpected void function generates the right
1024 TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
1025 // First, tests the message when there is only one EXPECT_CALL().
1027 EXPECT_CALL(a1, DoA(1));
1029 // Ideally we should match the failure message against a regex, but
1030 // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
1031 // multiple sub-strings instead.
1032 EXPECT_NONFATAL_FAILURE(
1034 "Unexpected mock function call - returning directly.\n"
1035 " Function call: DoA(9)\n"
1036 "Google Mock tried the following 1 expectation, but it didn't match:");
1037 EXPECT_NONFATAL_FAILURE(
1039 " Expected arg #0: is equal to 1\n"
1041 " Expected: to be called once\n"
1042 " Actual: called once - saturated and active");
1044 // Next, tests the message when there are more than one EXPECT_CALL().
1046 EXPECT_CALL(a2, DoA(1));
1047 EXPECT_CALL(a2, DoA(3));
1049 EXPECT_NONFATAL_FAILURE(
1051 "Unexpected mock function call - returning directly.\n"
1052 " Function call: DoA(2)\n"
1053 "Google Mock tried the following 2 expectations, but none matched:");
1054 EXPECT_NONFATAL_FAILURE(
1056 "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1057 " Expected arg #0: is equal to 1\n"
1059 " Expected: to be called once\n"
1060 " Actual: called once - saturated and active");
1061 EXPECT_NONFATAL_FAILURE(
1063 "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1064 " Expected arg #0: is equal to 3\n"
1066 " Expected: to be called once\n"
1067 " Actual: never called - unsatisfied and active");
1071 // Tests that an unexpected non-void function generates the right
1073 TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1075 EXPECT_CALL(b1, DoB(1));
1077 EXPECT_NONFATAL_FAILURE(
1079 "Unexpected mock function call - returning default value.\n"
1080 " Function call: DoB(2)\n"
1082 "Google Mock tried the following 1 expectation, but it didn't match:");
1083 EXPECT_NONFATAL_FAILURE(
1085 " Expected arg #0: is equal to 1\n"
1087 " Expected: to be called once\n"
1088 " Actual: called once - saturated and active");
1091 // Tests that Google Mock explains that an retired expectation doesn't
1093 TEST(UnexpectedCallTest, RetiredExpectation) {
1095 EXPECT_CALL(b, DoB(1))
1096 .RetiresOnSaturation();
1099 EXPECT_NONFATAL_FAILURE(
1101 " Expected: the expectation is active\n"
1102 " Actual: it is retired");
1105 // Tests that Google Mock explains that an expectation that doesn't
1106 // match the arguments doesn't match the call.
1107 TEST(UnexpectedCallTest, UnmatchedArguments) {
1109 EXPECT_CALL(b, DoB(1));
1111 EXPECT_NONFATAL_FAILURE(
1113 " Expected arg #0: is equal to 1\n"
1118 // Tests that Google Mock explains that an expectation with
1119 // unsatisfied pre-requisites doesn't match the call.
1120 TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1123 EXPECT_CALL(b, DoB(1))
1125 EXPECT_CALL(b, DoB(2))
1128 EXPECT_CALL(b, DoB(3))
1130 EXPECT_CALL(b, DoB(4))
1131 .InSequence(s1, s2);
1133 ::testing::TestPartResultArray failures;
1135 ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1137 // Now 'failures' contains the Google Test failures generated by
1138 // the above statement.
1141 // There should be one non-fatal failure.
1142 ASSERT_EQ(1, failures.size());
1143 const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
1144 EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1146 // Verifies that the failure message contains the two unsatisfied
1147 // pre-requisites but not the satisfied one.
1149 EXPECT_THAT(r.message(), ContainsRegex(
1150 // PCRE has trouble using (.|\n) to match any character, but
1151 // supports the (?s) prefix for using . to match any character.
1152 "(?s)the following immediate pre-requisites are not satisfied:\n"
1153 ".*: pre-requisite #0\n"
1154 ".*: pre-requisite #1"));
1155 #elif GTEST_USES_POSIX_RE
1156 EXPECT_THAT(r.message(), ContainsRegex(
1157 // POSIX RE doesn't understand the (?s) prefix, but has no trouble
1159 "the following immediate pre-requisites are not satisfied:\n"
1160 "(.|\n)*: pre-requisite #0\n"
1161 "(.|\n)*: pre-requisite #1"));
1163 // We can only use Google Test's own simple regex.
1164 EXPECT_THAT(r.message(), ContainsRegex(
1165 "the following immediate pre-requisites are not satisfied:"));
1166 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1167 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1168 #endif // GTEST_USES_PCRE
1175 TEST(UndefinedReturnValueTest,
1176 ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1178 // FIXME: We should really verify the output message,
1179 // but we cannot yet due to that EXPECT_DEATH only captures stderr
1180 // while Google Mock logs to stdout.
1181 #if GTEST_HAS_EXCEPTIONS
1182 EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1184 EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1188 // Tests that an excessive call (one whose arguments match the
1189 // matchers but is called too many times) performs the default action.
1190 TEST(ExcessiveCallTest, DoesDefaultAction) {
1191 // When there is an ON_CALL() statement, the action specified by it
1194 ON_CALL(a, Binary(_, _))
1195 .WillByDefault(Return(true));
1196 EXPECT_CALL(a, Binary(0, 0));
1198 bool result = false;
1199 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1200 "Mock function called more times than expected");
1201 EXPECT_TRUE(result);
1203 // When there is no ON_CALL(), the default value for the return type
1204 // should be returned.
1206 EXPECT_CALL(b, DoB(0))
1209 EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1210 "Mock function called more times than expected");
1214 // Tests that when a void function is called too many times,
1215 // the failure message contains the argument values.
1216 TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1218 EXPECT_CALL(a, DoA(_))
1220 EXPECT_NONFATAL_FAILURE(
1222 "Mock function called more times than expected - returning directly.\n"
1223 " Function call: DoA(9)\n"
1224 " Expected: to be never called\n"
1225 " Actual: called once - over-saturated and active");
1228 // Tests that when a non-void function is called too many times, the
1229 // failure message contains the argument values and the return value.
1230 TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1232 EXPECT_CALL(b, DoB(_));
1234 EXPECT_NONFATAL_FAILURE(
1236 "Mock function called more times than expected - "
1237 "returning default value.\n"
1238 " Function call: DoB(2)\n"
1240 " Expected: to be called once\n"
1241 " Actual: called twice - over-saturated and active");
1244 // Tests using sequences.
1246 TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1251 EXPECT_CALL(a, DoA(1));
1252 EXPECT_CALL(a, DoA(2));
1255 EXPECT_NONFATAL_FAILURE({ // NOLINT
1257 }, "Unexpected mock function call");
1263 TEST(InSequenceTest, NestedInSequence) {
1268 EXPECT_CALL(a, DoA(1));
1272 EXPECT_CALL(a, DoA(2));
1273 EXPECT_CALL(a, DoA(3));
1277 EXPECT_NONFATAL_FAILURE({ // NOLINT
1280 }, "Unexpected mock function call");
1286 TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1291 EXPECT_CALL(a, DoA(1));
1292 EXPECT_CALL(a, DoA(2));
1294 EXPECT_CALL(a, DoA(3));
1296 EXPECT_NONFATAL_FAILURE({ // NOLINT
1298 }, "Unexpected mock function call");
1305 // Tests that any order is allowed when no sequence is used.
1306 TEST(SequenceTest, AnyOrderIsOkByDefault) {
1311 EXPECT_CALL(a, DoA(1));
1312 EXPECT_CALL(b, DoB())
1313 .Times(AnyNumber());
1323 EXPECT_CALL(a, DoA(1));
1324 EXPECT_CALL(b, DoB())
1325 .Times(AnyNumber());
1332 // Tests that the calls must be in strict order when a complete order
1334 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1336 ON_CALL(a, ReturnResult(_))
1337 .WillByDefault(Return(Result()));
1340 EXPECT_CALL(a, ReturnResult(1))
1342 EXPECT_CALL(a, ReturnResult(2))
1344 EXPECT_CALL(a, ReturnResult(3))
1349 // May only be called after a.ReturnResult(2).
1350 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1356 // Tests that the calls must be in strict order when a complete order
1358 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1360 ON_CALL(a, ReturnResult(_))
1361 .WillByDefault(Return(Result()));
1364 EXPECT_CALL(a, ReturnResult(1))
1366 EXPECT_CALL(a, ReturnResult(2))
1369 // May only be called after a.ReturnResult(1).
1370 EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1376 // Tests specifying a DAG using multiple sequences.
1377 class PartialOrderTest : public testing::Test {
1379 PartialOrderTest() {
1380 ON_CALL(a_, ReturnResult(_))
1381 .WillByDefault(Return(Result()));
1383 // Specifies this partial ordering:
1385 // a.ReturnResult(1) ==>
1386 // a.ReturnResult(2) * n ==> a.ReturnResult(3)
1389 EXPECT_CALL(a_, ReturnResult(1))
1391 EXPECT_CALL(b_, DoB())
1394 EXPECT_CALL(a_, ReturnResult(2))
1397 EXPECT_CALL(a_, ReturnResult(3))
1405 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
1409 // May only be called after the second DoB().
1410 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1416 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
1417 // May only be called after ReturnResult(1).
1418 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1426 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
1427 // May only be called last.
1428 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
1436 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
1442 // May only be called before ReturnResult(3).
1443 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1446 TEST(SequenceTest, Retirement) {
1450 EXPECT_CALL(a, DoA(1))
1452 EXPECT_CALL(a, DoA(_))
1454 .RetiresOnSaturation();
1455 EXPECT_CALL(a, DoA(1))
1463 // Tests Expectation.
1465 TEST(ExpectationTest, ConstrutorsWork) {
1467 Expectation e1; // Default ctor.
1469 // Ctor from various forms of EXPECT_CALL.
1470 Expectation e2 = EXPECT_CALL(a, DoA(2));
1471 Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1474 Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1475 Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1477 Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1478 Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1479 Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1480 Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1482 Expectation e10 = e2; // Copy ctor.
1484 EXPECT_THAT(e1, Ne(e2));
1485 EXPECT_THAT(e2, Eq(e10));
1497 TEST(ExpectationTest, AssignmentWorks) {
1500 Expectation e2 = EXPECT_CALL(a, DoA(1));
1502 EXPECT_THAT(e1, Ne(e2));
1505 EXPECT_THAT(e1, Eq(e2));
1510 // Tests ExpectationSet.
1512 TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1513 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1516 TEST(ExpectationSetTest, ConstructorsWork) {
1520 const Expectation e2;
1521 ExpectationSet es1; // Default ctor.
1522 ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
1523 ExpectationSet es3 = e1; // Ctor from Expectation.
1524 ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
1525 ExpectationSet es5 = e2; // Ctor from const Expectation.
1526 ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
1527 ExpectationSet es7 = es2; // Copy ctor.
1529 EXPECT_EQ(0, es1.size());
1530 EXPECT_EQ(1, es2.size());
1531 EXPECT_EQ(1, es3.size());
1532 EXPECT_EQ(1, es4.size());
1533 EXPECT_EQ(1, es5.size());
1534 EXPECT_EQ(1, es6.size());
1535 EXPECT_EQ(1, es7.size());
1537 EXPECT_THAT(es3, Ne(es2));
1538 EXPECT_THAT(es4, Eq(es3));
1539 EXPECT_THAT(es5, Eq(es4));
1540 EXPECT_THAT(es6, Eq(es5));
1541 EXPECT_THAT(es7, Eq(es2));
1545 TEST(ExpectationSetTest, AssignmentWorks) {
1547 ExpectationSet es2 = Expectation();
1550 EXPECT_EQ(1, es1.size());
1551 EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1552 EXPECT_THAT(es1, Eq(es2));
1555 TEST(ExpectationSetTest, InsertionWorks) {
1559 EXPECT_EQ(1, es1.size());
1560 EXPECT_THAT(*(es1.begin()), Eq(e1));
1563 Expectation e2 = EXPECT_CALL(a, DoA(1));
1565 EXPECT_EQ(2, es1.size());
1567 ExpectationSet::const_iterator it1 = es1.begin();
1568 ExpectationSet::const_iterator it2 = it1;
1570 EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
1571 EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
1575 TEST(ExpectationSetTest, SizeWorks) {
1577 EXPECT_EQ(0, es.size());
1579 es += Expectation();
1580 EXPECT_EQ(1, es.size());
1583 es += EXPECT_CALL(a, DoA(1));
1584 EXPECT_EQ(2, es.size());
1589 TEST(ExpectationSetTest, IsEnumerable) {
1591 EXPECT_TRUE(es.begin() == es.end());
1593 es += Expectation();
1594 ExpectationSet::const_iterator it = es.begin();
1595 EXPECT_TRUE(it != es.end());
1596 EXPECT_THAT(*it, Eq(Expectation()));
1598 EXPECT_TRUE(it== es.end());
1601 // Tests the .After() clause.
1603 TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1606 es += EXPECT_CALL(a, DoA(1));
1607 es += EXPECT_CALL(a, DoA(2));
1608 EXPECT_CALL(a, DoA(3))
1616 TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1619 // The following also verifies that const Expectation objects work
1620 // too. Do not remove the const modifiers.
1621 const Expectation e1 = EXPECT_CALL(a, DoA(1));
1622 const Expectation e2 = EXPECT_CALL(b, DoB())
1625 EXPECT_CALL(a, DoA(2)).After(e2);
1633 // Calls must be in strict order when specified so using .After().
1634 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1639 // a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1640 Expectation e1 = EXPECT_CALL(a, DoA(1));
1641 Expectation e2 = EXPECT_CALL(b, DoB())
1643 EXPECT_CALL(a, DoA(2))
1648 // May only be called after DoB().
1649 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1655 // Calls must be in strict order when specified so using .After().
1656 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
1661 // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
1662 Expectation e1 = EXPECT_CALL(a, DoA(1));
1663 Expectation e2 = EXPECT_CALL(b, DoB())
1666 EXPECT_CALL(a, DoA(2))
1672 // May only be called after the second DoB().
1673 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1679 // Calls must satisfy the partial order when specified so.
1680 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1682 ON_CALL(a, ReturnResult(_))
1683 .WillByDefault(Return(Result()));
1687 // a.DoA(2) ==> a.ReturnResult(3)
1688 Expectation e = EXPECT_CALL(a, DoA(1));
1689 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1690 EXPECT_CALL(a, ReturnResult(3))
1693 // May only be called last.
1694 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1701 // Calls must satisfy the partial order when specified so.
1702 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
1707 // a.DoA(2) ==> a.DoA(3)
1708 Expectation e = EXPECT_CALL(a, DoA(1));
1709 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1710 EXPECT_CALL(a, DoA(3))
1715 // May only be called last.
1716 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1722 // .After() can be combined with .InSequence().
1723 TEST(AfterTest, CanBeUsedWithInSequence) {
1726 Expectation e = EXPECT_CALL(a, DoA(1));
1727 EXPECT_CALL(a, DoA(2)).InSequence(s);
1728 EXPECT_CALL(a, DoA(3))
1734 // May only be after DoA(2).
1735 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1741 // .After() can be called multiple times.
1742 TEST(AfterTest, CanBeCalledManyTimes) {
1744 Expectation e1 = EXPECT_CALL(a, DoA(1));
1745 Expectation e2 = EXPECT_CALL(a, DoA(2));
1746 Expectation e3 = EXPECT_CALL(a, DoA(3));
1747 EXPECT_CALL(a, DoA(4))
1758 // .After() accepts up to 5 arguments.
1759 TEST(AfterTest, AcceptsUpToFiveArguments) {
1761 Expectation e1 = EXPECT_CALL(a, DoA(1));
1762 Expectation e2 = EXPECT_CALL(a, DoA(2));
1763 Expectation e3 = EXPECT_CALL(a, DoA(3));
1764 ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1765 ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1766 EXPECT_CALL(a, DoA(6))
1767 .After(e1, e2, e3, es1, es2);
1777 // .After() allows input to contain duplicated Expectations.
1778 TEST(AfterTest, AcceptsDuplicatedInput) {
1780 ON_CALL(a, ReturnResult(_))
1781 .WillByDefault(Return(Result()));
1785 // DoA(2) ==> ReturnResult(3)
1786 Expectation e1 = EXPECT_CALL(a, DoA(1));
1787 Expectation e2 = EXPECT_CALL(a, DoA(2));
1791 EXPECT_CALL(a, ReturnResult(3))
1792 .After(e1, e2, es, e1);
1796 // May only be after DoA(2).
1797 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1803 // An Expectation added to an ExpectationSet after it has been used in
1804 // an .After() has no effect.
1805 TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1807 ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1808 Expectation e2 = EXPECT_CALL(a, DoA(2));
1809 EXPECT_CALL(a, DoA(3))
1818 // Tests that Google Mock correctly handles calls to mock functions
1819 // after a mock object owning one of their pre-requisites has died.
1821 // Tests that calls that satisfy the original spec are successful.
1822 TEST(DeletingMockEarlyTest, Success1) {
1823 MockB* const b1 = new MockB;
1824 MockA* const a = new MockA;
1825 MockB* const b2 = new MockB;
1829 EXPECT_CALL(*b1, DoB(_))
1830 .WillOnce(Return(1));
1831 EXPECT_CALL(*a, Binary(_, _))
1833 .WillRepeatedly(Return(true));
1834 EXPECT_CALL(*b2, DoB(_))
1836 .WillRepeatedly(Return(2));
1839 EXPECT_EQ(1, b1->DoB(1));
1841 // a's pre-requisite has died.
1842 EXPECT_TRUE(a->Binary(0, 1));
1844 // a's successor has died.
1845 EXPECT_TRUE(a->Binary(1, 2));
1849 // Tests that calls that satisfy the original spec are successful.
1850 TEST(DeletingMockEarlyTest, Success2) {
1851 MockB* const b1 = new MockB;
1852 MockA* const a = new MockA;
1853 MockB* const b2 = new MockB;
1857 EXPECT_CALL(*b1, DoB(_))
1858 .WillOnce(Return(1));
1859 EXPECT_CALL(*a, Binary(_, _))
1860 .Times(AnyNumber());
1861 EXPECT_CALL(*b2, DoB(_))
1863 .WillRepeatedly(Return(2));
1866 delete a; // a is trivially satisfied.
1867 EXPECT_EQ(1, b1->DoB(1));
1868 EXPECT_EQ(2, b2->DoB(2));
1873 // Tests that it's OK to delete a mock object itself in its action.
1875 // Suppresses warning on unreferenced formal parameter in MSVC with
1878 # pragma warning(push)
1879 # pragma warning(disable:4100)
1882 ACTION_P(Delete, ptr) { delete ptr; }
1885 # pragma warning(pop)
1888 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1889 MockA* const a = new MockA;
1890 EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1891 a->DoA(42); // This will cause a to be deleted.
1894 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1895 MockA* const a = new MockA;
1896 EXPECT_CALL(*a, ReturnResult(_))
1897 .WillOnce(DoAll(Delete(a), Return(Result())));
1898 a->ReturnResult(42); // This will cause a to be deleted.
1901 // Tests that calls that violate the original spec yield failures.
1902 TEST(DeletingMockEarlyTest, Failure1) {
1903 MockB* const b1 = new MockB;
1904 MockA* const a = new MockA;
1905 MockB* const b2 = new MockB;
1909 EXPECT_CALL(*b1, DoB(_))
1910 .WillOnce(Return(1));
1911 EXPECT_CALL(*a, Binary(_, _))
1912 .Times(AnyNumber());
1913 EXPECT_CALL(*b2, DoB(_))
1915 .WillRepeatedly(Return(2));
1918 delete a; // a is trivially satisfied.
1919 EXPECT_NONFATAL_FAILURE({
1921 }, "Unexpected mock function call");
1922 EXPECT_EQ(1, b1->DoB(1));
1927 // Tests that calls that violate the original spec yield failures.
1928 TEST(DeletingMockEarlyTest, Failure2) {
1929 MockB* const b1 = new MockB;
1930 MockA* const a = new MockA;
1931 MockB* const b2 = new MockB;
1935 EXPECT_CALL(*b1, DoB(_));
1936 EXPECT_CALL(*a, Binary(_, _))
1937 .Times(AnyNumber());
1938 EXPECT_CALL(*b2, DoB(_))
1939 .Times(AnyNumber());
1942 EXPECT_NONFATAL_FAILURE(delete b1,
1943 "Actual: never called");
1944 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1945 "Unexpected mock function call");
1946 EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1947 "Unexpected mock function call");
1952 class EvenNumberCardinality : public CardinalityInterface {
1954 // Returns true iff call_count calls will satisfy this cardinality.
1955 virtual bool IsSatisfiedByCallCount(int call_count) const {
1956 return call_count % 2 == 0;
1959 // Returns true iff call_count calls will saturate this cardinality.
1960 virtual bool IsSaturatedByCallCount(int /* call_count */) const {
1964 // Describes self to an ostream.
1965 virtual void DescribeTo(::std::ostream* os) const {
1966 *os << "called even number of times";
1970 Cardinality EvenNumber() {
1971 return Cardinality(new EvenNumberCardinality);
1974 TEST(ExpectationBaseTest,
1975 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1976 MockA* a = new MockA;
1979 EXPECT_CALL(*a, DoA(1))
1980 .Times(EvenNumber())
1982 EXPECT_CALL(*a, DoA(2))
1985 EXPECT_CALL(*a, DoA(3))
1986 .Times(AnyNumber());
1990 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1991 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1994 // The following tests verify the message generated when a mock
1995 // function is called.
2000 inline void operator<<(::std::ostream& os, const Printable&) {
2004 struct Unprintable {
2005 Unprintable() : value(0) {}
2013 MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
2014 const Printable& x, Unprintable y));
2015 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
2018 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
2021 class VerboseFlagPreservingFixture : public testing::Test {
2023 VerboseFlagPreservingFixture()
2024 : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
2026 ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
2029 const std::string saved_verbose_flag_;
2031 GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
2034 #if GTEST_HAS_STREAM_REDIRECTION
2036 // Tests that an uninteresting mock function call on a naggy mock
2037 // generates a warning without the stack trace when
2038 // --gmock_verbose=warning is specified.
2039 TEST(FunctionCallMessageTest,
2040 UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
2041 GMOCK_FLAG(verbose) = kWarningVerbosity;
2044 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2045 const std::string output = GetCapturedStdout();
2046 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2047 EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
2050 // Tests that an uninteresting mock function call on a naggy mock
2051 // generates a warning containing the stack trace when
2052 // --gmock_verbose=info is specified.
2053 TEST(FunctionCallMessageTest,
2054 UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
2055 GMOCK_FLAG(verbose) = kInfoVerbosity;
2058 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2059 const std::string output = GetCapturedStdout();
2060 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2061 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
2065 // We check the stack trace content in dbg-mode only, as opt-mode
2066 // may inline the call we are interested in seeing.
2068 // Verifies that a void mock function's name appears in the stack
2070 EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
2072 // Verifies that a non-void mock function's name appears in the
2076 const std::string output2 = GetCapturedStdout();
2077 EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
2082 // Tests that an uninteresting mock function call on a naggy mock
2083 // causes the function arguments and return value to be printed.
2084 TEST(FunctionCallMessageTest,
2085 UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
2086 // A non-void mock function.
2090 const std::string output1 = GetCapturedStdout();
2091 EXPECT_PRED_FORMAT2(
2093 "Uninteresting mock function call - returning default value.\n"
2094 " Function call: DoB()\n"
2095 " Returns: 0\n", output1.c_str());
2096 // Makes sure the return value is printed.
2098 // A void mock function.
2101 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2102 const std::string output2 = GetCapturedStdout();
2103 EXPECT_THAT(output2.c_str(),
2105 "Uninteresting mock function call - returning directly\\.\n"
2106 " Function call: VoidMethod"
2107 "\\(false, 5, \"Hi\", NULL, @.+ "
2108 "Printable, 4-byte object <00-00 00-00>\\)"));
2109 // A void function has no return value to print.
2112 // Tests how the --gmock_verbose flag affects Google Mock's output.
2114 class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
2116 // Verifies that the given Google Mock output is correct. (When
2117 // should_print is true, the output should match the given regex and
2118 // contain the given function name in the stack trace. When it's
2119 // false, the output should be empty.)
2120 void VerifyOutput(const std::string& output, bool should_print,
2121 const std::string& expected_substring,
2122 const std::string& function_name) {
2124 EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2126 // We check the stack trace content in dbg-mode only, as opt-mode
2127 // may inline the call we are interested in seeing.
2128 EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2130 // Suppresses 'unused function parameter' warnings.
2131 static_cast<void>(function_name);
2134 EXPECT_STREQ("", output.c_str());
2138 // Tests how the flag affects expected calls.
2139 void TestExpectedCall(bool should_print) {
2141 EXPECT_CALL(a, DoA(5));
2142 EXPECT_CALL(a, Binary(_, 1))
2143 .WillOnce(Return(true));
2145 // A void-returning function.
2149 GetCapturedStdout(),
2151 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2152 " Function call: DoA(5)\n"
2156 // A non-void-returning function.
2160 GetCapturedStdout(),
2162 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2163 " Function call: Binary(2, 1)\n"
2169 // Tests how the flag affects uninteresting calls on a naggy mock.
2170 void TestUninterestingCallOnNaggyMock(bool should_print) {
2172 const std::string note =
2173 "NOTE: You can safely ignore the above warning unless this "
2174 "call should not happen. Do not suppress it by blindly adding "
2175 "an EXPECT_CALL() if you don't mean to enforce the call. "
2177 "https://github.com/google/googletest/blob/master/googlemock/docs/"
2179 "knowing-when-to-expect for details.";
2181 // A void-returning function.
2185 GetCapturedStdout(),
2187 "\nGMOCK WARNING:\n"
2188 "Uninteresting mock function call - returning directly.\n"
2189 " Function call: DoA(5)\n" +
2193 // A non-void-returning function.
2197 GetCapturedStdout(),
2199 "\nGMOCK WARNING:\n"
2200 "Uninteresting mock function call - returning default value.\n"
2201 " Function call: Binary(2, 1)\n"
2202 " Returns: false\n" +
2208 // Tests that --gmock_verbose=info causes both expected and
2209 // uninteresting calls to be reported.
2210 TEST_F(GMockVerboseFlagTest, Info) {
2211 GMOCK_FLAG(verbose) = kInfoVerbosity;
2212 TestExpectedCall(true);
2213 TestUninterestingCallOnNaggyMock(true);
2216 // Tests that --gmock_verbose=warning causes uninteresting calls to be
2218 TEST_F(GMockVerboseFlagTest, Warning) {
2219 GMOCK_FLAG(verbose) = kWarningVerbosity;
2220 TestExpectedCall(false);
2221 TestUninterestingCallOnNaggyMock(true);
2224 // Tests that --gmock_verbose=warning causes neither expected nor
2225 // uninteresting calls to be reported.
2226 TEST_F(GMockVerboseFlagTest, Error) {
2227 GMOCK_FLAG(verbose) = kErrorVerbosity;
2228 TestExpectedCall(false);
2229 TestUninterestingCallOnNaggyMock(false);
2232 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2233 // as --gmock_verbose=warning.
2234 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2235 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
2236 TestExpectedCall(false);
2237 TestUninterestingCallOnNaggyMock(true);
2240 #endif // GTEST_HAS_STREAM_REDIRECTION
2242 // A helper class that generates a failure when printed. We use it to
2243 // ensure that Google Mock doesn't print a value (even to an internal
2244 // buffer) when it is not supposed to do so.
2245 class PrintMeNot {};
2247 void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2248 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2249 << "printed even to an internal buffer.";
2252 class LogTestHelper {
2256 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2259 GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
2262 class GMockLogTest : public VerboseFlagPreservingFixture {
2264 LogTestHelper helper_;
2267 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2268 GMOCK_FLAG(verbose) = kWarningVerbosity;
2269 EXPECT_CALL(helper_, Foo(_))
2270 .WillOnce(Return(PrintMeNot()));
2271 helper_.Foo(PrintMeNot()); // This is an expected call.
2274 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2275 GMOCK_FLAG(verbose) = kErrorVerbosity;
2276 EXPECT_CALL(helper_, Foo(_))
2277 .WillOnce(Return(PrintMeNot()));
2278 helper_.Foo(PrintMeNot()); // This is an expected call.
2281 TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2282 GMOCK_FLAG(verbose) = kErrorVerbosity;
2283 ON_CALL(helper_, Foo(_))
2284 .WillByDefault(Return(PrintMeNot()));
2285 helper_.Foo(PrintMeNot()); // This should generate a warning.
2288 // Tests Mock::AllowLeak().
2290 TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2291 MockA* a = new MockA;
2295 TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2296 MockA* a = new MockA;
2298 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2302 TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2303 MockA* a = new MockA;
2304 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2308 TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2309 MockA* a = new MockA;
2311 EXPECT_CALL(*a, DoA(_));
2315 TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2316 MockA* a = new MockA;
2317 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2321 TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2322 MockA* a = new MockA;
2323 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2324 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2328 // Tests that we can verify and clear a mock object's expectations
2329 // when none of its methods has expectations.
2330 TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2332 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2334 // There should be no expectations on the methods now, so we can
2335 // freely call them.
2336 EXPECT_EQ(0, b.DoB());
2337 EXPECT_EQ(0, b.DoB(1));
2340 // Tests that we can verify and clear a mock object's expectations
2341 // when some, but not all, of its methods have expectations *and* the
2342 // verification succeeds.
2343 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2345 EXPECT_CALL(b, DoB())
2346 .WillOnce(Return(1));
2348 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2350 // There should be no expectations on the methods now, so we can
2351 // freely call them.
2352 EXPECT_EQ(0, b.DoB());
2353 EXPECT_EQ(0, b.DoB(1));
2356 // Tests that we can verify and clear a mock object's expectations
2357 // when some, but not all, of its methods have expectations *and* the
2358 // verification fails.
2359 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2361 EXPECT_CALL(b, DoB())
2362 .WillOnce(Return(1));
2364 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2365 "Actual: never called");
2366 ASSERT_FALSE(result);
2368 // There should be no expectations on the methods now, so we can
2369 // freely call them.
2370 EXPECT_EQ(0, b.DoB());
2371 EXPECT_EQ(0, b.DoB(1));
2374 // Tests that we can verify and clear a mock object's expectations
2375 // when all of its methods have expectations.
2376 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2378 EXPECT_CALL(b, DoB())
2379 .WillOnce(Return(1));
2380 EXPECT_CALL(b, DoB(_))
2381 .WillOnce(Return(2));
2384 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2386 // There should be no expectations on the methods now, so we can
2387 // freely call them.
2388 EXPECT_EQ(0, b.DoB());
2389 EXPECT_EQ(0, b.DoB(1));
2392 // Tests that we can verify and clear a mock object's expectations
2393 // when a method has more than one expectation.
2394 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2396 EXPECT_CALL(b, DoB(0))
2397 .WillOnce(Return(1));
2398 EXPECT_CALL(b, DoB(_))
2399 .WillOnce(Return(2));
2402 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2403 "Actual: never called");
2404 ASSERT_FALSE(result);
2406 // There should be no expectations on the methods now, so we can
2407 // freely call them.
2408 EXPECT_EQ(0, b.DoB());
2409 EXPECT_EQ(0, b.DoB(1));
2412 // Tests that we can call VerifyAndClearExpectations() on the same
2413 // mock object multiple times.
2414 TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2416 EXPECT_CALL(b, DoB());
2418 Mock::VerifyAndClearExpectations(&b);
2420 EXPECT_CALL(b, DoB(_))
2421 .WillOnce(Return(1));
2423 Mock::VerifyAndClearExpectations(&b);
2424 Mock::VerifyAndClearExpectations(&b);
2426 // There should be no expectations on the methods now, so we can
2427 // freely call them.
2428 EXPECT_EQ(0, b.DoB());
2429 EXPECT_EQ(0, b.DoB(1));
2432 // Tests that we can clear a mock object's default actions when none
2433 // of its methods has default actions.
2434 TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2436 // If this crashes or generates a failure, the test will catch it.
2437 Mock::VerifyAndClear(&b);
2438 EXPECT_EQ(0, b.DoB());
2441 // Tests that we can clear a mock object's default actions when some,
2442 // but not all of its methods have default actions.
2443 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2446 .WillByDefault(Return(1));
2448 Mock::VerifyAndClear(&b);
2450 // Verifies that the default action of int DoB() was removed.
2451 EXPECT_EQ(0, b.DoB());
2454 // Tests that we can clear a mock object's default actions when all of
2455 // its methods have default actions.
2456 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2459 .WillByDefault(Return(1));
2461 .WillByDefault(Return(2));
2463 Mock::VerifyAndClear(&b);
2465 // Verifies that the default action of int DoB() was removed.
2466 EXPECT_EQ(0, b.DoB());
2468 // Verifies that the default action of int DoB(int) was removed.
2469 EXPECT_EQ(0, b.DoB(0));
2472 // Tests that we can clear a mock object's default actions when a
2473 // method has more than one ON_CALL() set on it.
2474 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2477 .WillByDefault(Return(1));
2479 .WillByDefault(Return(2));
2481 Mock::VerifyAndClear(&b);
2483 // Verifies that the default actions (there are two) of int DoB(int)
2485 EXPECT_EQ(0, b.DoB(0));
2486 EXPECT_EQ(0, b.DoB(1));
2489 // Tests that we can call VerifyAndClear() on a mock object multiple
2491 TEST(VerifyAndClearTest, CanCallManyTimes) {
2494 .WillByDefault(Return(1));
2495 Mock::VerifyAndClear(&b);
2496 Mock::VerifyAndClear(&b);
2499 .WillByDefault(Return(1));
2500 Mock::VerifyAndClear(&b);
2502 EXPECT_EQ(0, b.DoB());
2503 EXPECT_EQ(0, b.DoB(1));
2506 // Tests that VerifyAndClear() works when the verification succeeds.
2507 TEST(VerifyAndClearTest, Success) {
2510 .WillByDefault(Return(1));
2511 EXPECT_CALL(b, DoB(1))
2512 .WillOnce(Return(2));
2516 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2518 // There should be no expectations on the methods now, so we can
2519 // freely call them.
2520 EXPECT_EQ(0, b.DoB());
2521 EXPECT_EQ(0, b.DoB(1));
2524 // Tests that VerifyAndClear() works when the verification fails.
2525 TEST(VerifyAndClearTest, Failure) {
2528 .WillByDefault(Return(1));
2529 EXPECT_CALL(b, DoB())
2530 .WillOnce(Return(2));
2534 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2535 "Actual: never called");
2536 ASSERT_FALSE(result);
2538 // There should be no expectations on the methods now, so we can
2539 // freely call them.
2540 EXPECT_EQ(0, b.DoB());
2541 EXPECT_EQ(0, b.DoB(1));
2544 // Tests that VerifyAndClear() works when the default actions and
2545 // expectations are set on a const mock object.
2546 TEST(VerifyAndClearTest, Const) {
2548 ON_CALL(Const(b), DoB())
2549 .WillByDefault(Return(1));
2551 EXPECT_CALL(Const(b), DoB())
2552 .WillOnce(DoDefault())
2553 .WillOnce(Return(2));
2557 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2559 // There should be no expectations on the methods now, so we can
2560 // freely call them.
2561 EXPECT_EQ(0, b.DoB());
2562 EXPECT_EQ(0, b.DoB(1));
2565 // Tests that we can set default actions and expectations on a mock
2566 // object after VerifyAndClear() has been called on it.
2567 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2570 .WillByDefault(Return(1));
2571 EXPECT_CALL(b, DoB(_))
2572 .WillOnce(Return(2));
2575 Mock::VerifyAndClear(&b);
2577 EXPECT_CALL(b, DoB())
2578 .WillOnce(Return(3));
2580 .WillByDefault(Return(4));
2582 EXPECT_EQ(3, b.DoB());
2583 EXPECT_EQ(4, b.DoB(1));
2586 // Tests that calling VerifyAndClear() on one mock object does not
2587 // affect other mock objects (either of the same type or not).
2588 TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2593 ON_CALL(a, Binary(_, _))
2594 .WillByDefault(Return(true));
2595 EXPECT_CALL(a, Binary(_, _))
2596 .WillOnce(DoDefault())
2597 .WillOnce(Return(false));
2600 .WillByDefault(Return(1));
2601 EXPECT_CALL(b1, DoB(_))
2602 .WillOnce(Return(2));
2605 .WillByDefault(Return(3));
2606 EXPECT_CALL(b2, DoB(_));
2609 Mock::VerifyAndClear(&b2);
2611 // Verifies that the default actions and expectations of a and b1
2612 // are still in effect.
2613 EXPECT_TRUE(a.Binary(0, 0));
2614 EXPECT_FALSE(a.Binary(0, 0));
2616 EXPECT_EQ(1, b1.DoB());
2617 EXPECT_EQ(2, b1.DoB(0));
2620 TEST(VerifyAndClearTest,
2621 DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2622 linked_ptr<MockA> a(new MockA);
2623 ReferenceHoldingMock test_mock;
2625 // EXPECT_CALL stores a reference to a inside test_mock.
2626 EXPECT_CALL(test_mock, AcceptReference(_))
2627 .WillRepeatedly(SetArgPointee<0>(a));
2629 // Throw away the reference to the mock that we have in a. After this, the
2630 // only reference to it is stored by test_mock.
2633 // When test_mock goes out of scope, it destroys the last remaining reference
2634 // to the mock object originally pointed to by a. This will cause the MockA
2635 // destructor to be called from inside the ReferenceHoldingMock destructor.
2636 // The state of all mocks is protected by a single global lock, but there
2637 // should be no deadlock.
2640 TEST(VerifyAndClearTest,
2641 DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2642 linked_ptr<MockA> a(new MockA);
2643 ReferenceHoldingMock test_mock;
2645 // ON_CALL stores a reference to a inside test_mock.
2646 ON_CALL(test_mock, AcceptReference(_))
2647 .WillByDefault(SetArgPointee<0>(a));
2649 // Throw away the reference to the mock that we have in a. After this, the
2650 // only reference to it is stored by test_mock.
2653 // When test_mock goes out of scope, it destroys the last remaining reference
2654 // to the mock object originally pointed to by a. This will cause the MockA
2655 // destructor to be called from inside the ReferenceHoldingMock destructor.
2656 // The state of all mocks is protected by a single global lock, but there
2657 // should be no deadlock.
2660 // Tests that a mock function's action can call a mock function
2661 // (either the same function or a different one) either as an explicit
2662 // action or as a default action without causing a dead lock. It
2663 // verifies that the action is not performed inside the critical
2665 TEST(SynchronizationTest, CanCallMockMethodInAction) {
2669 .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
2670 &MockC::NonVoidMethod)));
2671 EXPECT_CALL(a, DoA(1));
2672 EXPECT_CALL(a, DoA(1))
2673 .WillOnce(Invoke(&a, &MockA::DoA))
2674 .RetiresOnSaturation();
2675 EXPECT_CALL(c, NonVoidMethod());
2678 // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2679 // which will in turn match the first EXPECT_CALL() and trigger a call to
2680 // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2681 // EXPECT_CALL() did not specify an action.
2684 TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
2687 ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
2688 int do_a_47_arg0 = 0;
2689 ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
2692 EXPECT_THAT(do_a_arg0, 17);
2693 EXPECT_THAT(do_a_47_arg0, 0);
2695 EXPECT_THAT(do_a_arg0, 17);
2696 EXPECT_THAT(do_a_47_arg0, 47);
2698 ON_CALL(a, Binary).WillByDefault(Return(true));
2699 ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
2700 EXPECT_THAT(a.Binary(14, 17), true);
2701 EXPECT_THAT(a.Binary(17, 14), false);
2704 TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
2706 ON_CALL(b, DoB()).WillByDefault(Return(9));
2707 ON_CALL(b, DoB(5)).WillByDefault(Return(11));
2709 EXPECT_THAT(b.DoB(), 9);
2710 EXPECT_THAT(b.DoB(1), 0); // default value
2711 EXPECT_THAT(b.DoB(5), 11);
2714 struct MockWithConstMethods {
2716 MOCK_CONST_METHOD1(Foo, int(int));
2717 MOCK_CONST_METHOD2(Bar, int(int, const char*));
2720 TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
2721 MockWithConstMethods mock;
2722 ON_CALL(mock, Foo).WillByDefault(Return(7));
2723 ON_CALL(mock, Bar).WillByDefault(Return(33));
2725 EXPECT_THAT(mock.Foo(17), 7);
2726 EXPECT_THAT(mock.Bar(27, "purple"), 33);
2729 class MockConstOverload {
2731 MOCK_METHOD1(Overloaded, int(int));
2732 MOCK_CONST_METHOD1(Overloaded, int(int));
2735 TEST(ParameterlessExpectationsTest,
2736 CanSetExpectationsForConstOverloadedMethods) {
2737 MockConstOverload mock;
2738 ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
2739 ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
2740 ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
2741 ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
2743 EXPECT_THAT(mock.Overloaded(1), 7);
2744 EXPECT_THAT(mock.Overloaded(5), 9);
2745 EXPECT_THAT(mock.Overloaded(7), 7);
2747 const MockConstOverload& const_mock = mock;
2748 EXPECT_THAT(const_mock.Overloaded(1), 0);
2749 EXPECT_THAT(const_mock.Overloaded(5), 11);
2750 EXPECT_THAT(const_mock.Overloaded(7), 13);
2755 // Allows the user to define their own main and then invoke gmock_main
2756 // from it. This might be necessary on some platforms which require
2757 // specific setup and teardown.
2758 #if GMOCK_RENAME_MAIN
2759 int gmock_main(int argc, char **argv) {
2761 int main(int argc, char **argv) {
2762 #endif // GMOCK_RENAME_MAIN
2763 testing::InitGoogleMock(&argc, argv);
2764 // Ensures that the tests pass no matter what value of
2765 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2766 testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2767 testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2769 return RUN_ALL_TESTS();