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 // Google Mock - a framework for writing C++ mock classes.
32 // This file tests the spec builder syntax.
34 #include "gmock/gmock-spec-builders.h"
37 #include <ostream> // NOLINT
40 #include <type_traits>
42 #include "gmock/gmock.h"
43 #include "gmock/internal/gmock-port.h"
44 #include "gtest/gtest-spi.h"
45 #include "gtest/gtest.h"
46 #include "gtest/internal/gtest-port.h"
51 using ::testing::internal::FormatFileLocation;
52 using ::testing::internal::kAllow;
53 using ::testing::internal::kErrorVerbosity;
54 using ::testing::internal::kFail;
55 using ::testing::internal::kInfoVerbosity;
56 using ::testing::internal::kWarn;
57 using ::testing::internal::kWarningVerbosity;
59 #if GTEST_HAS_STREAM_REDIRECTION
60 using ::testing::internal::CaptureStdout;
61 using ::testing::internal::GetCapturedStdout;
66 class MockIncomplete {
68 // This line verifies that a mock method can take a by-reference
69 // argument of an incomplete type.
70 MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
73 // Tells Google Mock how to print a value of type Incomplete.
74 void PrintTo(const Incomplete& x, ::std::ostream* os);
76 TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
77 // Even though this mock class contains a mock method that takes
78 // by-reference an argument whose type is incomplete, we can still
79 // use the mock, as long as Google Mock knows how to print the
81 MockIncomplete incomplete;
82 EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber());
85 // The definition of the printer for the argument type doesn't have to
86 // be visible where the mock is used.
87 void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
93 // A type that's not default constructible.
94 class NonDefaultConstructible {
96 explicit NonDefaultConstructible(int /* dummy */) {}
103 MOCK_METHOD1(DoA, void(int n));
104 MOCK_METHOD1(ReturnResult, Result(int n));
105 MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
106 MOCK_METHOD2(Binary, bool(int x, int y));
107 MOCK_METHOD2(ReturnInt, int(int x, int y));
110 MockA(const MockA&) = delete;
111 MockA& operator=(const MockA&) = delete;
118 MOCK_CONST_METHOD0(DoB, int()); // NOLINT
119 MOCK_METHOD1(DoB, int(int n)); // NOLINT
122 MockB(const MockB&) = delete;
123 MockB& operator=(const MockB&) = delete;
126 class ReferenceHoldingMock {
128 ReferenceHoldingMock() {}
130 MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
133 ReferenceHoldingMock(const ReferenceHoldingMock&) = delete;
134 ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete;
137 // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
138 // redefining a mock method name. This could happen, for example, when
139 // the tested code #includes Win32 API headers which define many APIs
140 // as macros, e.g. #define TextOut TextOutW.
142 #define Method MethodW
147 virtual int Method() = 0;
149 class MockCC : public CC {
153 MOCK_METHOD0(Method, int());
156 MockCC(const MockCC&) = delete;
157 MockCC& operator=(const MockCC&) = delete;
160 // Tests that a method with expanded name compiles.
161 TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
163 ON_CALL(cc, Method());
166 // Tests that the method with expanded name not only compiles but runs
167 // and returns a correct value, too.
168 TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
170 ON_CALL(cc, Method()).WillByDefault(Return(42));
171 EXPECT_EQ(42, cc.Method());
174 // Tests that a method with expanded name compiles.
175 TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
177 EXPECT_CALL(cc, Method());
181 // Tests that it works, too.
182 TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {
184 EXPECT_CALL(cc, Method()).WillOnce(Return(42));
185 EXPECT_EQ(42, cc.Method());
188 #undef Method // Done with macro redefinition tests.
190 // Tests that ON_CALL evaluates its arguments exactly once as promised
192 TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {
196 ON_CALL(*pa++, DoA(_));
197 EXPECT_EQ(&a + 1, pa);
200 TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {
204 ON_CALL(a, DoA(n++));
208 // Tests that the syntax of ON_CALL() is enforced at run time.
210 TEST(OnCallSyntaxTest, WithIsOptional) {
213 ON_CALL(a, DoA(5)).WillByDefault(Return());
214 ON_CALL(a, DoA(_)).With(_).WillByDefault(Return());
217 TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
220 EXPECT_NONFATAL_FAILURE(
222 ON_CALL(a, ReturnResult(_))
225 .WillByDefault(Return(Result()));
227 ".With() cannot appear more than once in an ON_CALL()");
230 TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
233 EXPECT_DEATH_IF_SUPPORTED(
241 TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
244 EXPECT_NONFATAL_FAILURE(
246 ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return());
248 ".WillByDefault() must appear exactly once in an ON_CALL()");
251 // Tests that EXPECT_CALL evaluates its arguments exactly once as
252 // promised by Google Mock.
253 TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
257 EXPECT_CALL(*pa++, DoA(_));
259 EXPECT_EQ(&a + 1, pa);
262 TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {
266 EXPECT_CALL(a, DoA(n++));
271 // Tests that the syntax of EXPECT_CALL() is enforced at run time.
273 TEST(ExpectCallSyntaxTest, WithIsOptional) {
276 EXPECT_CALL(a, DoA(5)).Times(0);
277 EXPECT_CALL(a, DoA(6)).With(_).Times(0);
280 TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
283 EXPECT_NONFATAL_FAILURE(
285 EXPECT_CALL(a, DoA(6)).With(_).With(_);
287 ".With() cannot appear more than once in an EXPECT_CALL()");
292 TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
295 EXPECT_NONFATAL_FAILURE(
297 EXPECT_CALL(a, DoA(1)).Times(1).With(_);
299 ".With() must be the first clause in an EXPECT_CALL()");
303 EXPECT_NONFATAL_FAILURE(
305 EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_);
307 ".With() must be the first clause in an EXPECT_CALL()");
312 TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
315 EXPECT_CALL(a, DoA(1)).WillOnce(Return());
317 EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
324 TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
327 EXPECT_NONFATAL_FAILURE(
329 EXPECT_CALL(a, DoA(1)).Times(1).Times(2);
331 ".Times() cannot appear more than once in an EXPECT_CALL()");
337 TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
341 EXPECT_NONFATAL_FAILURE(
343 EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1);
345 ".Times() may only appear *before* ");
350 TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
354 EXPECT_CALL(a, DoA(1));
355 EXPECT_CALL(a, DoA(2)).InSequence(s);
361 TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
365 EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1);
370 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
374 Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber());
375 EXPECT_NONFATAL_FAILURE(
377 EXPECT_CALL(a, DoA(2)).After(e).InSequence(s);
379 ".InSequence() cannot appear after ");
384 TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
388 EXPECT_NONFATAL_FAILURE(
390 EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s);
392 ".InSequence() cannot appear after ");
397 TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
400 Expectation e = EXPECT_CALL(a, DoA(1));
401 EXPECT_NONFATAL_FAILURE(
402 { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); },
403 ".After() cannot appear after ");
409 TEST(ExpectCallSyntaxTest, WillIsOptional) {
412 EXPECT_CALL(a, DoA(1));
413 EXPECT_CALL(a, DoA(2)).WillOnce(Return());
419 TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
422 EXPECT_CALL(a, DoA(1))
429 TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
432 EXPECT_NONFATAL_FAILURE(
434 EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return());
436 ".WillOnce() cannot appear after ");
441 TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
444 EXPECT_CALL(a, DoA(1)).WillOnce(Return());
445 EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
452 TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
455 EXPECT_NONFATAL_FAILURE(
457 EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly(
460 ".WillRepeatedly() cannot appear more than once in an "
464 TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
467 EXPECT_NONFATAL_FAILURE(
469 EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return());
471 ".WillRepeatedly() cannot appear after ");
474 TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
477 EXPECT_CALL(a, DoA(1));
478 EXPECT_CALL(a, DoA(1)).RetiresOnSaturation();
484 TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
487 EXPECT_NONFATAL_FAILURE(
489 EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation();
491 ".RetiresOnSaturation() cannot appear more than once");
496 TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
499 EXPECT_CALL(a, DoA(1));
502 EXPECT_NONFATAL_FAILURE(
505 EXPECT_CALL(a, DoA(1));
507 "to be called once");
508 EXPECT_NONFATAL_FAILURE(
511 EXPECT_CALL(a, DoA(1));
515 "to be called once");
518 #if GTEST_HAS_STREAM_REDIRECTION
520 // Tests that Google Mock doesn't print a warning when the number of
521 // WillOnce() is adequate.
522 TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
527 // It's always fine to omit WillOnce() entirely.
528 EXPECT_CALL(b, DoB()).Times(0);
529 EXPECT_CALL(b, DoB(1)).Times(AtMost(1));
530 EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1));
532 // It's fine for the number of WillOnce()s to equal the upper bound.
533 EXPECT_CALL(b, DoB(3))
534 .Times(Between(1, 2))
536 .WillOnce(Return(2));
538 // It's fine for the number of WillOnce()s to be smaller than the
539 // upper bound when there is a WillRepeatedly().
540 EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly(
543 // Satisfies the above expectations.
547 EXPECT_STREQ("", GetCapturedStdout().c_str());
550 // Tests that Google Mock warns on having too many actions in an
551 // expectation compared to its cardinality.
552 TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
557 // Warns when the number of WillOnce()s is larger than the upper bound.
558 EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); // #1
559 EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce(
561 EXPECT_CALL(b, DoB(1))
565 .RetiresOnSaturation(); // #3
567 // Warns when the number of WillOnce()s equals the upper bound and
568 // there is a WillRepeatedly().
569 EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); // #4
570 EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly(
573 // Satisfies the above expectations.
577 const std::string output = GetCapturedStdout();
578 EXPECT_PRED_FORMAT2(IsSubstring,
579 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
580 "Expected to be never called, but has 1 WillOnce().",
582 EXPECT_PRED_FORMAT2(IsSubstring,
583 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
584 "Expected to be called at most once, "
585 "but has 2 WillOnce()s.",
589 "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
590 "Expected to be called once, but has 2 WillOnce()s.",
592 EXPECT_PRED_FORMAT2(IsSubstring,
593 "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
594 "Expected to be never called, but has 0 WillOnce()s "
595 "and a WillRepeatedly().",
599 "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
600 "Expected to be called once, but has 1 WillOnce() "
601 "and a WillRepeatedly().",
605 // Tests that Google Mock warns on having too few actions in an
606 // expectation compared to its cardinality.
607 TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
610 EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1));
614 const std::string output = GetCapturedStdout();
615 EXPECT_PRED_FORMAT2(IsSubstring,
616 "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
617 "Expected to be called between 2 and 3 times, "
618 "but has only 1 WillOnce().",
623 TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
624 int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);
626 GMOCK_FLAG_SET(default_mock_behavior, kAllow);
632 std::string output = GetCapturedStdout();
633 EXPECT_TRUE(output.empty()) << output;
635 GMOCK_FLAG_SET(default_mock_behavior, kWarn);
641 std::string warning_output = GetCapturedStdout();
642 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
643 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
646 GMOCK_FLAG_SET(default_mock_behavior, kFail);
647 EXPECT_NONFATAL_FAILURE(
652 "Uninteresting mock function call");
654 // Out of bounds values are converted to kWarn
655 GMOCK_FLAG_SET(default_mock_behavior, -1);
661 warning_output = GetCapturedStdout();
662 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
663 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
665 GMOCK_FLAG_SET(default_mock_behavior, 3);
671 warning_output = GetCapturedStdout();
672 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
673 EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
676 GMOCK_FLAG_SET(default_mock_behavior, original_behavior);
679 #endif // GTEST_HAS_STREAM_REDIRECTION
681 // Tests the semantics of ON_CALL().
683 // Tests that the built-in default action is taken when no ON_CALL()
685 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
687 EXPECT_CALL(b, DoB());
689 EXPECT_EQ(0, b.DoB());
692 // Tests that the built-in default action is taken when no ON_CALL()
693 // matches the invocation.
694 TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
696 ON_CALL(b, DoB(1)).WillByDefault(Return(1));
697 EXPECT_CALL(b, DoB(_));
699 EXPECT_EQ(0, b.DoB(2));
702 // Tests that the last matching ON_CALL() action is taken.
703 TEST(OnCallTest, PicksLastMatchingOnCall) {
705 ON_CALL(b, DoB(_)).WillByDefault(Return(3));
706 ON_CALL(b, DoB(2)).WillByDefault(Return(2));
707 ON_CALL(b, DoB(1)).WillByDefault(Return(1));
708 EXPECT_CALL(b, DoB(_));
710 EXPECT_EQ(2, b.DoB(2));
713 // Tests the semantics of EXPECT_CALL().
715 // Tests that any call is allowed when no EXPECT_CALL() is specified.
716 TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
718 EXPECT_CALL(b, DoB());
719 // There is no expectation on DoB(int).
723 // DoB(int) can be called any number of times.
728 // Tests that the last matching EXPECT_CALL() fires.
729 TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
731 EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2));
732 EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1));
734 EXPECT_EQ(1, b.DoB(1));
737 // Tests lower-bound violation.
738 TEST(ExpectCallTest, CatchesTooFewCalls) {
739 EXPECT_NONFATAL_FAILURE(
742 EXPECT_CALL(b, DoB(5)).Times(AtLeast(2));
746 "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
747 " Expected: to be called at least twice\n"
748 " Actual: called once - unsatisfied and active");
751 // Tests that the cardinality can be inferred when no Times(...) is
753 TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
756 EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
758 EXPECT_EQ(1, b.DoB());
759 EXPECT_EQ(2, b.DoB());
762 EXPECT_NONFATAL_FAILURE(
765 EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
767 EXPECT_EQ(1, b.DoB());
769 "to be called twice");
773 EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
775 EXPECT_EQ(1, b.DoB());
776 EXPECT_EQ(2, b.DoB());
777 EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
781 TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
784 EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
786 EXPECT_EQ(1, b.DoB());
791 EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
793 EXPECT_EQ(1, b.DoB());
794 EXPECT_EQ(2, b.DoB());
795 EXPECT_EQ(2, b.DoB());
798 EXPECT_NONFATAL_FAILURE(
801 EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
803 "to be called at least once");
806 #if defined(__cplusplus) && __cplusplus >= 201703L
808 // It should be possible to return a non-moveable type from a mock action in
809 // C++17 and above, where it's guaranteed that such a type can be initialized
810 // from a prvalue returned from a function.
811 TEST(ExpectCallTest, NonMoveableType) {
812 // Define a non-moveable result type.
814 explicit Result(int x_in) : x(x_in) {}
815 Result(Result&&) = delete;
820 static_assert(!std::is_move_constructible_v<Result>);
821 static_assert(!std::is_copy_constructible_v<Result>);
823 static_assert(!std::is_move_assignable_v<Result>);
824 static_assert(!std::is_copy_assignable_v<Result>);
826 // We should be able to use a callable that returns that result as both a
827 // OnceAction and an Action, whether the callable ignores arguments or not.
828 const auto return_17 = [] { return Result(17); };
830 static_cast<void>(OnceAction<Result()>{return_17});
831 static_cast<void>(Action<Result()>{return_17});
833 static_cast<void>(OnceAction<Result(int)>{return_17});
834 static_cast<void>(Action<Result(int)>{return_17});
836 // It should be possible to return the result end to end through an
837 // EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
838 MockFunction<Result()> mock;
839 EXPECT_CALL(mock, Call) //
840 .WillOnce(return_17) //
841 .WillRepeatedly(return_17);
843 EXPECT_EQ(17, mock.AsStdFunction()().x);
844 EXPECT_EQ(17, mock.AsStdFunction()().x);
845 EXPECT_EQ(17, mock.AsStdFunction()().x);
848 #endif // C++17 and above
850 // Tests that the n-th action is taken for the n-th matching
852 TEST(ExpectCallTest, NthMatchTakesNthAction) {
854 EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(
857 EXPECT_EQ(1, b.DoB());
858 EXPECT_EQ(2, b.DoB());
859 EXPECT_EQ(3, b.DoB());
862 // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
863 // list is exhausted.
864 TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
866 EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
868 EXPECT_EQ(1, b.DoB());
869 EXPECT_EQ(2, b.DoB());
870 EXPECT_EQ(2, b.DoB());
873 #if GTEST_HAS_STREAM_REDIRECTION
875 // Tests that the default action is taken when the WillOnce(...) list is
876 // exhausted and there is no WillRepeatedly().
877 TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
879 EXPECT_CALL(b, DoB(_)).Times(1);
880 EXPECT_CALL(b, DoB())
883 .WillOnce(Return(2));
886 EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
887 // expectation has no action clause at all.
888 EXPECT_EQ(1, b.DoB());
889 EXPECT_EQ(2, b.DoB());
890 const std::string output1 = GetCapturedStdout();
891 EXPECT_STREQ("", output1.c_str());
894 EXPECT_EQ(0, b.DoB());
895 EXPECT_EQ(0, b.DoB());
896 const std::string output2 = GetCapturedStdout();
897 EXPECT_THAT(output2.c_str(),
898 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
899 "Called 3 times, but only 2 WillOnce()s are specified"
900 " - returning default value."));
901 EXPECT_THAT(output2.c_str(),
902 HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"
903 "Called 4 times, but only 2 WillOnce()s are specified"
904 " - returning default value."));
907 TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {
909 std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
910 EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));
912 EXPECT_EQ(1, b.DoB());
915 EXPECT_EQ(0, b.DoB());
916 const std::string output = GetCapturedStdout();
917 // The warning message should contain the call location.
918 EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);
921 TEST(FunctionMockerMessageTest,
922 ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {
923 std::string on_call_location;
927 on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);
928 ON_CALL(b, DoB(_)).WillByDefault(Return(0));
931 EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
934 #endif // GTEST_HAS_STREAM_REDIRECTION
936 // Tests that an uninteresting call performs the default action.
937 TEST(UninterestingCallTest, DoesDefaultAction) {
938 // When there is an ON_CALL() statement, the action specified by it
941 ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
942 EXPECT_TRUE(a.Binary(1, 2));
944 // When there is no ON_CALL(), the default value for the return type
945 // should be returned.
947 EXPECT_EQ(0, b.DoB());
950 // Tests that an unexpected call performs the default action.
951 TEST(UnexpectedCallTest, DoesDefaultAction) {
952 // When there is an ON_CALL() statement, the action specified by it
955 ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
956 EXPECT_CALL(a, Binary(0, 0));
959 EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
960 "Unexpected mock function call");
963 // When there is no ON_CALL(), the default value for the return type
964 // should be returned.
966 EXPECT_CALL(b, DoB(0)).Times(0);
968 EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call");
972 // Tests that when an unexpected void function generates the right
974 TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
975 // First, tests the message when there is only one EXPECT_CALL().
977 EXPECT_CALL(a1, DoA(1));
979 // Ideally we should match the failure message against a regex, but
980 // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for
981 // multiple sub-strings instead.
982 EXPECT_NONFATAL_FAILURE(
984 "Unexpected mock function call - returning directly.\n"
985 " Function call: DoA(9)\n"
986 "Google Mock tried the following 1 expectation, but it didn't match:");
987 EXPECT_NONFATAL_FAILURE(
989 " Expected arg #0: is equal to 1\n"
991 " Expected: to be called once\n"
992 " Actual: called once - saturated and active");
994 // Next, tests the message when there are more than one EXPECT_CALL().
996 EXPECT_CALL(a2, DoA(1));
997 EXPECT_CALL(a2, DoA(3));
999 EXPECT_NONFATAL_FAILURE(
1001 "Unexpected mock function call - returning directly.\n"
1002 " Function call: DoA(2)\n"
1003 "Google Mock tried the following 2 expectations, but none matched:");
1004 EXPECT_NONFATAL_FAILURE(
1006 "tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"
1007 " Expected arg #0: is equal to 1\n"
1009 " Expected: to be called once\n"
1010 " Actual: called once - saturated and active");
1011 EXPECT_NONFATAL_FAILURE(
1013 "tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"
1014 " Expected arg #0: is equal to 3\n"
1016 " Expected: to be called once\n"
1017 " Actual: never called - unsatisfied and active");
1021 // Tests that an unexpected non-void function generates the right
1023 TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {
1025 EXPECT_CALL(b1, DoB(1));
1027 EXPECT_NONFATAL_FAILURE(
1029 "Unexpected mock function call - returning default value.\n"
1030 " Function call: DoB(2)\n"
1032 "Google Mock tried the following 1 expectation, but it didn't match:");
1033 EXPECT_NONFATAL_FAILURE(
1035 " Expected arg #0: is equal to 1\n"
1037 " Expected: to be called once\n"
1038 " Actual: called once - saturated and active");
1041 // Tests that Google Mock explains that an retired expectation doesn't
1043 TEST(UnexpectedCallTest, RetiredExpectation) {
1045 EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();
1048 EXPECT_NONFATAL_FAILURE(b.DoB(1),
1049 " Expected: the expectation is active\n"
1050 " Actual: it is retired");
1053 // Tests that Google Mock explains that an expectation that doesn't
1054 // match the arguments doesn't match the call.
1055 TEST(UnexpectedCallTest, UnmatchedArguments) {
1057 EXPECT_CALL(b, DoB(1));
1059 EXPECT_NONFATAL_FAILURE(b.DoB(2),
1060 " Expected arg #0: is equal to 1\n"
1065 // Tests that Google Mock explains that an expectation with
1066 // unsatisfied pre-requisites doesn't match the call.
1067 TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
1070 EXPECT_CALL(b, DoB(1)).InSequence(s1);
1071 EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);
1072 EXPECT_CALL(b, DoB(3)).InSequence(s2);
1073 EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);
1075 ::testing::TestPartResultArray failures;
1077 ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
1079 // Now 'failures' contains the Google Test failures generated by
1080 // the above statement.
1083 // There should be one non-fatal failure.
1084 ASSERT_EQ(1, failures.size());
1085 const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
1086 EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
1088 // Verifies that the failure message contains the two unsatisfied
1089 // pre-requisites but not the satisfied one.
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(),
1102 // POSIX RE doesn't understand the (?s) prefix, but has no
1103 // trouble with (.|\n).
1104 "the following immediate pre-requisites are not satisfied:\n"
1105 "(.|\n)*: pre-requisite #0\n"
1106 "(.|\n)*: pre-requisite #1"));
1108 // We can only use Google Test's own simple regex.
1109 EXPECT_THAT(r.message(),
1111 "the following immediate pre-requisites are not satisfied:"));
1112 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
1113 EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
1114 #endif // GTEST_USES_PCRE
1121 TEST(UndefinedReturnValueTest,
1122 ReturnValueIsMandatoryWhenNotDefaultConstructible) {
1124 // FIXME: We should really verify the output message,
1125 // but we cannot yet due to that EXPECT_DEATH only captures stderr
1126 // while Google Mock logs to stdout.
1127 #if GTEST_HAS_EXCEPTIONS
1128 EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());
1130 EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
1134 // Tests that an excessive call (one whose arguments match the
1135 // matchers but is called too many times) performs the default action.
1136 TEST(ExcessiveCallTest, DoesDefaultAction) {
1137 // When there is an ON_CALL() statement, the action specified by it
1140 ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
1141 EXPECT_CALL(a, Binary(0, 0));
1143 bool result = false;
1144 EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
1145 "Mock function called more times than expected");
1146 EXPECT_TRUE(result);
1148 // When there is no ON_CALL(), the default value for the return type
1149 // should be returned.
1151 EXPECT_CALL(b, DoB(0)).Times(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(_)).Times(0);
1163 EXPECT_NONFATAL_FAILURE(
1165 "Mock function called more times than expected - returning directly.\n"
1166 " Function call: DoA(9)\n"
1167 " Expected: to be never called\n"
1168 " Actual: called once - over-saturated and active");
1171 // Tests that when a non-void function is called too many times, the
1172 // failure message contains the argument values and the return value.
1173 TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {
1175 EXPECT_CALL(b, DoB(_));
1177 EXPECT_NONFATAL_FAILURE(
1179 "Mock function called more times than expected - "
1180 "returning default value.\n"
1181 " Function call: DoB(2)\n"
1183 " Expected: to be called once\n"
1184 " Actual: called twice - over-saturated and active");
1187 // Tests using sequences.
1189 TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
1194 EXPECT_CALL(a, DoA(1));
1195 EXPECT_CALL(a, DoA(2));
1198 EXPECT_NONFATAL_FAILURE(
1202 "Unexpected mock function call");
1208 TEST(InSequenceTest, NestedInSequence) {
1213 EXPECT_CALL(a, DoA(1));
1217 EXPECT_CALL(a, DoA(2));
1218 EXPECT_CALL(a, DoA(3));
1222 EXPECT_NONFATAL_FAILURE(
1227 "Unexpected mock function call");
1233 TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
1238 EXPECT_CALL(a, DoA(1));
1239 EXPECT_CALL(a, DoA(2));
1241 EXPECT_CALL(a, DoA(3));
1243 EXPECT_NONFATAL_FAILURE(
1247 "Unexpected mock function call");
1254 // Tests that any order is allowed when no sequence is used.
1255 TEST(SequenceTest, AnyOrderIsOkByDefault) {
1260 EXPECT_CALL(a, DoA(1));
1261 EXPECT_CALL(b, DoB()).Times(AnyNumber());
1271 EXPECT_CALL(a, DoA(1));
1272 EXPECT_CALL(b, DoB()).Times(AnyNumber());
1279 // Tests that the calls must be in strict order when a complete order
1281 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
1283 ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
1286 EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
1287 EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
1288 EXPECT_CALL(a, ReturnResult(3)).InSequence(s);
1292 // May only be called after a.ReturnResult(2).
1293 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1299 // Tests that the calls must be in strict order when a complete order
1301 TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
1303 ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
1306 EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
1307 EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
1309 // May only be called after a.ReturnResult(1).
1310 EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
1316 // Tests specifying a DAG using multiple sequences.
1317 class PartialOrderTest : public testing::Test {
1319 PartialOrderTest() {
1320 ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result()));
1322 // Specifies this partial ordering:
1324 // a.ReturnResult(1) ==>
1325 // a.ReturnResult(2) * n ==> a.ReturnResult(3)
1328 EXPECT_CALL(a_, ReturnResult(1)).InSequence(x);
1329 EXPECT_CALL(b_, DoB()).Times(2).InSequence(y);
1330 EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y);
1331 EXPECT_CALL(a_, ReturnResult(3)).InSequence(x);
1338 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
1342 // May only be called after the second DoB().
1343 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1349 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {
1350 // May only be called after ReturnResult(1).
1351 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1359 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {
1360 // May only be called last.
1361 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");
1369 TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {
1375 // May only be called before ReturnResult(3).
1376 EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
1379 TEST(SequenceTest, Retirement) {
1383 EXPECT_CALL(a, DoA(1)).InSequence(s);
1384 EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation();
1385 EXPECT_CALL(a, DoA(1)).InSequence(s);
1392 // Tests Expectation.
1394 TEST(ExpectationTest, ConstrutorsWork) {
1396 Expectation e1; // Default ctor.
1398 // Ctor from various forms of EXPECT_CALL.
1399 Expectation e2 = EXPECT_CALL(a, DoA(2));
1400 Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);
1403 Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);
1404 Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);
1406 Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);
1407 Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());
1408 Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());
1409 Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();
1411 Expectation e10 = e2; // Copy ctor.
1413 EXPECT_THAT(e1, Ne(e2));
1414 EXPECT_THAT(e2, Eq(e10));
1426 TEST(ExpectationTest, AssignmentWorks) {
1429 Expectation e2 = EXPECT_CALL(a, DoA(1));
1431 EXPECT_THAT(e1, Ne(e2));
1434 EXPECT_THAT(e1, Eq(e2));
1439 // Tests ExpectationSet.
1441 TEST(ExpectationSetTest, MemberTypesAreCorrect) {
1442 ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
1445 TEST(ExpectationSetTest, ConstructorsWork) {
1449 const Expectation e2;
1450 ExpectationSet es1; // Default ctor.
1451 ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
1452 ExpectationSet es3 = e1; // Ctor from Expectation.
1453 ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
1454 ExpectationSet es5 = e2; // Ctor from const Expectation.
1455 ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
1456 ExpectationSet es7 = es2; // Copy ctor.
1458 EXPECT_EQ(0, es1.size());
1459 EXPECT_EQ(1, es2.size());
1460 EXPECT_EQ(1, es3.size());
1461 EXPECT_EQ(1, es4.size());
1462 EXPECT_EQ(1, es5.size());
1463 EXPECT_EQ(1, es6.size());
1464 EXPECT_EQ(1, es7.size());
1466 EXPECT_THAT(es3, Ne(es2));
1467 EXPECT_THAT(es4, Eq(es3));
1468 EXPECT_THAT(es5, Eq(es4));
1469 EXPECT_THAT(es6, Eq(es5));
1470 EXPECT_THAT(es7, Eq(es2));
1474 TEST(ExpectationSetTest, AssignmentWorks) {
1476 ExpectationSet es2 = Expectation();
1479 EXPECT_EQ(1, es1.size());
1480 EXPECT_THAT(*(es1.begin()), Eq(Expectation()));
1481 EXPECT_THAT(es1, Eq(es2));
1484 TEST(ExpectationSetTest, InsertionWorks) {
1488 EXPECT_EQ(1, es1.size());
1489 EXPECT_THAT(*(es1.begin()), Eq(e1));
1492 Expectation e2 = EXPECT_CALL(a, DoA(1));
1494 EXPECT_EQ(2, es1.size());
1496 ExpectationSet::const_iterator it1 = es1.begin();
1497 ExpectationSet::const_iterator it2 = it1;
1499 EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.
1500 EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.
1504 TEST(ExpectationSetTest, SizeWorks) {
1506 EXPECT_EQ(0, es.size());
1508 es += Expectation();
1509 EXPECT_EQ(1, es.size());
1512 es += EXPECT_CALL(a, DoA(1));
1513 EXPECT_EQ(2, es.size());
1518 TEST(ExpectationSetTest, IsEnumerable) {
1520 EXPECT_TRUE(es.begin() == es.end());
1522 es += Expectation();
1523 ExpectationSet::const_iterator it = es.begin();
1524 EXPECT_TRUE(it != es.end());
1525 EXPECT_THAT(*it, Eq(Expectation()));
1527 EXPECT_TRUE(it == es.end());
1530 // Tests the .After() clause.
1532 TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
1535 es += EXPECT_CALL(a, DoA(1));
1536 es += EXPECT_CALL(a, DoA(2));
1537 EXPECT_CALL(a, DoA(3)).After(es);
1544 TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
1547 // The following also verifies that const Expectation objects work
1548 // too. Do not remove the const modifiers.
1549 const Expectation e1 = EXPECT_CALL(a, DoA(1));
1550 const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
1551 EXPECT_CALL(a, DoA(2)).After(e2);
1559 // Calls must be in strict order when specified so using .After().
1560 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
1565 // a.DoA(1) ==> b.DoB() ==> a.DoA(2)
1566 Expectation e1 = EXPECT_CALL(a, DoA(1));
1567 Expectation e2 = EXPECT_CALL(b, DoB()).After(e1);
1568 EXPECT_CALL(a, DoA(2)).After(e2);
1572 // May only be called after DoB().
1573 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1579 // Calls must be in strict order when specified so using .After().
1580 TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
1585 // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
1586 Expectation e1 = EXPECT_CALL(a, DoA(1));
1587 Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
1588 EXPECT_CALL(a, DoA(2)).After(e2);
1593 // May only be called after the second DoB().
1594 EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
1600 // Calls must satisfy the partial order when specified so.
1601 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
1603 ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
1607 // a.DoA(2) ==> a.ReturnResult(3)
1608 Expectation e = EXPECT_CALL(a, DoA(1));
1609 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1610 EXPECT_CALL(a, ReturnResult(3)).After(e, es);
1612 // May only be called last.
1613 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1620 // Calls must satisfy the partial order when specified so.
1621 TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
1626 // a.DoA(2) ==> a.DoA(3)
1627 Expectation e = EXPECT_CALL(a, DoA(1));
1628 const ExpectationSet es = EXPECT_CALL(a, DoA(2));
1629 EXPECT_CALL(a, DoA(3)).After(e, es);
1633 // May only be called last.
1634 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1640 // .After() can be combined with .InSequence().
1641 TEST(AfterTest, CanBeUsedWithInSequence) {
1644 Expectation e = EXPECT_CALL(a, DoA(1));
1645 EXPECT_CALL(a, DoA(2)).InSequence(s);
1646 EXPECT_CALL(a, DoA(3)).InSequence(s).After(e);
1650 // May only be after DoA(2).
1651 EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
1657 // .After() can be called multiple times.
1658 TEST(AfterTest, CanBeCalledManyTimes) {
1660 Expectation e1 = EXPECT_CALL(a, DoA(1));
1661 Expectation e2 = EXPECT_CALL(a, DoA(2));
1662 Expectation e3 = EXPECT_CALL(a, DoA(3));
1663 EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3);
1671 // .After() accepts up to 5 arguments.
1672 TEST(AfterTest, AcceptsUpToFiveArguments) {
1674 Expectation e1 = EXPECT_CALL(a, DoA(1));
1675 Expectation e2 = EXPECT_CALL(a, DoA(2));
1676 Expectation e3 = EXPECT_CALL(a, DoA(3));
1677 ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
1678 ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
1679 EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2);
1689 // .After() allows input to contain duplicated Expectations.
1690 TEST(AfterTest, AcceptsDuplicatedInput) {
1692 ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
1696 // DoA(2) ==> ReturnResult(3)
1697 Expectation e1 = EXPECT_CALL(a, DoA(1));
1698 Expectation e2 = EXPECT_CALL(a, DoA(2));
1702 EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1);
1706 // May only be after DoA(2).
1707 EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
1713 // An Expectation added to an ExpectationSet after it has been used in
1714 // an .After() has no effect.
1715 TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
1717 ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
1718 Expectation e2 = EXPECT_CALL(a, DoA(2));
1719 EXPECT_CALL(a, DoA(3)).After(es1);
1727 // Tests that Google Mock correctly handles calls to mock functions
1728 // after a mock object owning one of their pre-requisites has died.
1730 // Tests that calls that satisfy the original spec are successful.
1731 TEST(DeletingMockEarlyTest, Success1) {
1732 MockB* const b1 = new MockB;
1733 MockA* const a = new MockA;
1734 MockB* const b2 = new MockB;
1738 EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
1739 EXPECT_CALL(*a, Binary(_, _))
1741 .WillRepeatedly(Return(true));
1742 EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
1745 EXPECT_EQ(1, b1->DoB(1));
1747 // a's pre-requisite has died.
1748 EXPECT_TRUE(a->Binary(0, 1));
1750 // a's successor has died.
1751 EXPECT_TRUE(a->Binary(1, 2));
1755 // Tests that calls that satisfy the original spec are successful.
1756 TEST(DeletingMockEarlyTest, Success2) {
1757 MockB* const b1 = new MockB;
1758 MockA* const a = new MockA;
1759 MockB* const b2 = new MockB;
1763 EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
1764 EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
1765 EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
1768 delete a; // a is trivially satisfied.
1769 EXPECT_EQ(1, b1->DoB(1));
1770 EXPECT_EQ(2, b2->DoB(2));
1775 // Tests that it's OK to delete a mock object itself in its action.
1777 // Suppresses warning on unreferenced formal parameter in MSVC with
1780 #pragma warning(push)
1781 #pragma warning(disable : 4100)
1784 ACTION_P(Delete, ptr) { delete ptr; }
1787 #pragma warning(pop)
1790 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
1791 MockA* const a = new MockA;
1792 EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
1793 a->DoA(42); // This will cause a to be deleted.
1796 TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
1797 MockA* const a = new MockA;
1798 EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));
1799 a->ReturnResult(42); // This will cause a to be deleted.
1802 // Tests that calls that violate the original spec yield failures.
1803 TEST(DeletingMockEarlyTest, Failure1) {
1804 MockB* const b1 = new MockB;
1805 MockA* const a = new MockA;
1806 MockB* const b2 = new MockB;
1810 EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
1811 EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
1812 EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
1815 delete a; // a is trivially satisfied.
1816 EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call");
1817 EXPECT_EQ(1, b1->DoB(1));
1822 // Tests that calls that violate the original spec yield failures.
1823 TEST(DeletingMockEarlyTest, Failure2) {
1824 MockB* const b1 = new MockB;
1825 MockA* const a = new MockA;
1826 MockB* const b2 = new MockB;
1830 EXPECT_CALL(*b1, DoB(_));
1831 EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
1832 EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());
1835 EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called");
1836 EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call");
1837 EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call");
1842 class EvenNumberCardinality : public CardinalityInterface {
1844 // Returns true if and only if call_count calls will satisfy this
1846 bool IsSatisfiedByCallCount(int call_count) const override {
1847 return call_count % 2 == 0;
1850 // Returns true if and only if call_count calls will saturate this
1852 bool IsSaturatedByCallCount(int /* call_count */) const override {
1856 // Describes self to an ostream.
1857 void DescribeTo(::std::ostream* os) const override {
1858 *os << "called even number of times";
1862 Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }
1864 TEST(ExpectationBaseTest,
1865 AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
1866 MockA* a = new MockA;
1869 EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);
1870 EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);
1871 EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());
1875 EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
1876 EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
1879 // The following tests verify the message generated when a mock
1880 // function is called.
1882 struct Printable {};
1884 inline void operator<<(::std::ostream& os, const Printable&) {
1888 struct Unprintable {
1889 Unprintable() : value(0) {}
1897 MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
1898 const Printable& x, Unprintable y));
1899 MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
1902 MockC(const MockC&) = delete;
1903 MockC& operator=(const MockC&) = delete;
1906 class VerboseFlagPreservingFixture : public testing::Test {
1908 VerboseFlagPreservingFixture()
1909 : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}
1911 ~VerboseFlagPreservingFixture() override {
1912 GMOCK_FLAG_SET(verbose, saved_verbose_flag_);
1916 const std::string saved_verbose_flag_;
1918 VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;
1919 VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =
1923 #if GTEST_HAS_STREAM_REDIRECTION
1925 // Tests that an uninteresting mock function call on a naggy mock
1926 // generates a warning without the stack trace when
1927 // --gmock_verbose=warning is specified.
1928 TEST(FunctionCallMessageTest,
1929 UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
1930 GMOCK_FLAG_SET(verbose, kWarningVerbosity);
1933 c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1934 const std::string output = GetCapturedStdout();
1935 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1936 EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
1939 // Tests that an uninteresting mock function call on a naggy mock
1940 // generates a warning containing the stack trace when
1941 // --gmock_verbose=info is specified.
1942 TEST(FunctionCallMessageTest,
1943 UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
1944 GMOCK_FLAG_SET(verbose, kInfoVerbosity);
1947 c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1948 const std::string output = GetCapturedStdout();
1949 EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
1950 EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
1954 // We check the stack trace content in dbg-mode only, as opt-mode
1955 // may inline the call we are interested in seeing.
1957 // Verifies that a void mock function's name appears in the stack
1959 EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
1961 // Verifies that a non-void mock function's name appears in the
1965 const std::string output2 = GetCapturedStdout();
1966 EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
1971 // Tests that an uninteresting mock function call on a naggy mock
1972 // causes the function arguments and return value to be printed.
1973 TEST(FunctionCallMessageTest,
1974 UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
1975 // A non-void mock function.
1979 const std::string output1 = GetCapturedStdout();
1980 EXPECT_PRED_FORMAT2(
1982 "Uninteresting mock function call - returning default value.\n"
1983 " Function call: DoB()\n"
1986 // Makes sure the return value is printed.
1988 // A void mock function.
1991 c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
1992 const std::string output2 = GetCapturedStdout();
1995 ContainsRegex("Uninteresting mock function call - returning directly\\.\n"
1996 " Function call: VoidMethod"
1997 "\\(false, 5, \"Hi\", NULL, @.+ "
1998 "Printable, 4-byte object <00-00 00-00>\\)"));
1999 // A void function has no return value to print.
2002 // Tests how the --gmock_verbose flag affects Google Mock's output.
2004 class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
2006 // Verifies that the given Google Mock output is correct. (When
2007 // should_print is true, the output should match the given regex and
2008 // contain the given function name in the stack trace. When it's
2009 // false, the output should be empty.)
2010 void VerifyOutput(const std::string& output, bool should_print,
2011 const std::string& expected_substring,
2012 const std::string& function_name) {
2014 EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
2016 // We check the stack trace content in dbg-mode only, as opt-mode
2017 // may inline the call we are interested in seeing.
2018 EXPECT_THAT(output.c_str(), HasSubstr(function_name));
2020 // Suppresses 'unused function parameter' warnings.
2021 static_cast<void>(function_name);
2024 EXPECT_STREQ("", output.c_str());
2028 // Tests how the flag affects expected calls.
2029 void TestExpectedCall(bool should_print) {
2031 EXPECT_CALL(a, DoA(5));
2032 EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));
2034 // A void-returning function.
2037 VerifyOutput(GetCapturedStdout(), should_print,
2038 "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
2039 " Function call: DoA(5)\n"
2043 // A non-void-returning function.
2046 VerifyOutput(GetCapturedStdout(), should_print,
2047 "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
2048 " Function call: Binary(2, 1)\n"
2054 // Tests how the flag affects uninteresting calls on a naggy mock.
2055 void TestUninterestingCallOnNaggyMock(bool should_print) {
2057 const std::string note =
2058 "NOTE: You can safely ignore the above warning unless this "
2059 "call should not happen. Do not suppress it by blindly adding "
2060 "an EXPECT_CALL() if you don't mean to enforce the call. "
2062 "https://github.com/google/googletest/blob/master/docs/"
2063 "gmock_cook_book.md#"
2064 "knowing-when-to-expect for details.";
2066 // A void-returning function.
2069 VerifyOutput(GetCapturedStdout(), should_print,
2070 "\nGMOCK WARNING:\n"
2071 "Uninteresting mock function call - returning directly.\n"
2072 " Function call: DoA(5)\n" +
2076 // A non-void-returning function.
2079 VerifyOutput(GetCapturedStdout(), should_print,
2080 "\nGMOCK WARNING:\n"
2081 "Uninteresting mock function call - returning default value.\n"
2082 " Function call: Binary(2, 1)\n"
2083 " Returns: false\n" +
2089 // Tests that --gmock_verbose=info causes both expected and
2090 // uninteresting calls to be reported.
2091 TEST_F(GMockVerboseFlagTest, Info) {
2092 GMOCK_FLAG_SET(verbose, kInfoVerbosity);
2093 TestExpectedCall(true);
2094 TestUninterestingCallOnNaggyMock(true);
2097 // Tests that --gmock_verbose=warning causes uninteresting calls to be
2099 TEST_F(GMockVerboseFlagTest, Warning) {
2100 GMOCK_FLAG_SET(verbose, kWarningVerbosity);
2101 TestExpectedCall(false);
2102 TestUninterestingCallOnNaggyMock(true);
2105 // Tests that --gmock_verbose=warning causes neither expected nor
2106 // uninteresting calls to be reported.
2107 TEST_F(GMockVerboseFlagTest, Error) {
2108 GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2109 TestExpectedCall(false);
2110 TestUninterestingCallOnNaggyMock(false);
2113 // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
2114 // as --gmock_verbose=warning.
2115 TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
2116 GMOCK_FLAG_SET(verbose, "invalid"); // Treated as "warning".
2117 TestExpectedCall(false);
2118 TestUninterestingCallOnNaggyMock(true);
2121 #endif // GTEST_HAS_STREAM_REDIRECTION
2123 // A helper class that generates a failure when printed. We use it to
2124 // ensure that Google Mock doesn't print a value (even to an internal
2125 // buffer) when it is not supposed to do so.
2126 class PrintMeNot {};
2128 void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {
2129 ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "
2130 << "printed even to an internal buffer.";
2133 class LogTestHelper {
2137 MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
2140 LogTestHelper(const LogTestHelper&) = delete;
2141 LogTestHelper& operator=(const LogTestHelper&) = delete;
2144 class GMockLogTest : public VerboseFlagPreservingFixture {
2146 LogTestHelper helper_;
2149 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
2150 GMOCK_FLAG_SET(verbose, kWarningVerbosity);
2151 EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
2152 helper_.Foo(PrintMeNot()); // This is an expected call.
2155 TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
2156 GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2157 EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
2158 helper_.Foo(PrintMeNot()); // This is an expected call.
2161 TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
2162 GMOCK_FLAG_SET(verbose, kErrorVerbosity);
2163 ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));
2164 helper_.Foo(PrintMeNot()); // This should generate a warning.
2167 // Tests Mock::AllowLeak().
2169 TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
2170 MockA* a = new MockA;
2174 TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {
2175 MockA* a = new MockA;
2177 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2181 TEST(AllowLeakTest, CanBeCalledAfterOnCall) {
2182 MockA* a = new MockA;
2183 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2187 TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {
2188 MockA* a = new MockA;
2190 EXPECT_CALL(*a, DoA(_));
2194 TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {
2195 MockA* a = new MockA;
2196 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2200 TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {
2201 MockA* a = new MockA;
2202 ON_CALL(*a, DoA(_)).WillByDefault(Return());
2203 EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());
2207 // Tests that we can verify and clear a mock object's expectations
2208 // when none of its methods has expectations.
2209 TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {
2211 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2213 // There should be no expectations on the methods now, so we can
2214 // freely call them.
2215 EXPECT_EQ(0, b.DoB());
2216 EXPECT_EQ(0, b.DoB(1));
2219 // Tests that we can verify and clear a mock object's expectations
2220 // when some, but not all, of its methods have expectations *and* the
2221 // verification succeeds.
2222 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
2224 EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2226 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2228 // There should be no expectations on the methods now, so we can
2229 // freely call them.
2230 EXPECT_EQ(0, b.DoB());
2231 EXPECT_EQ(0, b.DoB(1));
2234 // Tests that we can verify and clear a mock object's expectations
2235 // when some, but not all, of its methods have expectations *and* the
2236 // verification fails.
2237 TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
2239 EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2241 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2242 "Actual: never called");
2243 ASSERT_FALSE(result);
2245 // There should be no expectations on the methods now, so we can
2246 // freely call them.
2247 EXPECT_EQ(0, b.DoB());
2248 EXPECT_EQ(0, b.DoB(1));
2251 // Tests that we can verify and clear a mock object's expectations
2252 // when all of its methods have expectations.
2253 TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
2255 EXPECT_CALL(b, DoB()).WillOnce(Return(1));
2256 EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2259 ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
2261 // There should be no expectations on the methods now, so we can
2262 // freely call them.
2263 EXPECT_EQ(0, b.DoB());
2264 EXPECT_EQ(0, b.DoB(1));
2267 // Tests that we can verify and clear a mock object's expectations
2268 // when a method has more than one expectation.
2269 TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
2271 EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));
2272 EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2275 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
2276 "Actual: never called");
2277 ASSERT_FALSE(result);
2279 // There should be no expectations on the methods now, so we can
2280 // freely call them.
2281 EXPECT_EQ(0, b.DoB());
2282 EXPECT_EQ(0, b.DoB(1));
2285 // Tests that we can call VerifyAndClearExpectations() on the same
2286 // mock object multiple times.
2287 TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
2289 EXPECT_CALL(b, DoB());
2291 Mock::VerifyAndClearExpectations(&b);
2293 EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));
2295 Mock::VerifyAndClearExpectations(&b);
2296 Mock::VerifyAndClearExpectations(&b);
2298 // There should be no expectations on the methods now, so we can
2299 // freely call them.
2300 EXPECT_EQ(0, b.DoB());
2301 EXPECT_EQ(0, b.DoB(1));
2304 // Tests that we can clear a mock object's default actions when none
2305 // of its methods has default actions.
2306 TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {
2308 // If this crashes or generates a failure, the test will catch it.
2309 Mock::VerifyAndClear(&b);
2310 EXPECT_EQ(0, b.DoB());
2313 // Tests that we can clear a mock object's default actions when some,
2314 // but not all of its methods have default actions.
2315 TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
2317 ON_CALL(b, DoB()).WillByDefault(Return(1));
2319 Mock::VerifyAndClear(&b);
2321 // Verifies that the default action of int DoB() was removed.
2322 EXPECT_EQ(0, b.DoB());
2325 // Tests that we can clear a mock object's default actions when all of
2326 // its methods have default actions.
2327 TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
2329 ON_CALL(b, DoB()).WillByDefault(Return(1));
2330 ON_CALL(b, DoB(_)).WillByDefault(Return(2));
2332 Mock::VerifyAndClear(&b);
2334 // Verifies that the default action of int DoB() was removed.
2335 EXPECT_EQ(0, b.DoB());
2337 // Verifies that the default action of int DoB(int) was removed.
2338 EXPECT_EQ(0, b.DoB(0));
2341 // Tests that we can clear a mock object's default actions when a
2342 // method has more than one ON_CALL() set on it.
2343 TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
2345 ON_CALL(b, DoB(0)).WillByDefault(Return(1));
2346 ON_CALL(b, DoB(_)).WillByDefault(Return(2));
2348 Mock::VerifyAndClear(&b);
2350 // Verifies that the default actions (there are two) of int DoB(int)
2352 EXPECT_EQ(0, b.DoB(0));
2353 EXPECT_EQ(0, b.DoB(1));
2356 // Tests that we can call VerifyAndClear() on a mock object multiple
2358 TEST(VerifyAndClearTest, CanCallManyTimes) {
2360 ON_CALL(b, DoB()).WillByDefault(Return(1));
2361 Mock::VerifyAndClear(&b);
2362 Mock::VerifyAndClear(&b);
2364 ON_CALL(b, DoB(_)).WillByDefault(Return(1));
2365 Mock::VerifyAndClear(&b);
2367 EXPECT_EQ(0, b.DoB());
2368 EXPECT_EQ(0, b.DoB(1));
2371 // Tests that VerifyAndClear() works when the verification succeeds.
2372 TEST(VerifyAndClearTest, Success) {
2374 ON_CALL(b, DoB()).WillByDefault(Return(1));
2375 EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));
2379 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2381 // There should be no expectations on the methods now, so we can
2382 // freely call them.
2383 EXPECT_EQ(0, b.DoB());
2384 EXPECT_EQ(0, b.DoB(1));
2387 // Tests that VerifyAndClear() works when the verification fails.
2388 TEST(VerifyAndClearTest, Failure) {
2390 ON_CALL(b, DoB(_)).WillByDefault(Return(1));
2391 EXPECT_CALL(b, DoB()).WillOnce(Return(2));
2395 EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
2396 "Actual: never called");
2397 ASSERT_FALSE(result);
2399 // There should be no expectations on the methods now, so we can
2400 // freely call them.
2401 EXPECT_EQ(0, b.DoB());
2402 EXPECT_EQ(0, b.DoB(1));
2405 // Tests that VerifyAndClear() works when the default actions and
2406 // expectations are set on a const mock object.
2407 TEST(VerifyAndClearTest, Const) {
2409 ON_CALL(Const(b), DoB()).WillByDefault(Return(1));
2411 EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));
2415 ASSERT_TRUE(Mock::VerifyAndClear(&b));
2417 // There should be no expectations on the methods now, so we can
2418 // freely call them.
2419 EXPECT_EQ(0, b.DoB());
2420 EXPECT_EQ(0, b.DoB(1));
2423 // Tests that we can set default actions and expectations on a mock
2424 // object after VerifyAndClear() has been called on it.
2425 TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
2427 ON_CALL(b, DoB()).WillByDefault(Return(1));
2428 EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
2431 Mock::VerifyAndClear(&b);
2433 EXPECT_CALL(b, DoB()).WillOnce(Return(3));
2434 ON_CALL(b, DoB(_)).WillByDefault(Return(4));
2436 EXPECT_EQ(3, b.DoB());
2437 EXPECT_EQ(4, b.DoB(1));
2440 // Tests that calling VerifyAndClear() on one mock object does not
2441 // affect other mock objects (either of the same type or not).
2442 TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
2447 ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
2448 EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));
2450 ON_CALL(b1, DoB()).WillByDefault(Return(1));
2451 EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));
2453 ON_CALL(b2, DoB()).WillByDefault(Return(3));
2454 EXPECT_CALL(b2, DoB(_));
2457 Mock::VerifyAndClear(&b2);
2459 // Verifies that the default actions and expectations of a and b1
2460 // are still in effect.
2461 EXPECT_TRUE(a.Binary(0, 0));
2462 EXPECT_FALSE(a.Binary(0, 0));
2464 EXPECT_EQ(1, b1.DoB());
2465 EXPECT_EQ(2, b1.DoB(0));
2468 TEST(VerifyAndClearTest,
2469 DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {
2470 std::shared_ptr<MockA> a(new MockA);
2471 ReferenceHoldingMock test_mock;
2473 // EXPECT_CALL stores a reference to a inside test_mock.
2474 EXPECT_CALL(test_mock, AcceptReference(_))
2475 .WillRepeatedly(SetArgPointee<0>(a));
2477 // Throw away the reference to the mock that we have in a. After this, the
2478 // only reference to it is stored by test_mock.
2481 // When test_mock goes out of scope, it destroys the last remaining reference
2482 // to the mock object originally pointed to by a. This will cause the MockA
2483 // destructor to be called from inside the ReferenceHoldingMock destructor.
2484 // The state of all mocks is protected by a single global lock, but there
2485 // should be no deadlock.
2488 TEST(VerifyAndClearTest,
2489 DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
2490 std::shared_ptr<MockA> a(new MockA);
2491 ReferenceHoldingMock test_mock;
2493 // ON_CALL stores a reference to a inside test_mock.
2494 ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));
2496 // Throw away the reference to the mock that we have in a. After this, the
2497 // only reference to it is stored by test_mock.
2500 // When test_mock goes out of scope, it destroys the last remaining reference
2501 // to the mock object originally pointed to by a. This will cause the MockA
2502 // destructor to be called from inside the ReferenceHoldingMock destructor.
2503 // The state of all mocks is protected by a single global lock, but there
2504 // should be no deadlock.
2507 // Tests that a mock function's action can call a mock function
2508 // (either the same function or a different one) either as an explicit
2509 // action or as a default action without causing a dead lock. It
2510 // verifies that the action is not performed inside the critical
2512 TEST(SynchronizationTest, CanCallMockMethodInAction) {
2515 ON_CALL(a, DoA(_)).WillByDefault(
2516 IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));
2517 EXPECT_CALL(a, DoA(1));
2518 EXPECT_CALL(a, DoA(1))
2519 .WillOnce(Invoke(&a, &MockA::DoA))
2520 .RetiresOnSaturation();
2521 EXPECT_CALL(c, NonVoidMethod());
2524 // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
2525 // which will in turn match the first EXPECT_CALL() and trigger a call to
2526 // c.NonVoidMethod() that was specified by the ON_CALL() since the first
2527 // EXPECT_CALL() did not specify an action.
2530 TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {
2533 ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));
2534 int do_a_47_arg0 = 0;
2535 ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));
2538 EXPECT_THAT(do_a_arg0, 17);
2539 EXPECT_THAT(do_a_47_arg0, 0);
2541 EXPECT_THAT(do_a_arg0, 17);
2542 EXPECT_THAT(do_a_47_arg0, 47);
2544 ON_CALL(a, Binary).WillByDefault(Return(true));
2545 ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));
2546 EXPECT_THAT(a.Binary(14, 17), true);
2547 EXPECT_THAT(a.Binary(17, 14), false);
2550 TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {
2552 ON_CALL(b, DoB()).WillByDefault(Return(9));
2553 ON_CALL(b, DoB(5)).WillByDefault(Return(11));
2555 EXPECT_THAT(b.DoB(), 9);
2556 EXPECT_THAT(b.DoB(1), 0); // default value
2557 EXPECT_THAT(b.DoB(5), 11);
2560 struct MockWithConstMethods {
2562 MOCK_CONST_METHOD1(Foo, int(int));
2563 MOCK_CONST_METHOD2(Bar, int(int, const char*));
2566 TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {
2567 MockWithConstMethods mock;
2568 ON_CALL(mock, Foo).WillByDefault(Return(7));
2569 ON_CALL(mock, Bar).WillByDefault(Return(33));
2571 EXPECT_THAT(mock.Foo(17), 7);
2572 EXPECT_THAT(mock.Bar(27, "purple"), 33);
2575 class MockConstOverload {
2577 MOCK_METHOD1(Overloaded, int(int));
2578 MOCK_CONST_METHOD1(Overloaded, int(int));
2581 TEST(ParameterlessExpectationsTest,
2582 CanSetExpectationsForConstOverloadedMethods) {
2583 MockConstOverload mock;
2584 ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));
2585 ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));
2586 ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));
2587 ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));
2589 EXPECT_THAT(mock.Overloaded(1), 7);
2590 EXPECT_THAT(mock.Overloaded(5), 9);
2591 EXPECT_THAT(mock.Overloaded(7), 7);
2593 const MockConstOverload& const_mock = mock;
2594 EXPECT_THAT(const_mock.Overloaded(1), 0);
2595 EXPECT_THAT(const_mock.Overloaded(5), 11);
2596 EXPECT_THAT(const_mock.Overloaded(7), 13);
2600 } // namespace testing
2602 // Allows the user to define their own main and then invoke gmock_main
2603 // from it. This might be necessary on some platforms which require
2604 // specific setup and teardown.
2605 #if GMOCK_RENAME_MAIN
2606 int gmock_main(int argc, char** argv) {
2608 int main(int argc, char** argv) {
2609 #endif // GMOCK_RENAME_MAIN
2610 testing::InitGoogleMock(&argc, argv);
2611 // Ensures that the tests pass no matter what value of
2612 // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
2613 GMOCK_FLAG_SET(catch_leaked_mocks, true);
2614 GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);
2616 return RUN_ALL_TESTS();