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.
30 // Author: wan@google.com (Zhanyong Wan)
32 // Google Mock - a framework for writing C++ mock classes.
34 // This file tests the spec builder syntax.
36 #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;
72 using testing::ContainsRegex;
75 using testing::DoDefault;
77 using testing::Expectation;
78 using testing::ExpectationSet;
79 using testing::GMOCK_FLAG(verbose);
81 using testing::InSequence;
82 using testing::Invoke;
83 using testing::InvokeWithoutArgs;
84 using testing::IsNotSubstring;
85 using testing::IsSubstring;
87 using testing::Message;
89 using testing::NaggyMock;
91 using testing::Return;
92 using testing::Sequence;
93 using testing::SetArgPointee;
94 using testing::internal::ExpectationTester;
95 using testing::internal::FormatFileLocation;
96 using testing::internal::kErrorVerbosity;
97 using testing::internal::kInfoVerbosity;
98 using testing::internal::kWarningVerbosity;
99 using testing::internal::linked_ptr;
100 using testing::internal::string;
102 #if GTEST_HAS_STREAM_REDIRECTION
103 using testing::HasSubstr;
104 using testing::internal::CaptureStdout;
105 using testing::internal::GetCapturedStdout;
110 class MockIncomplete {
112 // This line verifies that a mock method can take a by-reference
113 // argument of an incomplete type.
114 MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
117 // Tells Google Mock how to print a value of type Incomplete.
118 void PrintTo(const Incomplete& x, ::std::ostream* os);
120 TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
121 // Even though this mock class contains a mock method that takes
122 // by-reference an argument whose type is incomplete, we can still
123 // use the mock, as long as Google Mock knows how to print the
125 MockIncomplete incomplete;
126 EXPECT_CALL(incomplete, ByRefFunc(_))
130 // The definition of the printer for the argument type doesn't have to
131 // be visible where the mock is used.
132 void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
138 // A type that's not default constructible.
139 class NonDefaultConstructible {
141 explicit NonDefaultConstructible(int /* dummy */) {}
148 MOCK_METHOD1(DoA, void(int n));
149 MOCK_METHOD1(ReturnResult, Result(int n));
150 MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
151 MOCK_METHOD2(Binary, bool(int x, int y));
152 MOCK_METHOD2(ReturnInt, int(int x, int y));
155 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA);
162 MOCK_CONST_METHOD0(DoB, int()); // NOLINT
163 MOCK_METHOD1(DoB, int(int n)); // NOLINT
166 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB);
169 class ReferenceHoldingMock {
171 ReferenceHoldingMock() {}
173 MOCK_METHOD1(AcceptReference, void(linked_ptr<MockA>*));
176 GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock);
179 // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
180 // redefining a mock method name. This could happen, for example, when
181 // the tested code #includes Win32 API headers which define many APIs
182 // as macros, e.g. #define TextOut TextOutW.
184 #define Method MethodW
189 virtual int Method() = 0;
191 class MockCC : public CC {
195 MOCK_METHOD0(Method, int());
198 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC);
201 // Tests that a method with expanded name compiles.
202 TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
204 ON_CALL(cc, Method());
207 // Tests that the method with expanded name not only compiles but runs
208 // and returns a correct value, too.
209 TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
211 ON_CALL(cc, Method()).WillByDefault(Return(42));
212 EXPECT_EQ(42, cc.Method());
215 // Tests that a method with expanded name compiles.
216 TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
218 EXPECT_CALL(cc, Method());
222 // Tests that it works, too.
223 TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
225 EXPECT_CALL(cc, Method()).WillOnce(Return(42));
226 EXPECT_EQ(42, cc.Method());
229 #undef Method // Done with macro redefinition tests.
231 // Tests that ON_CALL evaluates its arguments exactly once as promised
233 TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
237 ON_CALL(*pa++, DoA(_));
238 EXPECT_EQ(&a + 1, pa);
241 TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
245 ON_CALL(a, DoA(n++));
249 // Tests that the syntax of ON_CALL() is enforced at run time.
251 TEST(OnCallSyntaxTest, WithIsOptional) {
255 .WillByDefault(Return());
258 .WillByDefault(Return());
261 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
264 EXPECT_NONFATAL_FAILURE({ // NOLINT
265 ON_CALL(a, ReturnResult(_))
268 .WillByDefault(Return(Result()));
269 }, ".With() cannot appear more than once in an ON_CALL()");
272 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
275 EXPECT_DEATH_IF_SUPPORTED({
281 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
284 EXPECT_NONFATAL_FAILURE({ // NOLINT
286 .WillByDefault(Return())
287 .WillByDefault(Return());
288 }, ".WillByDefault() must appear exactly once in an ON_CALL()");
291 // Tests that EXPECT_CALL evaluates its arguments exactly once as
292 // promised by Google Mock.
293 TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
297 EXPECT_CALL(*pa++, DoA(_));
299 EXPECT_EQ(&a + 1, pa);
302 TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
306 EXPECT_CALL(a, DoA(n++));
311 // Tests that the syntax of EXPECT_CALL() is enforced at run time.
313 TEST(ExpectCallSyntaxTest, WithIsOptional) {
316 EXPECT_CALL(a, DoA(5))
318 EXPECT_CALL(a, DoA(6))
323 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
326 EXPECT_NONFATAL_FAILURE({ // NOLINT
327 EXPECT_CALL(a, DoA(6))
330 }, ".With() cannot appear more than once in an EXPECT_CALL()");
335 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
338 EXPECT_NONFATAL_FAILURE({ // NOLINT
339 EXPECT_CALL(a, DoA(1))
342 }, ".With() must be the first clause in an EXPECT_CALL()");
346 EXPECT_NONFATAL_FAILURE({ // NOLINT
347 EXPECT_CALL(a, DoA(2))
350 }, ".With() must be the first clause in an EXPECT_CALL()");
355 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
358 EXPECT_CALL(a, DoA(1))
361 EXPECT_CALL(a, DoA(2))
363 .WillRepeatedly(Return());
370 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
373 EXPECT_NONFATAL_FAILURE({ // NOLINT
374 EXPECT_CALL(a, DoA(1))
377 }, ".Times() cannot appear more than once in an EXPECT_CALL()");
383 TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
387 EXPECT_NONFATAL_FAILURE({ // NOLINT
388 EXPECT_CALL(a, DoA(1))
391 }, ".Times() cannot appear after ");
396 TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
400 EXPECT_CALL(a, DoA(1));
401 EXPECT_CALL(a, DoA(2))
408 TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
412 EXPECT_CALL(a, DoA(1))
419 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
423 Expectation e = EXPECT_CALL(a, DoA(1))
425 EXPECT_NONFATAL_FAILURE({ // NOLINT
426 EXPECT_CALL(a, DoA(2))
429 }, ".InSequence() cannot appear after ");
434 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
438 EXPECT_NONFATAL_FAILURE({ // NOLINT
439 EXPECT_CALL(a, DoA(1))
442 }, ".InSequence() cannot appear after ");
447 TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
450 Expectation e = EXPECT_CALL(a, DoA(1));
451 EXPECT_NONFATAL_FAILURE({
452 EXPECT_CALL(a, DoA(2))
455 }, ".After() cannot appear after ");
461 TEST(ExpectCallSyntaxTest, WillIsOptional) {
464 EXPECT_CALL(a, DoA(1));
465 EXPECT_CALL(a, DoA(2))
472 TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
475 EXPECT_CALL(a, DoA(1))
482 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
485 EXPECT_NONFATAL_FAILURE({ // NOLINT
486 EXPECT_CALL(a, DoA(1))
487 .WillRepeatedly(Return())
489 }, ".WillOnce() cannot appear after ");
494 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
497 EXPECT_CALL(a, DoA(1))
499 EXPECT_CALL(a, DoA(2))
501 .WillRepeatedly(Return());
508 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
511 EXPECT_NONFATAL_FAILURE({ // NOLINT
512 EXPECT_CALL(a, DoA(1))
513 .WillRepeatedly(Return())
514 .WillRepeatedly(Return());
515 }, ".WillRepeatedly() cannot appear more than once in an "
519 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
522 EXPECT_NONFATAL_FAILURE({ // NOLINT
523 EXPECT_CALL(a, DoA(1))
524 .RetiresOnSaturation()
525 .WillRepeatedly(Return());
526 }, ".WillRepeatedly() cannot appear after ");
529 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
532 EXPECT_CALL(a, DoA(1));
533 EXPECT_CALL(a, DoA(1))
534 .RetiresOnSaturation();
540 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
543 EXPECT_NONFATAL_FAILURE({ // NOLINT
544 EXPECT_CALL(a, DoA(1))
545 .RetiresOnSaturation()
546 .RetiresOnSaturation();
547 }, ".RetiresOnSaturation() cannot appear more than once");
552 TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
555 EXPECT_CALL(a, DoA(1));
558 EXPECT_NONFATAL_FAILURE({ // NOLINT
560 EXPECT_CALL(a, DoA(1));
561 }, "to be called once");
562 EXPECT_NONFATAL_FAILURE({ // NOLINT
564 EXPECT_CALL(a, DoA(1));
567 }, "to be called once");
570 #if GTEST_HAS_STREAM_REDIRECTION
572 // Tests that Google Mock doesn't print a warning when the number of
573 // WillOnce() is adequate.
574 TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
579 // It's always fine to omit WillOnce() entirely.
580 EXPECT_CALL(b, DoB())
582 EXPECT_CALL(b, DoB(1))
584 EXPECT_CALL(b, DoB(2))
586 .WillRepeatedly(Return(1));
588 // It's fine for the number of WillOnce()s to equal the upper bound.
589 EXPECT_CALL(b, DoB(3))
590 .Times(Between(1, 2))
592 .WillOnce(Return(2));
594 // It's fine for the number of WillOnce()s to be smaller than the
595 // upper bound when there is a WillRepeatedly().
596 EXPECT_CALL(b, DoB(4))
599 .WillRepeatedly(Return(2));
601 // Satisfies the above expectations.
605 EXPECT_STREQ("", GetCapturedStdout().c_str());
608 // Tests that Google Mock warns on having too many actions in an
609 // expectation compared to its cardinality.
610 TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
615 // Warns when the number of WillOnce()s is larger than the upper bound.
616 EXPECT_CALL(b, DoB())
618 .WillOnce(Return(1)); // #1
619 EXPECT_CALL(b, DoB())
622 .WillOnce(Return(2)); // #2
623 EXPECT_CALL(b, DoB(1))
627 .RetiresOnSaturation(); // #3
629 // Warns when the number of WillOnce()s equals the upper bound and
630 // there is a WillRepeatedly().
631 EXPECT_CALL(b, DoB())
633 .WillRepeatedly(Return(1)); // #4
634 EXPECT_CALL(b, DoB(2))
637 .WillRepeatedly(Return(2)); // #5
639 // Satisfies the above expectations.
643 const std::string output = GetCapturedStdout();
646 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
647 "Expected to be never called, but has 1 WillOnce().",
651 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
652 "Expected to be called at most once, "
653 "but has 2 WillOnce()s.",
657 "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
658 "Expected to be called once, but has 2 WillOnce()s.",
662 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
663 "Expected to be never called, but has 0 WillOnce()s "
664 "and a WillRepeatedly().",
668 "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
669 "Expected to be called once, but has 1 WillOnce() "
670 "and a WillRepeatedly().",
674 // Tests that Google Mock warns on having too few actions in an
675 // expectation compared to its cardinality.
676 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
679 EXPECT_CALL(b, DoB())
680 .Times(Between(2, 3))
681 .WillOnce(Return(1));
685 const std::string output = GetCapturedStdout();
688 "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
689 "Expected to be called between 2 and 3 times, "
690 "but has only 1 WillOnce().",
695 #endif // GTEST_HAS_STREAM_REDIRECTION
697 // Tests the semantics of ON_CALL().
699 // Tests that the built-in default action is taken when no ON_CALL()
701 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
703 EXPECT_CALL(b, DoB());
705 EXPECT_EQ(0, b.DoB());
708 // Tests that the built-in default action is taken when no ON_CALL()
709 // matches the invocation.
710 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
713 .WillByDefault(Return(1));
714 EXPECT_CALL(b, DoB(_));
716 EXPECT_EQ(0, b.DoB(2));
719 // Tests that the last matching ON_CALL() action is taken.
720 TEST(OnCallTest, PicksLastMatchingOnCall) {
723 .WillByDefault(Return(3));
725 .WillByDefault(Return(2));
727 .WillByDefault(Return(1));
728 EXPECT_CALL(b, DoB(_));
730 EXPECT_EQ(2, b.DoB(2));
733 // Tests the semantics of EXPECT_CALL().
735 // Tests that any call is allowed when no EXPECT_CALL() is specified.
736 TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
738 EXPECT_CALL(b, DoB());
739 // There is no expectation on DoB(int).
743 // DoB(int) can be called any number of times.
748 // Tests that the last matching EXPECT_CALL() fires.
749 TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
751 EXPECT_CALL(b, DoB(_))
752 .WillRepeatedly(Return(2));
753 EXPECT_CALL(b, DoB(1))
754 .WillRepeatedly(Return(1));
756 EXPECT_EQ(1, b.DoB(1));
759 // Tests lower-bound violation.
760 TEST(ExpectCallTest, CatchesTooFewCalls) {
761 EXPECT_NONFATAL_FAILURE({ // NOLINT
763 EXPECT_CALL(b, DoB(5))
767 }, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
768 " Expected: to be called at least twice\n"
769 " Actual: called once - unsatisfied and active");
772 // Tests that the cardinality can be inferred when no Times(...) is
774 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
777 EXPECT_CALL(b, DoB())
779 .WillOnce(Return(2));
781 EXPECT_EQ(1, b.DoB());
782 EXPECT_EQ(2, b.DoB());
785 EXPECT_NONFATAL_FAILURE({ // NOLINT
787 EXPECT_CALL(b, DoB())
789 .WillOnce(Return(2));
791 EXPECT_EQ(1, b.DoB());
792 }, "to be called twice");
796 EXPECT_CALL(b, DoB())
798 .WillOnce(Return(2));
800 EXPECT_EQ(1, b.DoB());
801 EXPECT_EQ(2, b.DoB());
802 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
806 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
809 EXPECT_CALL(b, DoB())
811 .WillRepeatedly(Return(2));
813 EXPECT_EQ(1, b.DoB());
818 EXPECT_CALL(b, DoB())
820 .WillRepeatedly(Return(2));
822 EXPECT_EQ(1, b.DoB());
823 EXPECT_EQ(2, b.DoB());
824 EXPECT_EQ(2, b.DoB());
827 EXPECT_NONFATAL_FAILURE({ // NOLINT
829 EXPECT_CALL(b, DoB())
831 .WillRepeatedly(Return(2));
832 }, "to be called at least once");
835 // Tests that the n-th action is taken for the n-th matching
837 TEST(ExpectCallTest, NthMatchTakesNthAction) {
839 EXPECT_CALL(b, DoB())
842 .WillOnce(Return(3));
844 EXPECT_EQ(1, b.DoB());
845 EXPECT_EQ(2, b.DoB());
846 EXPECT_EQ(3, b.DoB());
849 // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
850 // list is exhausted.
851 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
853 EXPECT_CALL(b, DoB())
855 .WillRepeatedly(Return(2));
857 EXPECT_EQ(1, b.DoB());
858 EXPECT_EQ(2, b.DoB());
859 EXPECT_EQ(2, b.DoB());
862 #if GTEST_HAS_STREAM_REDIRECTION
864 // Tests that the default action is taken when the WillOnce(...) list is
865 // exhausted and there is no WillRepeatedly().
866 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
868 EXPECT_CALL(b, DoB(_))
870 EXPECT_CALL(b, DoB())
873 .WillOnce(Return(2));
876 EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
877 // expectation has no action clause at all.
878 EXPECT_EQ(1, b.DoB());
879 EXPECT_EQ(2, b.DoB());
880 const std::string output1 = GetCapturedStdout();
881 EXPECT_STREQ("", output1.c_str());
884 EXPECT_EQ(0, b.DoB());
885 EXPECT_EQ(0, b.DoB());
886 const std::string output2 = GetCapturedStdout();
887 EXPECT_THAT(output2.c_str(),
888 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
889 "Called 3 times, but only 2 WillOnce()s are specified"
890 " - returning default value."));
891 EXPECT_THAT(output2.c_str(),
892 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
893 "Called 4 times, but only 2 WillOnce()s are specified"
894 " - returning default value."));
897 TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
899 std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
900 EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
902 EXPECT_EQ(1, b.DoB());
905 EXPECT_EQ(0, b.DoB());
906 const std::string output = GetCapturedStdout();
907 // The warning message should contain the call location.
908 EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
911 TEST(FunctionMockerMessageTest,
912 ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
913 std::string on_call_location;
917 on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
918 ON_CALL(b, DoB(_)).WillByDefault(Return(0));
921 EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
924 #endif // GTEST_HAS_STREAM_REDIRECTION
926 // Tests that an uninteresting call performs the default action.
927 TEST(UninterestingCallTest, DoesDefaultAction) {
928 // When there is an ON_CALL() statement, the action specified by it
931 ON_CALL(a, Binary(_, _))
932 .WillByDefault(Return(true));
933 EXPECT_TRUE(a.Binary(1, 2));
935 // When there is no ON_CALL(), the default value for the return type
936 // should be returned.
938 EXPECT_EQ(0, b.DoB());
941 // Tests that an unexpected call performs the default action.
942 TEST(UnexpectedCallTest, DoesDefaultAction) {
943 // When there is an ON_CALL() statement, the action specified by it
946 ON_CALL(a, Binary(_, _))
947 .WillByDefault(Return(true));
948 EXPECT_CALL(a, Binary(0, 0));
951 EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
952 "Unexpected mock function call");
955 // When there is no ON_CALL(), the default value for the return type
956 // should be returned.
958 EXPECT_CALL(b, DoB(0))
961 EXPECT_NONFATAL_FAILURE(n = b.DoB(1),
962 "Unexpected mock function call");
966 // Tests that when an unexpected void function generates the right
968 TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
969 // First, tests the message when there is only one EXPECT_CALL().
971 EXPECT_CALL(a1, DoA(1));
973 // Ideally we should match the failure message against a regex, but
974 // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
975 // multiple sub-strings instead.
976 EXPECT_NONFATAL_FAILURE(
978 "Unexpected mock function call - returning directly.\n"
979 " Function call: DoA(9)\n"
980 "Google Mock tried the following 1 expectation, but it didn't match:");
981 EXPECT_NONFATAL_FAILURE(
983 " Expected arg #0: is equal to 1\n"
985 " Expected: to be called once\n"
986 " Actual: called once - saturated and active");
988 // Next, tests the message when there are more than one EXPECT_CALL().
990 EXPECT_CALL(a2, DoA(1));
991 EXPECT_CALL(a2, DoA(3));
993 EXPECT_NONFATAL_FAILURE(
995 "Unexpected mock function call - returning directly.\n"
996 " Function call: DoA(2)\n"
997 "Google Mock tried the following 2 expectations, but none matched:");
998 EXPECT_NONFATAL_FAILURE(
1000 "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1001 " Expected arg #0: is equal to 1\n"
1003 " Expected: to be called once\n"
1004 " Actual: called once - saturated and active");
1005 EXPECT_NONFATAL_FAILURE(
1007 "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1008 " Expected arg #0: is equal to 3\n"
1010 " Expected: to be called once\n"
1011 " Actual: never called - unsatisfied and active");
1015 // Tests that an unexpected non-void function generates the right
1017 TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1019 EXPECT_CALL(b1, DoB(1));
1021 EXPECT_NONFATAL_FAILURE(
1023 "Unexpected mock function call - returning default value.\n"
1024 " Function call: DoB(2)\n"
1026 "Google Mock tried the following 1 expectation, but it didn't match:");
1027 EXPECT_NONFATAL_FAILURE(
1029 " Expected arg #0: is equal to 1\n"
1031 " Expected: to be called once\n"
1032 " Actual: called once - saturated and active");
1035 // Tests that Google Mock explains that an retired expectation doesn't
1037 TEST(UnexpectedCallTest, RetiredExpectation) {
1039 EXPECT_CALL(b, DoB(1))
1040 .RetiresOnSaturation();
1043 EXPECT_NONFATAL_FAILURE(
1045 " Expected: the expectation is active\n"
1046 " Actual: it is retired");
1049 // Tests that Google Mock explains that an expectation that doesn't
1050 // match the arguments doesn't match the call.
1051 TEST(UnexpectedCallTest, UnmatchedArguments) {
1053 EXPECT_CALL(b, DoB(1));
1055 EXPECT_NONFATAL_FAILURE(
1057 " Expected arg #0: is equal to 1\n"
1062 // Tests that Google Mock explains that an expectation with
1063 // unsatisfied pre-requisites doesn't match the call.
1064 TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1067 EXPECT_CALL(b, DoB(1))
1069 EXPECT_CALL(b, DoB(2))
1072 EXPECT_CALL(b, DoB(3))
1074 EXPECT_CALL(b, DoB(4))
1075 .InSequence(s1, s2);
1077 ::testing::TestPartResultArray failures;
1079 ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1081 // Now 'failures' contains the Google Test failures generated by
1082 // the above statement.
1085 // There should be one non-fatal failure.
1086 ASSERT_EQ(1, failures.size());
1087 const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
1088 EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1090 // Verifies that the failure message contains the two unsatisfied
1091 // pre-requisites but not the satisfied one.
1093 EXPECT_THAT(r.message(), ContainsRegex(
1094 // PCRE has trouble using (.|\n) to match any character, but
1095 // supports the (?s) prefix for using . to match any character.
1096 "(?s)the following immediate pre-requisites are not satisfied:\n"
1097 ".*: pre-requisite #0\n"
1098 ".*: pre-requisite #1"));
1099 #elif GTEST_USES_POSIX_RE
1100 EXPECT_THAT(r.message(), ContainsRegex(
1101 // POSIX RE doesn't understand the (?s) prefix, but has no trouble
1103 "the following immediate pre-requisites are not satisfied:\n"
1104 "(.|\n)*: pre-requisite #0\n"
1105 "(.|\n)*: pre-requisite #1"));
1107 // We can only use Google Test's own simple regex.
1108 EXPECT_THAT(r.message(), ContainsRegex(
1109 "the following immediate pre-requisites are not satisfied:"));
1110 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1111 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1112 #endif // GTEST_USES_PCRE
1119 TEST(UndefinedReturnValueTest,
1120 ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1122 // TODO(wan@google.com): We should really verify the output message,
1123 // but we cannot yet due to that EXPECT_DEATH only captures stderr
1124 // while Google Mock logs to stdout.
1125 #if GTEST_HAS_EXCEPTIONS
1126 EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1128 EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1132 // Tests that an excessive call (one whose arguments match the
1133 // matchers but is called too many times) performs the default action.
1134 TEST(ExcessiveCallTest, DoesDefaultAction) {
1135 // When there is an ON_CALL() statement, the action specified by it
1138 ON_CALL(a, Binary(_, _))
1139 .WillByDefault(Return(true));
1140 EXPECT_CALL(a, Binary(0, 0));
1142 bool result = false;
1143 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1144 "Mock function called more times than expected");
1145 EXPECT_TRUE(result);
1147 // When there is no ON_CALL(), the default value for the return type
1148 // should be returned.
1150 EXPECT_CALL(b, DoB(0))
1153 EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
1154 "Mock function called more times than expected");
1158 // Tests that when a void function is called too many times,
1159 // the failure message contains the argument values.
1160 TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
1162 EXPECT_CALL(a, DoA(_))
1164 EXPECT_NONFATAL_FAILURE(
1166 "Mock function called more times than expected - returning directly.\n"
1167 " Function call: DoA(9)\n"
1168 " Expected: to be never called\n"
1169 " Actual: called once - over-saturated and active");
1172 // Tests that when a non-void function is called too many times, the
1173 // failure message contains the argument values and the return value.
1174 TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1176 EXPECT_CALL(b, DoB(_));
1178 EXPECT_NONFATAL_FAILURE(
1180 "Mock function called more times than expected - "
1181 "returning default value.\n"
1182 " Function call: DoB(2)\n"
1184 " Expected: to be called once\n"
1185 " Actual: called twice - over-saturated and active");
1188 // Tests using sequences.
1190 TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1195 EXPECT_CALL(a, DoA(1));
1196 EXPECT_CALL(a, DoA(2));
1199 EXPECT_NONFATAL_FAILURE({ // NOLINT
1201 }, "Unexpected mock function call");
1207 TEST(InSequenceTest, NestedInSequence) {
1212 EXPECT_CALL(a, DoA(1));
1216 EXPECT_CALL(a, DoA(2));
1217 EXPECT_CALL(a, DoA(3));
1221 EXPECT_NONFATAL_FAILURE({ // NOLINT
1224 }, "Unexpected mock function call");
1230 TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1235 EXPECT_CALL(a, DoA(1));
1236 EXPECT_CALL(a, DoA(2));
1238 EXPECT_CALL(a, DoA(3));
1240 EXPECT_NONFATAL_FAILURE({ // NOLINT
1242 }, "Unexpected mock function call");
1249 // Tests that any order is allowed when no sequence is used.
1250 TEST(SequenceTest, AnyOrderIsOkByDefault) {
1255 EXPECT_CALL(a, DoA(1));
1256 EXPECT_CALL(b, DoB())
1257 .Times(AnyNumber());
1267 EXPECT_CALL(a, DoA(1));
1268 EXPECT_CALL(b, DoB())
1269 .Times(AnyNumber());
1276 // Tests that the calls must be in strict order when a complete order
1278 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1280 ON_CALL(a, ReturnResult(_))
1281 .WillByDefault(Return(Result()));
1284 EXPECT_CALL(a, ReturnResult(1))
1286 EXPECT_CALL(a, ReturnResult(2))
1288 EXPECT_CALL(a, ReturnResult(3))
1293 // May only be called after a.ReturnResult(2).
1294 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1300 // Tests that the calls must be in strict order when a complete order
1302 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1304 ON_CALL(a, ReturnResult(_))
1305 .WillByDefault(Return(Result()));
1308 EXPECT_CALL(a, ReturnResult(1))
1310 EXPECT_CALL(a, ReturnResult(2))
1313 // May only be called after a.ReturnResult(1).
1314 EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1320 // Tests specifying a DAG using multiple sequences.
1321 class PartialOrderTest : public testing::Test {
1323 PartialOrderTest() {
1324 ON_CALL(a_, ReturnResult(_))
1325 .WillByDefault(Return(Result()));
1327 // Specifies this partial ordering:
1329 // a.ReturnResult(1) ==>
1330 // a.ReturnResult(2) * n ==> a.ReturnResult(3)
1333 EXPECT_CALL(a_, ReturnResult(1))
1335 EXPECT_CALL(b_, DoB())
1338 EXPECT_CALL(a_, ReturnResult(2))
1341 EXPECT_CALL(a_, ReturnResult(3))
1349 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
1353 // May only be called after the second DoB().
1354 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1360 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
1361 // May only be called after ReturnResult(1).
1362 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1370 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
1371 // May only be called last.
1372 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
1380 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
1386 // May only be called before ReturnResult(3).
1387 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1390 TEST(SequenceTest, Retirement) {
1394 EXPECT_CALL(a, DoA(1))
1396 EXPECT_CALL(a, DoA(_))
1398 .RetiresOnSaturation();
1399 EXPECT_CALL(a, DoA(1))
1407 // Tests Expectation.
1409 TEST(ExpectationTest, ConstrutorsWork) {
1411 Expectation e1; // Default ctor.
1413 // Ctor from various forms of EXPECT_CALL.
1414 Expectation e2 = EXPECT_CALL(a, DoA(2));
1415 Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1418 Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1419 Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1421 Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1422 Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1423 Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1424 Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1426 Expectation e10 = e2; // Copy ctor.
1428 EXPECT_THAT(e1, Ne(e2));
1429 EXPECT_THAT(e2, Eq(e10));
1441 TEST(ExpectationTest, AssignmentWorks) {
1444 Expectation e2 = EXPECT_CALL(a, DoA(1));
1446 EXPECT_THAT(e1, Ne(e2));
1449 EXPECT_THAT(e1, Eq(e2));
1454 // Tests ExpectationSet.
1456 TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1457 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1460 TEST(ExpectationSetTest, ConstructorsWork) {
1464 const Expectation e2;
1465 ExpectationSet es1; // Default ctor.
1466 ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
1467 ExpectationSet es3 = e1; // Ctor from Expectation.
1468 ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
1469 ExpectationSet es5 = e2; // Ctor from const Expectation.
1470 ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
1471 ExpectationSet es7 = es2; // Copy ctor.
1473 EXPECT_EQ(0, es1.size());
1474 EXPECT_EQ(1, es2.size());
1475 EXPECT_EQ(1, es3.size());
1476 EXPECT_EQ(1, es4.size());
1477 EXPECT_EQ(1, es5.size());
1478 EXPECT_EQ(1, es6.size());
1479 EXPECT_EQ(1, es7.size());
1481 EXPECT_THAT(es3, Ne(es2));
1482 EXPECT_THAT(es4, Eq(es3));
1483 EXPECT_THAT(es5, Eq(es4));
1484 EXPECT_THAT(es6, Eq(es5));
1485 EXPECT_THAT(es7, Eq(es2));
1489 TEST(ExpectationSetTest, AssignmentWorks) {
1491 ExpectationSet es2 = Expectation();
1494 EXPECT_EQ(1, es1.size());
1495 EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1496 EXPECT_THAT(es1, Eq(es2));
1499 TEST(ExpectationSetTest, InsertionWorks) {
1503 EXPECT_EQ(1, es1.size());
1504 EXPECT_THAT(*(es1.begin()), Eq(e1));
1507 Expectation e2 = EXPECT_CALL(a, DoA(1));
1509 EXPECT_EQ(2, es1.size());
1511 ExpectationSet::const_iterator it1 = es1.begin();
1512 ExpectationSet::const_iterator it2 = it1;
1514 EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
1515 EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
1519 TEST(ExpectationSetTest, SizeWorks) {
1521 EXPECT_EQ(0, es.size());
1523 es += Expectation();
1524 EXPECT_EQ(1, es.size());
1527 es += EXPECT_CALL(a, DoA(1));
1528 EXPECT_EQ(2, es.size());
1533 TEST(ExpectationSetTest, IsEnumerable) {
1535 EXPECT_TRUE(es.begin() == es.end());
1537 es += Expectation();
1538 ExpectationSet::const_iterator it = es.begin();
1539 EXPECT_TRUE(it != es.end());
1540 EXPECT_THAT(*it, Eq(Expectation()));
1542 EXPECT_TRUE(it== es.end());
1545 // Tests the .After() clause.
1547 TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1550 es += EXPECT_CALL(a, DoA(1));
1551 es += EXPECT_CALL(a, DoA(2));
1552 EXPECT_CALL(a, DoA(3))
1560 TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1563 // The following also verifies that const Expectation objects work
1564 // too. Do not remove the const modifiers.
1565 const Expectation e1 = EXPECT_CALL(a, DoA(1));
1566 const Expectation e2 = EXPECT_CALL(b, DoB())
1569 EXPECT_CALL(a, DoA(2)).After(e2);
1577 // Calls must be in strict order when specified so using .After().
1578 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1583 // a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1584 Expectation e1 = EXPECT_CALL(a, DoA(1));
1585 Expectation e2 = EXPECT_CALL(b, DoB())
1587 EXPECT_CALL(a, DoA(2))
1592 // May only be called after DoB().
1593 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1599 // Calls must be in strict order when specified so using .After().
1600 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
1605 // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
1606 Expectation e1 = EXPECT_CALL(a, DoA(1));
1607 Expectation e2 = EXPECT_CALL(b, DoB())
1610 EXPECT_CALL(a, DoA(2))
1616 // May only be called after the second DoB().
1617 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1623 // Calls must satisfy the partial order when specified so.
1624 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1626 ON_CALL(a, ReturnResult(_))
1627 .WillByDefault(Return(Result()));
1631 // a.DoA(2) ==> a.ReturnResult(3)
1632 Expectation e = EXPECT_CALL(a, DoA(1));
1633 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1634 EXPECT_CALL(a, ReturnResult(3))
1637 // May only be called last.
1638 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1645 // Calls must satisfy the partial order when specified so.
1646 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
1651 // a.DoA(2) ==> a.DoA(3)
1652 Expectation e = EXPECT_CALL(a, DoA(1));
1653 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1654 EXPECT_CALL(a, DoA(3))
1659 // May only be called last.
1660 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1666 // .After() can be combined with .InSequence().
1667 TEST(AfterTest, CanBeUsedWithInSequence) {
1670 Expectation e = EXPECT_CALL(a, DoA(1));
1671 EXPECT_CALL(a, DoA(2)).InSequence(s);
1672 EXPECT_CALL(a, DoA(3))
1678 // May only be after DoA(2).
1679 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1685 // .After() can be called multiple times.
1686 TEST(AfterTest, CanBeCalledManyTimes) {
1688 Expectation e1 = EXPECT_CALL(a, DoA(1));
1689 Expectation e2 = EXPECT_CALL(a, DoA(2));
1690 Expectation e3 = EXPECT_CALL(a, DoA(3));
1691 EXPECT_CALL(a, DoA(4))
1702 // .After() accepts up to 5 arguments.
1703 TEST(AfterTest, AcceptsUpToFiveArguments) {
1705 Expectation e1 = EXPECT_CALL(a, DoA(1));
1706 Expectation e2 = EXPECT_CALL(a, DoA(2));
1707 Expectation e3 = EXPECT_CALL(a, DoA(3));
1708 ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1709 ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1710 EXPECT_CALL(a, DoA(6))
1711 .After(e1, e2, e3, es1, es2);
1721 // .After() allows input to contain duplicated Expectations.
1722 TEST(AfterTest, AcceptsDuplicatedInput) {
1724 ON_CALL(a, ReturnResult(_))
1725 .WillByDefault(Return(Result()));
1729 // DoA(2) ==> ReturnResult(3)
1730 Expectation e1 = EXPECT_CALL(a, DoA(1));
1731 Expectation e2 = EXPECT_CALL(a, DoA(2));
1735 EXPECT_CALL(a, ReturnResult(3))
1736 .After(e1, e2, es, e1);
1740 // May only be after DoA(2).
1741 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1747 // An Expectation added to an ExpectationSet after it has been used in
1748 // an .After() has no effect.
1749 TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1751 ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1752 Expectation e2 = EXPECT_CALL(a, DoA(2));
1753 EXPECT_CALL(a, DoA(3))
1762 // Tests that Google Mock correctly handles calls to mock functions
1763 // after a mock object owning one of their pre-requisites has died.
1765 // Tests that calls that satisfy the original spec are successful.
1766 TEST(DeletingMockEarlyTest, Success1) {
1767 MockB* const b1 = new MockB;
1768 MockA* const a = new MockA;
1769 MockB* const b2 = new MockB;
1773 EXPECT_CALL(*b1, DoB(_))
1774 .WillOnce(Return(1));
1775 EXPECT_CALL(*a, Binary(_, _))
1777 .WillRepeatedly(Return(true));
1778 EXPECT_CALL(*b2, DoB(_))
1780 .WillRepeatedly(Return(2));
1783 EXPECT_EQ(1, b1->DoB(1));
1785 // a's pre-requisite has died.
1786 EXPECT_TRUE(a->Binary(0, 1));
1788 // a's successor has died.
1789 EXPECT_TRUE(a->Binary(1, 2));
1793 // Tests that calls that satisfy the original spec are successful.
1794 TEST(DeletingMockEarlyTest, Success2) {
1795 MockB* const b1 = new MockB;
1796 MockA* const a = new MockA;
1797 MockB* const b2 = new MockB;
1801 EXPECT_CALL(*b1, DoB(_))
1802 .WillOnce(Return(1));
1803 EXPECT_CALL(*a, Binary(_, _))
1804 .Times(AnyNumber());
1805 EXPECT_CALL(*b2, DoB(_))
1807 .WillRepeatedly(Return(2));
1810 delete a; // a is trivially satisfied.
1811 EXPECT_EQ(1, b1->DoB(1));
1812 EXPECT_EQ(2, b2->DoB(2));
1817 // Tests that it's OK to delete a mock object itself in its action.
1819 // Suppresses warning on unreferenced formal parameter in MSVC with
1822 # pragma warning(push)
1823 # pragma warning(disable:4100)
1826 ACTION_P(Delete, ptr) { delete ptr; }
1829 # pragma warning(pop)
1832 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1833 MockA* const a = new MockA;
1834 EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1835 a->DoA(42); // This will cause a to be deleted.
1838 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1839 MockA* const a = new MockA;
1840 EXPECT_CALL(*a, ReturnResult(_))
1841 .WillOnce(DoAll(Delete(a), Return(Result())));
1842 a->ReturnResult(42); // This will cause a to be deleted.
1845 // Tests that calls that violate the original spec yield failures.
1846 TEST(DeletingMockEarlyTest, Failure1) {
1847 MockB* const b1 = new MockB;
1848 MockA* const a = new MockA;
1849 MockB* const b2 = new MockB;
1853 EXPECT_CALL(*b1, DoB(_))
1854 .WillOnce(Return(1));
1855 EXPECT_CALL(*a, Binary(_, _))
1856 .Times(AnyNumber());
1857 EXPECT_CALL(*b2, DoB(_))
1859 .WillRepeatedly(Return(2));
1862 delete a; // a is trivially satisfied.
1863 EXPECT_NONFATAL_FAILURE({
1865 }, "Unexpected mock function call");
1866 EXPECT_EQ(1, b1->DoB(1));
1871 // Tests that calls that violate the original spec yield failures.
1872 TEST(DeletingMockEarlyTest, Failure2) {
1873 MockB* const b1 = new MockB;
1874 MockA* const a = new MockA;
1875 MockB* const b2 = new MockB;
1879 EXPECT_CALL(*b1, DoB(_));
1880 EXPECT_CALL(*a, Binary(_, _))
1881 .Times(AnyNumber());
1882 EXPECT_CALL(*b2, DoB(_))
1883 .Times(AnyNumber());
1886 EXPECT_NONFATAL_FAILURE(delete b1,
1887 "Actual: never called");
1888 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1),
1889 "Unexpected mock function call");
1890 EXPECT_NONFATAL_FAILURE(b2->DoB(1),
1891 "Unexpected mock function call");
1896 class EvenNumberCardinality : public CardinalityInterface {
1898 // Returns true iff call_count calls will satisfy this cardinality.
1899 virtual bool IsSatisfiedByCallCount(int call_count) const {
1900 return call_count % 2 == 0;
1903 // Returns true iff call_count calls will saturate this cardinality.
1904 virtual bool IsSaturatedByCallCount(int /* call_count */) const {
1908 // Describes self to an ostream.
1909 virtual void DescribeTo(::std::ostream* os) const {
1910 *os << "called even number of times";
1914 Cardinality EvenNumber() {
1915 return Cardinality(new EvenNumberCardinality);
1918 TEST(ExpectationBaseTest,
1919 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1920 MockA* a = new MockA;
1923 EXPECT_CALL(*a, DoA(1))
1924 .Times(EvenNumber())
1926 EXPECT_CALL(*a, DoA(2))
1929 EXPECT_CALL(*a, DoA(3))
1930 .Times(AnyNumber());
1934 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1935 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1938 // The following tests verify the message generated when a mock
1939 // function is called.
1944 inline void operator<<(::std::ostream& os, const Printable&) {
1948 struct Unprintable {
1949 Unprintable() : value(0) {}
1957 MOCK_METHOD6(VoidMethod, void(bool cond, int n, string s, void* p,
1958 const Printable& x, Unprintable y));
1959 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
1962 GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC);
1965 class VerboseFlagPreservingFixture : public testing::Test {
1967 VerboseFlagPreservingFixture()
1968 : saved_verbose_flag_(GMOCK_FLAG(verbose)) {}
1970 ~VerboseFlagPreservingFixture() { GMOCK_FLAG(verbose) = saved_verbose_flag_; }
1973 const string saved_verbose_flag_;
1975 GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture);
1978 #if GTEST_HAS_STREAM_REDIRECTION
1980 // Tests that an uninteresting mock function call on a naggy mock
1981 // generates a warning without the stack trace when
1982 // --gmock_verbose=warning is specified.
1983 TEST(FunctionCallMessageTest,
1984 UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
1985 GMOCK_FLAG(verbose) = kWarningVerbosity;
1988 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
1989 const std::string output = GetCapturedStdout();
1990 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1991 EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
1994 // Tests that an uninteresting mock function call on a naggy mock
1995 // generates a warning containing the stack trace when
1996 // --gmock_verbose=info is specified.
1997 TEST(FunctionCallMessageTest,
1998 UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
1999 GMOCK_FLAG(verbose) = kInfoVerbosity;
2002 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2003 const std::string output = GetCapturedStdout();
2004 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
2005 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
2009 // We check the stack trace content in dbg-mode only, as opt-mode
2010 // may inline the call we are interested in seeing.
2012 // Verifies that a void mock function's name appears in the stack
2014 EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
2016 // Verifies that a non-void mock function's name appears in the
2020 const std::string output2 = GetCapturedStdout();
2021 EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
2026 // Tests that an uninteresting mock function call on a naggy mock
2027 // causes the function arguments and return value to be printed.
2028 TEST(FunctionCallMessageTest,
2029 UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
2030 // A non-void mock function.
2034 const std::string output1 = GetCapturedStdout();
2035 EXPECT_PRED_FORMAT2(
2037 "Uninteresting mock function call - returning default value.\n"
2038 " Function call: DoB()\n"
2039 " Returns: 0\n", output1.c_str());
2040 // Makes sure the return value is printed.
2042 // A void mock function.
2045 c.VoidMethod(false, 5, "Hi", NULL, Printable(), Unprintable());
2046 const std::string output2 = GetCapturedStdout();
2047 EXPECT_THAT(output2.c_str(),
2049 "Uninteresting mock function call - returning directly\\.\n"
2050 " Function call: VoidMethod"
2051 "\\(false, 5, \"Hi\", NULL, @.+ "
2052 "Printable, 4-byte object <00-00 00-00>\\)"));
2053 // A void function has no return value to print.
2056 // Tests how the --gmock_verbose flag affects Google Mock's output.
2058 class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
2060 // Verifies that the given Google Mock output is correct. (When
2061 // should_print is true, the output should match the given regex and
2062 // contain the given function name in the stack trace. When it's
2063 // false, the output should be empty.)
2064 void VerifyOutput(const std::string& output, bool should_print,
2065 const string& expected_substring,
2066 const string& function_name) {
2068 EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2070 // We check the stack trace content in dbg-mode only, as opt-mode
2071 // may inline the call we are interested in seeing.
2072 EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2074 // Suppresses 'unused function parameter' warnings.
2075 static_cast<void>(function_name);
2078 EXPECT_STREQ("", output.c_str());
2082 // Tests how the flag affects expected calls.
2083 void TestExpectedCall(bool should_print) {
2085 EXPECT_CALL(a, DoA(5));
2086 EXPECT_CALL(a, Binary(_, 1))
2087 .WillOnce(Return(true));
2089 // A void-returning function.
2093 GetCapturedStdout(),
2095 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2096 " Function call: DoA(5)\n"
2100 // A non-void-returning function.
2104 GetCapturedStdout(),
2106 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2107 " Function call: Binary(2, 1)\n"
2113 // Tests how the flag affects uninteresting calls on a naggy mock.
2114 void TestUninterestingCallOnNaggyMock(bool should_print) {
2117 "NOTE: You can safely ignore the above warning unless this "
2118 "call should not happen. Do not suppress it by blindly adding "
2119 "an EXPECT_CALL() if you don't mean to enforce the call. "
2120 "See https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md#"
2121 "knowing-when-to-expect for details.";
2123 // A void-returning function.
2127 GetCapturedStdout(),
2129 "\nGMOCK WARNING:\n"
2130 "Uninteresting mock function call - returning directly.\n"
2131 " Function call: DoA(5)\n" +
2135 // A non-void-returning function.
2139 GetCapturedStdout(),
2141 "\nGMOCK WARNING:\n"
2142 "Uninteresting mock function call - returning default value.\n"
2143 " Function call: Binary(2, 1)\n"
2144 " Returns: false\n" +
2150 // Tests that --gmock_verbose=info causes both expected and
2151 // uninteresting calls to be reported.
2152 TEST_F(GMockVerboseFlagTest, Info) {
2153 GMOCK_FLAG(verbose) = kInfoVerbosity;
2154 TestExpectedCall(true);
2155 TestUninterestingCallOnNaggyMock(true);
2158 // Tests that --gmock_verbose=warning causes uninteresting calls to be
2160 TEST_F(GMockVerboseFlagTest, Warning) {
2161 GMOCK_FLAG(verbose) = kWarningVerbosity;
2162 TestExpectedCall(false);
2163 TestUninterestingCallOnNaggyMock(true);
2166 // Tests that --gmock_verbose=warning causes neither expected nor
2167 // uninteresting calls to be reported.
2168 TEST_F(GMockVerboseFlagTest, Error) {
2169 GMOCK_FLAG(verbose) = kErrorVerbosity;
2170 TestExpectedCall(false);
2171 TestUninterestingCallOnNaggyMock(false);
2174 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2175 // as --gmock_verbose=warning.
2176 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2177 GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning".
2178 TestExpectedCall(false);
2179 TestUninterestingCallOnNaggyMock(true);
2182 #endif // GTEST_HAS_STREAM_REDIRECTION
2184 // A helper class that generates a failure when printed. We use it to
2185 // ensure that Google Mock doesn't print a value (even to an internal
2186 // buffer) when it is not supposed to do so.
2187 class PrintMeNot {};
2189 void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2190 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2191 << "printed even to an internal buffer.";
2194 class LogTestHelper {
2198 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2201 GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper);
2204 class GMockLogTest : public VerboseFlagPreservingFixture {
2206 LogTestHelper helper_;
2209 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2210 GMOCK_FLAG(verbose) = kWarningVerbosity;
2211 EXPECT_CALL(helper_, Foo(_))
2212 .WillOnce(Return(PrintMeNot()));
2213 helper_.Foo(PrintMeNot()); // This is an expected call.
2216 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2217 GMOCK_FLAG(verbose) = kErrorVerbosity;
2218 EXPECT_CALL(helper_, Foo(_))
2219 .WillOnce(Return(PrintMeNot()));
2220 helper_.Foo(PrintMeNot()); // This is an expected call.
2223 TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2224 GMOCK_FLAG(verbose) = kErrorVerbosity;
2225 ON_CALL(helper_, Foo(_))
2226 .WillByDefault(Return(PrintMeNot()));
2227 helper_.Foo(PrintMeNot()); // This should generate a warning.
2230 // Tests Mock::AllowLeak().
2232 TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2233 MockA* a = new MockA;
2237 TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2238 MockA* a = new MockA;
2240 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2244 TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2245 MockA* a = new MockA;
2246 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2250 TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2251 MockA* a = new MockA;
2253 EXPECT_CALL(*a, DoA(_));
2257 TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2258 MockA* a = new MockA;
2259 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2263 TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2264 MockA* a = new MockA;
2265 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2266 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2270 // Tests that we can verify and clear a mock object's expectations
2271 // when none of its methods has expectations.
2272 TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2274 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2276 // There should be no expectations on the methods now, so we can
2277 // freely call them.
2278 EXPECT_EQ(0, b.DoB());
2279 EXPECT_EQ(0, b.DoB(1));
2282 // Tests that we can verify and clear a mock object's expectations
2283 // when some, but not all, of its methods have expectations *and* the
2284 // verification succeeds.
2285 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2287 EXPECT_CALL(b, DoB())
2288 .WillOnce(Return(1));
2290 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2292 // There should be no expectations on the methods now, so we can
2293 // freely call them.
2294 EXPECT_EQ(0, b.DoB());
2295 EXPECT_EQ(0, b.DoB(1));
2298 // Tests that we can verify and clear a mock object's expectations
2299 // when some, but not all, of its methods have expectations *and* the
2300 // verification fails.
2301 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2303 EXPECT_CALL(b, DoB())
2304 .WillOnce(Return(1));
2306 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2307 "Actual: never called");
2308 ASSERT_FALSE(result);
2310 // There should be no expectations on the methods now, so we can
2311 // freely call them.
2312 EXPECT_EQ(0, b.DoB());
2313 EXPECT_EQ(0, b.DoB(1));
2316 // Tests that we can verify and clear a mock object's expectations
2317 // when all of its methods have expectations.
2318 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2320 EXPECT_CALL(b, DoB())
2321 .WillOnce(Return(1));
2322 EXPECT_CALL(b, DoB(_))
2323 .WillOnce(Return(2));
2326 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2328 // There should be no expectations on the methods now, so we can
2329 // freely call them.
2330 EXPECT_EQ(0, b.DoB());
2331 EXPECT_EQ(0, b.DoB(1));
2334 // Tests that we can verify and clear a mock object's expectations
2335 // when a method has more than one expectation.
2336 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2338 EXPECT_CALL(b, DoB(0))
2339 .WillOnce(Return(1));
2340 EXPECT_CALL(b, DoB(_))
2341 .WillOnce(Return(2));
2344 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2345 "Actual: never called");
2346 ASSERT_FALSE(result);
2348 // There should be no expectations on the methods now, so we can
2349 // freely call them.
2350 EXPECT_EQ(0, b.DoB());
2351 EXPECT_EQ(0, b.DoB(1));
2354 // Tests that we can call VerifyAndClearExpectations() on the same
2355 // mock object multiple times.
2356 TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2358 EXPECT_CALL(b, DoB());
2360 Mock::VerifyAndClearExpectations(&b);
2362 EXPECT_CALL(b, DoB(_))
2363 .WillOnce(Return(1));
2365 Mock::VerifyAndClearExpectations(&b);
2366 Mock::VerifyAndClearExpectations(&b);
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 clear a mock object's default actions when none
2375 // of its methods has default actions.
2376 TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2378 // If this crashes or generates a failure, the test will catch it.
2379 Mock::VerifyAndClear(&b);
2380 EXPECT_EQ(0, b.DoB());
2383 // Tests that we can clear a mock object's default actions when some,
2384 // but not all of its methods have default actions.
2385 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2388 .WillByDefault(Return(1));
2390 Mock::VerifyAndClear(&b);
2392 // Verifies that the default action of int DoB() was removed.
2393 EXPECT_EQ(0, b.DoB());
2396 // Tests that we can clear a mock object's default actions when all of
2397 // its methods have default actions.
2398 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2401 .WillByDefault(Return(1));
2403 .WillByDefault(Return(2));
2405 Mock::VerifyAndClear(&b);
2407 // Verifies that the default action of int DoB() was removed.
2408 EXPECT_EQ(0, b.DoB());
2410 // Verifies that the default action of int DoB(int) was removed.
2411 EXPECT_EQ(0, b.DoB(0));
2414 // Tests that we can clear a mock object's default actions when a
2415 // method has more than one ON_CALL() set on it.
2416 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2419 .WillByDefault(Return(1));
2421 .WillByDefault(Return(2));
2423 Mock::VerifyAndClear(&b);
2425 // Verifies that the default actions (there are two) of int DoB(int)
2427 EXPECT_EQ(0, b.DoB(0));
2428 EXPECT_EQ(0, b.DoB(1));
2431 // Tests that we can call VerifyAndClear() on a mock object multiple
2433 TEST(VerifyAndClearTest, CanCallManyTimes) {
2436 .WillByDefault(Return(1));
2437 Mock::VerifyAndClear(&b);
2438 Mock::VerifyAndClear(&b);
2441 .WillByDefault(Return(1));
2442 Mock::VerifyAndClear(&b);
2444 EXPECT_EQ(0, b.DoB());
2445 EXPECT_EQ(0, b.DoB(1));
2448 // Tests that VerifyAndClear() works when the verification succeeds.
2449 TEST(VerifyAndClearTest, Success) {
2452 .WillByDefault(Return(1));
2453 EXPECT_CALL(b, DoB(1))
2454 .WillOnce(Return(2));
2458 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2460 // There should be no expectations on the methods now, so we can
2461 // freely call them.
2462 EXPECT_EQ(0, b.DoB());
2463 EXPECT_EQ(0, b.DoB(1));
2466 // Tests that VerifyAndClear() works when the verification fails.
2467 TEST(VerifyAndClearTest, Failure) {
2470 .WillByDefault(Return(1));
2471 EXPECT_CALL(b, DoB())
2472 .WillOnce(Return(2));
2476 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2477 "Actual: never called");
2478 ASSERT_FALSE(result);
2480 // There should be no expectations on the methods now, so we can
2481 // freely call them.
2482 EXPECT_EQ(0, b.DoB());
2483 EXPECT_EQ(0, b.DoB(1));
2486 // Tests that VerifyAndClear() works when the default actions and
2487 // expectations are set on a const mock object.
2488 TEST(VerifyAndClearTest, Const) {
2490 ON_CALL(Const(b), DoB())
2491 .WillByDefault(Return(1));
2493 EXPECT_CALL(Const(b), DoB())
2494 .WillOnce(DoDefault())
2495 .WillOnce(Return(2));
2499 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2501 // There should be no expectations on the methods now, so we can
2502 // freely call them.
2503 EXPECT_EQ(0, b.DoB());
2504 EXPECT_EQ(0, b.DoB(1));
2507 // Tests that we can set default actions and expectations on a mock
2508 // object after VerifyAndClear() has been called on it.
2509 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2512 .WillByDefault(Return(1));
2513 EXPECT_CALL(b, DoB(_))
2514 .WillOnce(Return(2));
2517 Mock::VerifyAndClear(&b);
2519 EXPECT_CALL(b, DoB())
2520 .WillOnce(Return(3));
2522 .WillByDefault(Return(4));
2524 EXPECT_EQ(3, b.DoB());
2525 EXPECT_EQ(4, b.DoB(1));
2528 // Tests that calling VerifyAndClear() on one mock object does not
2529 // affect other mock objects (either of the same type or not).
2530 TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2535 ON_CALL(a, Binary(_, _))
2536 .WillByDefault(Return(true));
2537 EXPECT_CALL(a, Binary(_, _))
2538 .WillOnce(DoDefault())
2539 .WillOnce(Return(false));
2542 .WillByDefault(Return(1));
2543 EXPECT_CALL(b1, DoB(_))
2544 .WillOnce(Return(2));
2547 .WillByDefault(Return(3));
2548 EXPECT_CALL(b2, DoB(_));
2551 Mock::VerifyAndClear(&b2);
2553 // Verifies that the default actions and expectations of a and b1
2554 // are still in effect.
2555 EXPECT_TRUE(a.Binary(0, 0));
2556 EXPECT_FALSE(a.Binary(0, 0));
2558 EXPECT_EQ(1, b1.DoB());
2559 EXPECT_EQ(2, b1.DoB(0));
2562 TEST(VerifyAndClearTest,
2563 DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2564 linked_ptr<MockA> a(new MockA);
2565 ReferenceHoldingMock test_mock;
2567 // EXPECT_CALL stores a reference to a inside test_mock.
2568 EXPECT_CALL(test_mock, AcceptReference(_))
2569 .WillRepeatedly(SetArgPointee<0>(a));
2571 // Throw away the reference to the mock that we have in a. After this, the
2572 // only reference to it is stored by test_mock.
2575 // When test_mock goes out of scope, it destroys the last remaining reference
2576 // to the mock object originally pointed to by a. This will cause the MockA
2577 // destructor to be called from inside the ReferenceHoldingMock destructor.
2578 // The state of all mocks is protected by a single global lock, but there
2579 // should be no deadlock.
2582 TEST(VerifyAndClearTest,
2583 DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2584 linked_ptr<MockA> a(new MockA);
2585 ReferenceHoldingMock test_mock;
2587 // ON_CALL stores a reference to a inside test_mock.
2588 ON_CALL(test_mock, AcceptReference(_))
2589 .WillByDefault(SetArgPointee<0>(a));
2591 // Throw away the reference to the mock that we have in a. After this, the
2592 // only reference to it is stored by test_mock.
2595 // When test_mock goes out of scope, it destroys the last remaining reference
2596 // to the mock object originally pointed to by a. This will cause the MockA
2597 // destructor to be called from inside the ReferenceHoldingMock destructor.
2598 // The state of all mocks is protected by a single global lock, but there
2599 // should be no deadlock.
2602 // Tests that a mock function's action can call a mock function
2603 // (either the same function or a different one) either as an explicit
2604 // action or as a default action without causing a dead lock. It
2605 // verifies that the action is not performed inside the critical
2607 TEST(SynchronizationTest, CanCallMockMethodInAction) {
2611 .WillByDefault(IgnoreResult(InvokeWithoutArgs(&c,
2612 &MockC::NonVoidMethod)));
2613 EXPECT_CALL(a, DoA(1));
2614 EXPECT_CALL(a, DoA(1))
2615 .WillOnce(Invoke(&a, &MockA::DoA))
2616 .RetiresOnSaturation();
2617 EXPECT_CALL(c, NonVoidMethod());
2620 // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2621 // which will in turn match the first EXPECT_CALL() and trigger a call to
2622 // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2623 // EXPECT_CALL() did not specify an action.
2628 // Allows the user to define his own main and then invoke gmock_main
2629 // from it. This might be necessary on some platforms which require
2630 // specific setup and teardown.
2631 #if GMOCK_RENAME_MAIN
2632 int gmock_main(int argc, char **argv) {
2634 int main(int argc, char **argv) {
2635 #endif // GMOCK_RENAME_MAIN
2636 testing::InitGoogleMock(&argc, argv);
2638 // Ensures that the tests pass no matter what value of
2639 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2640 testing::GMOCK_FLAG(catch_leaked_mocks) = true;
2641 testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity;
2643 return RUN_ALL_TESTS();