Path: blob/main/contrib/googletest/googlemock/test/gmock-spec-builders_test.cc
48255 views
// Copyright 2007, Google Inc.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above10// copyright notice, this list of conditions and the following disclaimer11// in the documentation and/or other materials provided with the12// distribution.13// * Neither the name of Google Inc. nor the names of its14// contributors may be used to endorse or promote products derived from15// this software without specific prior written permission.16//17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS18// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT19// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR20// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT21// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,22// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT23// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY25// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT26// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE27// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2829// Google Mock - a framework for writing C++ mock classes.30//31// This file tests the spec builder syntax.3233#include "gmock/gmock-spec-builders.h"3435#include <memory>36#include <ostream> // NOLINT37#include <sstream>38#include <string>39#include <type_traits>4041#include "gmock/gmock.h"42#include "gmock/internal/gmock-port.h"43#include "gtest/gtest-spi.h"44#include "gtest/gtest.h"45#include "gtest/internal/gtest-port.h"4647namespace testing {48namespace {4950using ::testing::internal::FormatFileLocation;51using ::testing::internal::kAllow;52using ::testing::internal::kErrorVerbosity;53using ::testing::internal::kFail;54using ::testing::internal::kInfoVerbosity;55using ::testing::internal::kWarn;56using ::testing::internal::kWarningVerbosity;5758#if GTEST_HAS_STREAM_REDIRECTION59using ::testing::internal::CaptureStdout;60using ::testing::internal::GetCapturedStdout;61#endif6263class Incomplete {64};6566class MockIncomplete {67public:68// This line verifies that a mock method can take a by-reference69// argument of an incomplete type.70MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));71};7273// Tells Google Mock how to print a value of type Incomplete.74void PrintTo(const Incomplete& x, ::std::ostream* os);7576TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {77// Even though this mock class contains a mock method that takes78// by-reference an argument whose type is incomplete, we can still79// use the mock, as long as Google Mock knows how to print the80// argument.81MockIncomplete incomplete;82EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber());83}8485// The definition of the printer for the argument type doesn't have to86// be visible where the mock is used.87void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {88*os << "incomplete";89}9091class Result {};9293// A type that's not default constructible.94class NonDefaultConstructible {95public:96explicit NonDefaultConstructible(int /* dummy */) {}97};9899class MockA {100public:101MockA() = default;102103MOCK_METHOD1(DoA, void(int n));104MOCK_METHOD1(ReturnResult, Result(int n));105MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());106MOCK_METHOD2(Binary, bool(int x, int y));107MOCK_METHOD2(ReturnInt, int(int x, int y));108109private:110MockA(const MockA&) = delete;111MockA& operator=(const MockA&) = delete;112};113114class MockB {115public:116MockB() = default;117118MOCK_CONST_METHOD0(DoB, int()); // NOLINT119MOCK_METHOD1(DoB, int(int n)); // NOLINT120121private:122MockB(const MockB&) = delete;123MockB& operator=(const MockB&) = delete;124};125126class ReferenceHoldingMock {127public:128ReferenceHoldingMock() = default;129130MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));131132private:133ReferenceHoldingMock(const ReferenceHoldingMock&) = delete;134ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete;135};136137// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro138// redefining a mock method name. This could happen, for example, when139// the tested code #includes Win32 API headers which define many APIs140// as macros, e.g. #define TextOut TextOutW.141142#define Method MethodW143144class CC {145public:146virtual ~CC() = default;147virtual int Method() = 0;148};149class MockCC : public CC {150public:151MockCC() = default;152153MOCK_METHOD0(Method, int());154155private:156MockCC(const MockCC&) = delete;157MockCC& operator=(const MockCC&) = delete;158};159160// Tests that a method with expanded name compiles.161TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {162MockCC cc;163ON_CALL(cc, Method());164}165166// Tests that the method with expanded name not only compiles but runs167// and returns a correct value, too.168TEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {169MockCC cc;170ON_CALL(cc, Method()).WillByDefault(Return(42));171EXPECT_EQ(42, cc.Method());172}173174// Tests that a method with expanded name compiles.175TEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {176MockCC cc;177EXPECT_CALL(cc, Method());178cc.Method();179}180181// Tests that it works, too.182TEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {183MockCC cc;184EXPECT_CALL(cc, Method()).WillOnce(Return(42));185EXPECT_EQ(42, cc.Method());186}187188#undef Method // Done with macro redefinition tests.189190// Tests that ON_CALL evaluates its arguments exactly once as promised191// by Google Mock.192TEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {193MockA a;194MockA* pa = &a;195196ON_CALL(*pa++, DoA(_));197EXPECT_EQ(&a + 1, pa);198}199200TEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {201MockA a;202int n = 0;203204ON_CALL(a, DoA(n++));205EXPECT_EQ(1, n);206}207208// Tests that the syntax of ON_CALL() is enforced at run time.209210TEST(OnCallSyntaxTest, WithIsOptional) {211MockA a;212213ON_CALL(a, DoA(5)).WillByDefault(Return());214ON_CALL(a, DoA(_)).With(_).WillByDefault(Return());215}216217TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {218MockA a;219220EXPECT_NONFATAL_FAILURE(221{ // NOLINT222ON_CALL(a, ReturnResult(_))223.With(_)224.With(_)225.WillByDefault(Return(Result()));226},227".With() cannot appear more than once in an ON_CALL()");228}229230TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {231MockA a;232233EXPECT_DEATH_IF_SUPPORTED(234{235ON_CALL(a, DoA(5));236a.DoA(5);237},238"");239}240241TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {242MockA a;243244EXPECT_NONFATAL_FAILURE(245{ // NOLINT246ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return());247},248".WillByDefault() must appear exactly once in an ON_CALL()");249}250251// Tests that EXPECT_CALL evaluates its arguments exactly once as252// promised by Google Mock.253TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {254MockA a;255MockA* pa = &a;256257EXPECT_CALL(*pa++, DoA(_));258a.DoA(0);259EXPECT_EQ(&a + 1, pa);260}261262TEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {263MockA a;264int n = 0;265266EXPECT_CALL(a, DoA(n++));267a.DoA(0);268EXPECT_EQ(1, n);269}270271// Tests that the syntax of EXPECT_CALL() is enforced at run time.272273TEST(ExpectCallSyntaxTest, WithIsOptional) {274MockA a;275276EXPECT_CALL(a, DoA(5)).Times(0);277EXPECT_CALL(a, DoA(6)).With(_).Times(0);278}279280TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {281MockA a;282283EXPECT_NONFATAL_FAILURE(284{ // NOLINT285EXPECT_CALL(a, DoA(6)).With(_).With(_);286},287".With() cannot appear more than once in an EXPECT_CALL()");288289a.DoA(6);290}291292TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {293MockA a;294295EXPECT_NONFATAL_FAILURE(296{ // NOLINT297EXPECT_CALL(a, DoA(1)).Times(1).With(_);298},299".With() must be the first clause in an EXPECT_CALL()");300301a.DoA(1);302303EXPECT_NONFATAL_FAILURE(304{ // NOLINT305EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_);306},307".With() must be the first clause in an EXPECT_CALL()");308309a.DoA(2);310}311312TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {313MockA a;314315EXPECT_CALL(a, DoA(1)).WillOnce(Return());316317EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());318319a.DoA(1);320a.DoA(2);321a.DoA(2);322}323324TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {325MockA a;326327EXPECT_NONFATAL_FAILURE(328{ // NOLINT329EXPECT_CALL(a, DoA(1)).Times(1).Times(2);330},331".Times() cannot appear more than once in an EXPECT_CALL()");332333a.DoA(1);334a.DoA(1);335}336337TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {338MockA a;339Sequence s;340341EXPECT_NONFATAL_FAILURE(342{ // NOLINT343EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1);344},345".Times() may only appear *before* ");346347a.DoA(1);348}349350TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {351MockA a;352Sequence s;353354EXPECT_CALL(a, DoA(1));355EXPECT_CALL(a, DoA(2)).InSequence(s);356357a.DoA(1);358a.DoA(2);359}360361TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {362MockA a;363Sequence s1, s2;364365EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1);366367a.DoA(1);368}369370TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {371MockA a;372Sequence s;373374Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber());375EXPECT_NONFATAL_FAILURE(376{ // NOLINT377EXPECT_CALL(a, DoA(2)).After(e).InSequence(s);378},379".InSequence() cannot appear after ");380381a.DoA(2);382}383384TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {385MockA a;386Sequence s;387388EXPECT_NONFATAL_FAILURE(389{ // NOLINT390EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s);391},392".InSequence() cannot appear after ");393394a.DoA(1);395}396397TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {398MockA a;399400Expectation e = EXPECT_CALL(a, DoA(1));401EXPECT_NONFATAL_FAILURE(402{ EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); },403".After() cannot appear after ");404405a.DoA(1);406a.DoA(2);407}408409TEST(ExpectCallSyntaxTest, WillIsOptional) {410MockA a;411412EXPECT_CALL(a, DoA(1));413EXPECT_CALL(a, DoA(2)).WillOnce(Return());414415a.DoA(1);416a.DoA(2);417}418419TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {420MockA a;421422EXPECT_CALL(a, DoA(1))423.Times(AnyNumber())424.WillOnce(Return())425.WillOnce(Return())426.WillOnce(Return());427}428429TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {430MockA a;431432EXPECT_NONFATAL_FAILURE(433{ // NOLINT434EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return());435},436".WillOnce() cannot appear after ");437438a.DoA(1);439}440441TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {442MockA a;443444EXPECT_CALL(a, DoA(1)).WillOnce(Return());445EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());446447a.DoA(1);448a.DoA(2);449a.DoA(2);450}451452TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {453MockA a;454455EXPECT_NONFATAL_FAILURE(456{ // NOLINT457EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly(458Return());459},460".WillRepeatedly() cannot appear more than once in an "461"EXPECT_CALL()");462}463464TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {465MockA a;466467EXPECT_NONFATAL_FAILURE(468{ // NOLINT469EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return());470},471".WillRepeatedly() cannot appear after ");472}473474TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {475MockA a;476477EXPECT_CALL(a, DoA(1));478EXPECT_CALL(a, DoA(1)).RetiresOnSaturation();479480a.DoA(1);481a.DoA(1);482}483484TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {485MockA a;486487EXPECT_NONFATAL_FAILURE(488{ // NOLINT489EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation();490},491".RetiresOnSaturation() cannot appear more than once");492493a.DoA(1);494}495496TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {497{498MockA a;499EXPECT_CALL(a, DoA(1));500a.DoA(1);501}502EXPECT_NONFATAL_FAILURE(503{ // NOLINT504MockA a;505EXPECT_CALL(a, DoA(1));506},507"to be called once");508EXPECT_NONFATAL_FAILURE(509{ // NOLINT510MockA a;511EXPECT_CALL(a, DoA(1));512a.DoA(1);513a.DoA(1);514},515"to be called once");516}517518#if GTEST_HAS_STREAM_REDIRECTION519520// Tests that Google Mock doesn't print a warning when the number of521// WillOnce() is adequate.522TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {523CaptureStdout();524{525MockB b;526527// It's always fine to omit WillOnce() entirely.528EXPECT_CALL(b, DoB()).Times(0);529EXPECT_CALL(b, DoB(1)).Times(AtMost(1));530EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1));531532// It's fine for the number of WillOnce()s to equal the upper bound.533EXPECT_CALL(b, DoB(3))534.Times(Between(1, 2))535.WillOnce(Return(1))536.WillOnce(Return(2));537538// It's fine for the number of WillOnce()s to be smaller than the539// upper bound when there is a WillRepeatedly().540EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly(541Return(2));542543// Satisfies the above expectations.544b.DoB(2);545b.DoB(3);546}547EXPECT_STREQ("", GetCapturedStdout().c_str());548}549550// Tests that Google Mock warns on having too many actions in an551// expectation compared to its cardinality.552TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {553CaptureStdout();554{555MockB b;556557// Warns when the number of WillOnce()s is larger than the upper bound.558EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); // #1559EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce(560Return(2)); // #2561EXPECT_CALL(b, DoB(1))562.Times(1)563.WillOnce(Return(1))564.WillOnce(Return(2))565.RetiresOnSaturation(); // #3566567// Warns when the number of WillOnce()s equals the upper bound and568// there is a WillRepeatedly().569EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); // #4570EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly(571Return(2)); // #5572573// Satisfies the above expectations.574b.DoB(1);575b.DoB(2);576}577const std::string output = GetCapturedStdout();578EXPECT_PRED_FORMAT2(IsSubstring,579"Too many actions specified in EXPECT_CALL(b, DoB())...\n"580"Expected to be never called, but has 1 WillOnce().",581output); // #1582EXPECT_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.",586output); // #2587EXPECT_PRED_FORMAT2(588IsSubstring,589"Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"590"Expected to be called once, but has 2 WillOnce()s.",591output); // #3592EXPECT_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().",596output); // #4597EXPECT_PRED_FORMAT2(598IsSubstring,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().",602output); // #5603}604605// Tests that Google Mock warns on having too few actions in an606// expectation compared to its cardinality.607TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {608MockB b;609610EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1));611612CaptureStdout();613b.DoB();614const std::string output = GetCapturedStdout();615EXPECT_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().",619output);620b.DoB();621}622623TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {624int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);625626GMOCK_FLAG_SET(default_mock_behavior, kAllow);627CaptureStdout();628{629MockA a;630a.DoA(0);631}632std::string output = GetCapturedStdout();633EXPECT_TRUE(output.empty()) << output;634635GMOCK_FLAG_SET(default_mock_behavior, kWarn);636CaptureStdout();637{638MockA a;639a.DoA(0);640}641std::string warning_output = GetCapturedStdout();642EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);643EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",644warning_output);645646GMOCK_FLAG_SET(default_mock_behavior, kFail);647EXPECT_NONFATAL_FAILURE(648{649MockA a;650a.DoA(0);651},652"Uninteresting mock function call");653654// Out of bounds values are converted to kWarn655GMOCK_FLAG_SET(default_mock_behavior, -1);656CaptureStdout();657{658MockA a;659a.DoA(0);660}661warning_output = GetCapturedStdout();662EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);663EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",664warning_output);665GMOCK_FLAG_SET(default_mock_behavior, 3);666CaptureStdout();667{668MockA a;669a.DoA(0);670}671warning_output = GetCapturedStdout();672EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);673EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",674warning_output);675676GMOCK_FLAG_SET(default_mock_behavior, original_behavior);677}678679#endif // GTEST_HAS_STREAM_REDIRECTION680681// Tests the semantics of ON_CALL().682683// Tests that the built-in default action is taken when no ON_CALL()684// is specified.685TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {686MockB b;687EXPECT_CALL(b, DoB());688689EXPECT_EQ(0, b.DoB());690}691692// Tests that the built-in default action is taken when no ON_CALL()693// matches the invocation.694TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {695MockB b;696ON_CALL(b, DoB(1)).WillByDefault(Return(1));697EXPECT_CALL(b, DoB(_));698699EXPECT_EQ(0, b.DoB(2));700}701702// Tests that the last matching ON_CALL() action is taken.703TEST(OnCallTest, PicksLastMatchingOnCall) {704MockB b;705ON_CALL(b, DoB(_)).WillByDefault(Return(3));706ON_CALL(b, DoB(2)).WillByDefault(Return(2));707ON_CALL(b, DoB(1)).WillByDefault(Return(1));708EXPECT_CALL(b, DoB(_));709710EXPECT_EQ(2, b.DoB(2));711}712713// Tests the semantics of EXPECT_CALL().714715// Tests that any call is allowed when no EXPECT_CALL() is specified.716TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {717MockB b;718EXPECT_CALL(b, DoB());719// There is no expectation on DoB(int).720721b.DoB();722723// DoB(int) can be called any number of times.724b.DoB(1);725b.DoB(2);726}727728// Tests that the last matching EXPECT_CALL() fires.729TEST(ExpectCallTest, PicksLastMatchingExpectCall) {730MockB b;731EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2));732EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1));733734EXPECT_EQ(1, b.DoB(1));735}736737// Tests lower-bound violation.738TEST(ExpectCallTest, CatchesTooFewCalls) {739EXPECT_NONFATAL_FAILURE(740{ // NOLINT741MockB b;742EXPECT_CALL(b, DoB(5)).Description("DoB Method").Times(AtLeast(2));743744b.DoB(5);745},746"Actual function \"DoB Method\" call count "747"doesn't match EXPECT_CALL(b, DoB(5))...\n"748" Expected: to be called at least twice\n"749" Actual: called once - unsatisfied and active");750}751752// Tests that the cardinality can be inferred when no Times(...) is753// specified.754TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {755{756MockB b;757EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));758759EXPECT_EQ(1, b.DoB());760EXPECT_EQ(2, b.DoB());761}762763EXPECT_NONFATAL_FAILURE(764{ // NOLINT765MockB b;766EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));767768EXPECT_EQ(1, b.DoB());769},770"to be called twice");771772{ // NOLINT773MockB b;774EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));775776EXPECT_EQ(1, b.DoB());777EXPECT_EQ(2, b.DoB());778EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");779}780}781782TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {783{784MockB b;785EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));786787EXPECT_EQ(1, b.DoB());788}789790{ // NOLINT791MockB b;792EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));793794EXPECT_EQ(1, b.DoB());795EXPECT_EQ(2, b.DoB());796EXPECT_EQ(2, b.DoB());797}798799EXPECT_NONFATAL_FAILURE(800{ // NOLINT801MockB b;802EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));803},804"to be called at least once");805}806807#if defined(GTEST_INTERNAL_CPLUSPLUS_LANG) && \808GTEST_INTERNAL_CPLUSPLUS_LANG >= 201703L809810// It should be possible to return a non-moveable type from a mock action in811// C++17 and above, where it's guaranteed that such a type can be initialized812// from a prvalue returned from a function.813TEST(ExpectCallTest, NonMoveableType) {814// Define a non-moveable result type.815struct NonMoveableStruct {816explicit NonMoveableStruct(int x_in) : x(x_in) {}817NonMoveableStruct(NonMoveableStruct&&) = delete;818819int x;820};821822static_assert(!std::is_move_constructible_v<NonMoveableStruct>);823static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);824825static_assert(!std::is_move_assignable_v<NonMoveableStruct>);826static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);827828// We should be able to use a callable that returns that result as both a829// OnceAction and an Action, whether the callable ignores arguments or not.830const auto return_17 = [] { return NonMoveableStruct(17); };831832static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});833static_cast<void>(Action<NonMoveableStruct()>{return_17});834835static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});836static_cast<void>(Action<NonMoveableStruct(int)>{return_17});837838// It should be possible to return the result end to end through an839// EXPECT_CALL statement, with both WillOnce and WillRepeatedly.840MockFunction<NonMoveableStruct()> mock;841EXPECT_CALL(mock, Call) //842.WillOnce(return_17) //843.WillRepeatedly(return_17);844845EXPECT_EQ(17, mock.AsStdFunction()().x);846EXPECT_EQ(17, mock.AsStdFunction()().x);847EXPECT_EQ(17, mock.AsStdFunction()().x);848}849850#endif // C++17 and above851852// Tests that the n-th action is taken for the n-th matching853// invocation.854TEST(ExpectCallTest, NthMatchTakesNthAction) {855MockB b;856EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(857Return(3));858859EXPECT_EQ(1, b.DoB());860EXPECT_EQ(2, b.DoB());861EXPECT_EQ(3, b.DoB());862}863864// Tests that the WillRepeatedly() action is taken when the WillOnce(...)865// list is exhausted.866TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {867MockB b;868EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));869870EXPECT_EQ(1, b.DoB());871EXPECT_EQ(2, b.DoB());872EXPECT_EQ(2, b.DoB());873}874875#if GTEST_HAS_STREAM_REDIRECTION876877// Tests that the default action is taken when the WillOnce(...) list is878// exhausted and there is no WillRepeatedly().879TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {880MockB b;881EXPECT_CALL(b, DoB(_)).Times(1);882EXPECT_CALL(b, DoB())883.Times(AnyNumber())884.WillOnce(Return(1))885.WillOnce(Return(2));886887CaptureStdout();888EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the889// expectation has no action clause at all.890EXPECT_EQ(1, b.DoB());891EXPECT_EQ(2, b.DoB());892const std::string output1 = GetCapturedStdout();893EXPECT_STREQ("", output1.c_str());894895CaptureStdout();896EXPECT_EQ(0, b.DoB());897EXPECT_EQ(0, b.DoB());898const std::string output2 = GetCapturedStdout();899EXPECT_THAT(output2.c_str(),900HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"901"Called 3 times, but only 2 WillOnce()s are specified"902" - returning default value."));903EXPECT_THAT(output2.c_str(),904HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"905"Called 4 times, but only 2 WillOnce()s are specified"906" - returning default value."));907}908909TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) {910MockB b;911std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);912EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));913914EXPECT_EQ(1, b.DoB());915916CaptureStdout();917EXPECT_EQ(0, b.DoB());918const std::string output = GetCapturedStdout();919// The warning message should contain the call location.920EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);921}922923TEST(FunctionMockerMessageTest,924ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {925std::string on_call_location;926CaptureStdout();927{928NaggyMock<MockB> b;929on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);930ON_CALL(b, DoB(_)).WillByDefault(Return(0));931b.DoB(0);932}933EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());934}935936#endif // GTEST_HAS_STREAM_REDIRECTION937938// Tests that an uninteresting call performs the default action.939TEST(UninterestingCallTest, DoesDefaultAction) {940// When there is an ON_CALL() statement, the action specified by it941// should be taken.942MockA a;943ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));944EXPECT_TRUE(a.Binary(1, 2));945946// When there is no ON_CALL(), the default value for the return type947// should be returned.948MockB b;949EXPECT_EQ(0, b.DoB());950}951952// Tests that an unexpected call performs the default action.953TEST(UnexpectedCallTest, DoesDefaultAction) {954// When there is an ON_CALL() statement, the action specified by it955// should be taken.956MockA a;957ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));958EXPECT_CALL(a, Binary(0, 0));959a.Binary(0, 0);960bool result = false;961EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),962"Unexpected mock function call");963EXPECT_TRUE(result);964965// When there is no ON_CALL(), the default value for the return type966// should be returned.967MockB b;968EXPECT_CALL(b, DoB(0)).Times(0);969int n = -1;970EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call");971EXPECT_EQ(0, n);972}973974// Tests that when an unexpected void function generates the right975// failure message.976TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {977// First, tests the message when there is only one EXPECT_CALL().978MockA a1;979EXPECT_CALL(a1, DoA(1));980a1.DoA(1);981// Ideally we should match the failure message against a regex, but982// EXPECT_NONFATAL_FAILURE doesn't support that, so we test for983// multiple sub-strings instead.984EXPECT_NONFATAL_FAILURE(985a1.DoA(9),986"Unexpected mock function call - returning directly.\n"987" Function call: DoA(9)\n"988"Google Mock tried the following 1 expectation, but it didn't match:");989EXPECT_NONFATAL_FAILURE(990a1.DoA(9),991" Expected arg #0: is equal to 1\n"992" Actual: 9\n"993" Expected: to be called once\n"994" Actual: called once - saturated and active");995996// Next, tests the message when there are more than one EXPECT_CALL().997MockA a2;998EXPECT_CALL(a2, DoA(1));999EXPECT_CALL(a2, DoA(3));1000a2.DoA(1);1001EXPECT_NONFATAL_FAILURE(1002a2.DoA(2),1003"Unexpected mock function call - returning directly.\n"1004" Function call: DoA(2)\n"1005"Google Mock tried the following 2 expectations, but none matched:");1006EXPECT_NONFATAL_FAILURE(1007a2.DoA(2),1008"tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"1009" Expected arg #0: is equal to 1\n"1010" Actual: 2\n"1011" Expected: to be called once\n"1012" Actual: called once - saturated and active");1013EXPECT_NONFATAL_FAILURE(1014a2.DoA(2),1015"tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"1016" Expected arg #0: is equal to 3\n"1017" Actual: 2\n"1018" Expected: to be called once\n"1019" Actual: never called - unsatisfied and active");1020a2.DoA(3);1021}10221023// Tests that an unexpected non-void function generates the right1024// failure message.1025TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {1026MockB b1;1027EXPECT_CALL(b1, DoB(1));1028b1.DoB(1);1029EXPECT_NONFATAL_FAILURE(1030b1.DoB(2),1031"Unexpected mock function call - returning default value.\n"1032" Function call: DoB(2)\n"1033" Returns: 0\n"1034"Google Mock tried the following 1 expectation, but it didn't match:");1035EXPECT_NONFATAL_FAILURE(1036b1.DoB(2),1037" Expected arg #0: is equal to 1\n"1038" Actual: 2\n"1039" Expected: to be called once\n"1040" Actual: called once - saturated and active");1041}10421043// Tests that Google Mock explains that an retired expectation doesn't1044// match the call.1045TEST(UnexpectedCallTest, RetiredExpectation) {1046MockB b;1047EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();10481049b.DoB(1);1050EXPECT_NONFATAL_FAILURE(b.DoB(1),1051" Expected: the expectation is active\n"1052" Actual: it is retired");1053}10541055// Tests that Google Mock explains that an expectation that doesn't1056// match the arguments doesn't match the call.1057TEST(UnexpectedCallTest, UnmatchedArguments) {1058MockB b;1059EXPECT_CALL(b, DoB(1));10601061EXPECT_NONFATAL_FAILURE(b.DoB(2),1062" Expected arg #0: is equal to 1\n"1063" Actual: 2\n");1064b.DoB(1);1065}10661067// Tests that Google Mock explains that an expectation with1068// unsatisfied pre-requisites doesn't match the call.1069TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {1070Sequence s1, s2;1071MockB b;1072EXPECT_CALL(b, DoB(1)).InSequence(s1);1073EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);1074EXPECT_CALL(b, DoB(3)).InSequence(s2);1075EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);10761077::testing::TestPartResultArray failures;1078{1079::testing::ScopedFakeTestPartResultReporter reporter(&failures);1080b.DoB(4);1081// Now 'failures' contains the Google Test failures generated by1082// the above statement.1083}10841085// There should be one non-fatal failure.1086ASSERT_EQ(1, failures.size());1087const ::testing::TestPartResult& r = failures.GetTestPartResult(0);1088EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());10891090// Verifies that the failure message contains the two unsatisfied1091// pre-requisites but not the satisfied one.1092#ifdef GTEST_USES_POSIX_RE1093EXPECT_THAT(r.message(),1094ContainsRegex(1095// POSIX RE doesn't understand the (?s) prefix, but has no1096// trouble with (.|\n).1097"the following immediate pre-requisites are not satisfied:\n"1098"(.|\n)*: pre-requisite #0\n"1099"(.|\n)*: pre-requisite #1"));1100#else1101// We can only use Google Test's own simple regex.1102EXPECT_THAT(r.message(),1103ContainsRegex(1104"the following immediate pre-requisites are not satisfied:"));1105EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));1106EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));1107#endif // GTEST_USES_POSIX_RE11081109b.DoB(1);1110b.DoB(3);1111b.DoB(4);1112}11131114TEST(UndefinedReturnValueTest,1115ReturnValueIsMandatoryWhenNotDefaultConstructible) {1116MockA a;1117// FIXME: We should really verify the output message,1118// but we cannot yet due to that EXPECT_DEATH only captures stderr1119// while Google Mock logs to stdout.1120#if GTEST_HAS_EXCEPTIONS1121EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());1122#else1123EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");1124#endif1125}11261127// Tests that an excessive call (one whose arguments match the1128// matchers but is called too many times) performs the default action.1129TEST(ExcessiveCallTest, DoesDefaultAction) {1130// When there is an ON_CALL() statement, the action specified by it1131// should be taken.1132MockA a;1133ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));1134EXPECT_CALL(a, Binary(0, 0));1135a.Binary(0, 0);1136bool result = false;1137EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),1138"Mock function called more times than expected");1139EXPECT_TRUE(result);11401141// When there is no ON_CALL(), the default value for the return type1142// should be returned.1143MockB b;1144EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0);1145int n = -1;1146EXPECT_NONFATAL_FAILURE(1147n = b.DoB(0),1148"Mock function \"DoB Method\" called more times than expected");1149EXPECT_EQ(0, n);1150}11511152// Tests that when a void function is called too many times,1153// the failure message contains the argument values.1154TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {1155MockA a;1156EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0);1157EXPECT_NONFATAL_FAILURE(1158a.DoA(9),1159"Mock function \"DoA Method\" called more times than expected - "1160"returning directly.\n"1161" Function call: DoA(9)\n"1162" Expected: to be never called\n"1163" Actual: called once - over-saturated and active");1164}11651166// Tests that when a non-void function is called too many times, the1167// failure message contains the argument values and the return value.1168TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {1169MockB b;1170EXPECT_CALL(b, DoB(_));1171b.DoB(1);1172EXPECT_NONFATAL_FAILURE(1173b.DoB(2),1174"Mock function called more times than expected - "1175"returning default value.\n"1176" Function call: DoB(2)\n"1177" Returns: 0\n"1178" Expected: to be called once\n"1179" Actual: called twice - over-saturated and active");1180}11811182// Tests using sequences.11831184TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {1185MockA a;1186{1187InSequence dummy;11881189EXPECT_CALL(a, DoA(1));1190EXPECT_CALL(a, DoA(2));1191}11921193EXPECT_NONFATAL_FAILURE(1194{ // NOLINT1195a.DoA(2);1196},1197"Unexpected mock function call");11981199a.DoA(1);1200a.DoA(2);1201}12021203TEST(InSequenceTest, NestedInSequence) {1204MockA a;1205{1206InSequence dummy;12071208EXPECT_CALL(a, DoA(1));1209{1210InSequence dummy2;12111212EXPECT_CALL(a, DoA(2));1213EXPECT_CALL(a, DoA(3));1214}1215}12161217EXPECT_NONFATAL_FAILURE(1218{ // NOLINT1219a.DoA(1);1220a.DoA(3);1221},1222"Unexpected mock function call");12231224a.DoA(2);1225a.DoA(3);1226}12271228TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {1229MockA a;1230{1231InSequence dummy;12321233EXPECT_CALL(a, DoA(1));1234EXPECT_CALL(a, DoA(2));1235}1236EXPECT_CALL(a, DoA(3));12371238EXPECT_NONFATAL_FAILURE(1239{ // NOLINT1240a.DoA(2);1241},1242"Unexpected mock function call");12431244a.DoA(3);1245a.DoA(1);1246a.DoA(2);1247}12481249// Tests that any order is allowed when no sequence is used.1250TEST(SequenceTest, AnyOrderIsOkByDefault) {1251{1252MockA a;1253MockB b;12541255EXPECT_CALL(a, DoA(1));1256EXPECT_CALL(b, DoB()).Times(AnyNumber());12571258a.DoA(1);1259b.DoB();1260}12611262{ // NOLINT1263MockA a;1264MockB b;12651266EXPECT_CALL(a, DoA(1));1267EXPECT_CALL(b, DoB()).Times(AnyNumber());12681269b.DoB();1270a.DoA(1);1271}1272}12731274// Tests that the calls must be in strict order when a complete order1275// is specified.1276TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {1277MockA a;1278ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));12791280Sequence s;1281EXPECT_CALL(a, ReturnResult(1)).InSequence(s);1282EXPECT_CALL(a, ReturnResult(2)).InSequence(s);1283EXPECT_CALL(a, ReturnResult(3)).InSequence(s);12841285a.ReturnResult(1);12861287// May only be called after a.ReturnResult(2).1288EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");12891290a.ReturnResult(2);1291a.ReturnResult(3);1292}12931294// Tests that the calls must be in strict order when a complete order1295// is specified.1296TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {1297MockA a;1298ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));12991300Sequence s;1301EXPECT_CALL(a, ReturnResult(1)).InSequence(s);1302EXPECT_CALL(a, ReturnResult(2)).InSequence(s);13031304// May only be called after a.ReturnResult(1).1305EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");13061307a.ReturnResult(1);1308a.ReturnResult(2);1309}13101311// Tests specifying a DAG using multiple sequences.1312class PartialOrderTest : public testing::Test {1313protected:1314PartialOrderTest() {1315ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result()));13161317// Specifies this partial ordering:1318//1319// a.ReturnResult(1) ==>1320// a.ReturnResult(2) * n ==> a.ReturnResult(3)1321// b.DoB() * 2 ==>1322Sequence x, y;1323EXPECT_CALL(a_, ReturnResult(1)).InSequence(x);1324EXPECT_CALL(b_, DoB()).Times(2).InSequence(y);1325EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y);1326EXPECT_CALL(a_, ReturnResult(3)).InSequence(x);1327}13281329MockA a_;1330MockB b_;1331};13321333TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {1334a_.ReturnResult(1);1335b_.DoB();13361337// May only be called after the second DoB().1338EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");13391340b_.DoB();1341a_.ReturnResult(3);1342}13431344TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {1345// May only be called after ReturnResult(1).1346EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");13471348a_.ReturnResult(1);1349b_.DoB();1350b_.DoB();1351a_.ReturnResult(3);1352}13531354TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {1355// May only be called last.1356EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");13571358a_.ReturnResult(1);1359b_.DoB();1360b_.DoB();1361a_.ReturnResult(3);1362}13631364TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {1365a_.ReturnResult(1);1366b_.DoB();1367b_.DoB();1368a_.ReturnResult(3);13691370// May only be called before ReturnResult(3).1371EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");1372}13731374TEST(SequenceTest, Retirement) {1375MockA a;1376Sequence s;13771378EXPECT_CALL(a, DoA(1)).InSequence(s);1379EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation();1380EXPECT_CALL(a, DoA(1)).InSequence(s);13811382a.DoA(1);1383a.DoA(2);1384a.DoA(1);1385}13861387// Tests Expectation.13881389TEST(ExpectationTest, ConstrutorsWork) {1390MockA a;1391Expectation e1; // Default ctor.13921393// Ctor from various forms of EXPECT_CALL.1394Expectation e2 = EXPECT_CALL(a, DoA(2));1395Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);1396{1397Sequence s;1398Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);1399Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);1400}1401Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);1402Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());1403Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());1404Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();14051406Expectation e10 = e2; // Copy ctor.14071408EXPECT_THAT(e1, Ne(e2));1409EXPECT_THAT(e2, Eq(e10));14101411a.DoA(2);1412a.DoA(3);1413a.DoA(4);1414a.DoA(5);1415a.DoA(6);1416a.DoA(7);1417a.DoA(8);1418a.DoA(9);1419}14201421TEST(ExpectationTest, AssignmentWorks) {1422MockA a;1423Expectation e1;1424Expectation e2 = EXPECT_CALL(a, DoA(1));14251426EXPECT_THAT(e1, Ne(e2));14271428e1 = e2;1429EXPECT_THAT(e1, Eq(e2));14301431a.DoA(1);1432}14331434// Tests ExpectationSet.14351436TEST(ExpectationSetTest, MemberTypesAreCorrect) {1437::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();1438}14391440TEST(ExpectationSetTest, ConstructorsWork) {1441MockA a;14421443Expectation e1;1444const Expectation e2;1445ExpectationSet es1; // Default ctor.1446ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.1447ExpectationSet es3 = e1; // Ctor from Expectation.1448ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.1449ExpectationSet es5 = e2; // Ctor from const Expectation.1450ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.1451ExpectationSet es7 = es2; // Copy ctor.14521453EXPECT_EQ(0, es1.size());1454EXPECT_EQ(1, es2.size());1455EXPECT_EQ(1, es3.size());1456EXPECT_EQ(1, es4.size());1457EXPECT_EQ(1, es5.size());1458EXPECT_EQ(1, es6.size());1459EXPECT_EQ(1, es7.size());14601461EXPECT_THAT(es3, Ne(es2));1462EXPECT_THAT(es4, Eq(es3));1463EXPECT_THAT(es5, Eq(es4));1464EXPECT_THAT(es6, Eq(es5));1465EXPECT_THAT(es7, Eq(es2));1466a.DoA(1);1467}14681469TEST(ExpectationSetTest, AssignmentWorks) {1470ExpectationSet es1;1471ExpectationSet es2 = Expectation();14721473es1 = es2;1474EXPECT_EQ(1, es1.size());1475EXPECT_THAT(*(es1.begin()), Eq(Expectation()));1476EXPECT_THAT(es1, Eq(es2));1477}14781479TEST(ExpectationSetTest, InsertionWorks) {1480ExpectationSet es1;1481Expectation e1;1482es1 += e1;1483EXPECT_EQ(1, es1.size());1484EXPECT_THAT(*(es1.begin()), Eq(e1));14851486MockA a;1487Expectation e2 = EXPECT_CALL(a, DoA(1));1488es1 += e2;1489EXPECT_EQ(2, es1.size());14901491ExpectationSet::const_iterator it1 = es1.begin();1492ExpectationSet::const_iterator it2 = it1;1493++it2;1494EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.1495EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.1496a.DoA(1);1497}14981499TEST(ExpectationSetTest, SizeWorks) {1500ExpectationSet es;1501EXPECT_EQ(0, es.size());15021503es += Expectation();1504EXPECT_EQ(1, es.size());15051506MockA a;1507es += EXPECT_CALL(a, DoA(1));1508EXPECT_EQ(2, es.size());15091510a.DoA(1);1511}15121513TEST(ExpectationSetTest, IsEnumerable) {1514ExpectationSet es;1515EXPECT_TRUE(es.begin() == es.end());15161517es += Expectation();1518ExpectationSet::const_iterator it = es.begin();1519EXPECT_TRUE(it != es.end());1520EXPECT_THAT(*it, Eq(Expectation()));1521++it;1522EXPECT_TRUE(it == es.end());1523}15241525// Tests the .After() clause.15261527TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {1528MockA a;1529ExpectationSet es;1530es += EXPECT_CALL(a, DoA(1));1531es += EXPECT_CALL(a, DoA(2));1532EXPECT_CALL(a, DoA(3)).After(es);15331534a.DoA(1);1535a.DoA(2);1536a.DoA(3);1537}15381539TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {1540MockA a;1541MockB b;1542// The following also verifies that const Expectation objects work1543// too. Do not remove the const modifiers.1544const Expectation e1 = EXPECT_CALL(a, DoA(1));1545const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);1546EXPECT_CALL(a, DoA(2)).After(e2);15471548a.DoA(1);1549b.DoB();1550b.DoB();1551a.DoA(2);1552}15531554// Calls must be in strict order when specified so using .After().1555TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {1556MockA a;1557MockB b;15581559// Define ordering:1560// a.DoA(1) ==> b.DoB() ==> a.DoA(2)1561Expectation e1 = EXPECT_CALL(a, DoA(1));1562Expectation e2 = EXPECT_CALL(b, DoB()).After(e1);1563EXPECT_CALL(a, DoA(2)).After(e2);15641565a.DoA(1);15661567// May only be called after DoB().1568EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");15691570b.DoB();1571a.DoA(2);1572}15731574// Calls must be in strict order when specified so using .After().1575TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {1576MockA a;1577MockB b;15781579// Define ordering:1580// a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)1581Expectation e1 = EXPECT_CALL(a, DoA(1));1582Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);1583EXPECT_CALL(a, DoA(2)).After(e2);15841585a.DoA(1);1586b.DoB();15871588// May only be called after the second DoB().1589EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");15901591b.DoB();1592a.DoA(2);1593}15941595// Calls must satisfy the partial order when specified so.1596TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {1597MockA a;1598ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));15991600// Define ordering:1601// a.DoA(1) ==>1602// a.DoA(2) ==> a.ReturnResult(3)1603Expectation e = EXPECT_CALL(a, DoA(1));1604const ExpectationSet es = EXPECT_CALL(a, DoA(2));1605EXPECT_CALL(a, ReturnResult(3)).After(e, es);16061607// May only be called last.1608EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");16091610a.DoA(2);1611a.DoA(1);1612a.ReturnResult(3);1613}16141615// Calls must satisfy the partial order when specified so.1616TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {1617MockA a;16181619// Define ordering:1620// a.DoA(1) ==>1621// a.DoA(2) ==> a.DoA(3)1622Expectation e = EXPECT_CALL(a, DoA(1));1623const ExpectationSet es = EXPECT_CALL(a, DoA(2));1624EXPECT_CALL(a, DoA(3)).After(e, es);16251626a.DoA(2);16271628// May only be called last.1629EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");16301631a.DoA(1);1632a.DoA(3);1633}16341635// .After() can be combined with .InSequence().1636TEST(AfterTest, CanBeUsedWithInSequence) {1637MockA a;1638Sequence s;1639Expectation e = EXPECT_CALL(a, DoA(1));1640EXPECT_CALL(a, DoA(2)).InSequence(s);1641EXPECT_CALL(a, DoA(3)).InSequence(s).After(e);16421643a.DoA(1);16441645// May only be after DoA(2).1646EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");16471648a.DoA(2);1649a.DoA(3);1650}16511652// .After() can be called multiple times.1653TEST(AfterTest, CanBeCalledManyTimes) {1654MockA a;1655Expectation e1 = EXPECT_CALL(a, DoA(1));1656Expectation e2 = EXPECT_CALL(a, DoA(2));1657Expectation e3 = EXPECT_CALL(a, DoA(3));1658EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3);16591660a.DoA(3);1661a.DoA(1);1662a.DoA(2);1663a.DoA(4);1664}16651666// .After() accepts up to 5 arguments.1667TEST(AfterTest, AcceptsUpToFiveArguments) {1668MockA a;1669Expectation e1 = EXPECT_CALL(a, DoA(1));1670Expectation e2 = EXPECT_CALL(a, DoA(2));1671Expectation e3 = EXPECT_CALL(a, DoA(3));1672ExpectationSet es1 = EXPECT_CALL(a, DoA(4));1673ExpectationSet es2 = EXPECT_CALL(a, DoA(5));1674EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2);16751676a.DoA(5);1677a.DoA(2);1678a.DoA(4);1679a.DoA(1);1680a.DoA(3);1681a.DoA(6);1682}16831684// .After() allows input to contain duplicated Expectations.1685TEST(AfterTest, AcceptsDuplicatedInput) {1686MockA a;1687ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));16881689// Define ordering:1690// DoA(1) ==>1691// DoA(2) ==> ReturnResult(3)1692Expectation e1 = EXPECT_CALL(a, DoA(1));1693Expectation e2 = EXPECT_CALL(a, DoA(2));1694ExpectationSet es;1695es += e1;1696es += e2;1697EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1);16981699a.DoA(1);17001701// May only be after DoA(2).1702EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");17031704a.DoA(2);1705a.ReturnResult(3);1706}17071708// An Expectation added to an ExpectationSet after it has been used in1709// an .After() has no effect.1710TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {1711MockA a;1712ExpectationSet es1 = EXPECT_CALL(a, DoA(1));1713Expectation e2 = EXPECT_CALL(a, DoA(2));1714EXPECT_CALL(a, DoA(3)).After(es1);1715es1 += e2;17161717a.DoA(1);1718a.DoA(3);1719a.DoA(2);1720}17211722// Tests that Google Mock correctly handles calls to mock functions1723// after a mock object owning one of their pre-requisites has died.17241725// Tests that calls that satisfy the original spec are successful.1726TEST(DeletingMockEarlyTest, Success1) {1727MockB* const b1 = new MockB;1728MockA* const a = new MockA;1729MockB* const b2 = new MockB;17301731{1732InSequence dummy;1733EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));1734EXPECT_CALL(*a, Binary(_, _))1735.Times(AnyNumber())1736.WillRepeatedly(Return(true));1737EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));1738}17391740EXPECT_EQ(1, b1->DoB(1));1741delete b1;1742// a's pre-requisite has died.1743EXPECT_TRUE(a->Binary(0, 1));1744delete b2;1745// a's successor has died.1746EXPECT_TRUE(a->Binary(1, 2));1747delete a;1748}17491750// Tests that calls that satisfy the original spec are successful.1751TEST(DeletingMockEarlyTest, Success2) {1752MockB* const b1 = new MockB;1753MockA* const a = new MockA;1754MockB* const b2 = new MockB;17551756{1757InSequence dummy;1758EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));1759EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());1760EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));1761}17621763delete a; // a is trivially satisfied.1764EXPECT_EQ(1, b1->DoB(1));1765EXPECT_EQ(2, b2->DoB(2));1766delete b1;1767delete b2;1768}17691770// Tests that it's OK to delete a mock object itself in its action.17711772// Suppresses warning on unreferenced formal parameter in MSVC with1773// -W4.1774GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)17751776ACTION_P(Delete, ptr) { delete ptr; }17771778GTEST_DISABLE_MSC_WARNINGS_POP_() // 410017791780TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {1781MockA* const a = new MockA;1782EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));1783a->DoA(42); // This will cause a to be deleted.1784}17851786TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {1787MockA* const a = new MockA;1788EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));1789a->ReturnResult(42); // This will cause a to be deleted.1790}17911792// Tests that calls that violate the original spec yield failures.1793TEST(DeletingMockEarlyTest, Failure1) {1794MockB* const b1 = new MockB;1795MockA* const a = new MockA;1796MockB* const b2 = new MockB;17971798{1799InSequence dummy;1800EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));1801EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());1802EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));1803}18041805delete a; // a is trivially satisfied.1806EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call");1807EXPECT_EQ(1, b1->DoB(1));1808delete b1;1809delete b2;1810}18111812// Tests that calls that violate the original spec yield failures.1813TEST(DeletingMockEarlyTest, Failure2) {1814MockB* const b1 = new MockB;1815MockA* const a = new MockA;1816MockB* const b2 = new MockB;18171818{1819InSequence dummy;1820EXPECT_CALL(*b1, DoB(_));1821EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());1822EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());1823}18241825EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called");1826EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call");1827EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call");1828delete a;1829delete b2;1830}18311832class EvenNumberCardinality : public CardinalityInterface {1833public:1834// Returns true if and only if call_count calls will satisfy this1835// cardinality.1836bool IsSatisfiedByCallCount(int call_count) const override {1837return call_count % 2 == 0;1838}18391840// Returns true if and only if call_count calls will saturate this1841// cardinality.1842bool IsSaturatedByCallCount(int /* call_count */) const override {1843return false;1844}18451846// Describes self to an ostream.1847void DescribeTo(::std::ostream* os) const override {1848*os << "called even number of times";1849}1850};18511852Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }18531854TEST(ExpectationBaseTest,1855AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {1856MockA* a = new MockA;1857Sequence s;18581859EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);1860EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);1861EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());18621863a->DoA(3);1864a->DoA(1);1865EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");1866EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");1867}18681869// The following tests verify the message generated when a mock1870// function is called.18711872struct Printable {};18731874inline void operator<<(::std::ostream& os, const Printable&) {1875os << "Printable";1876}18771878struct Unprintable {1879Unprintable() : value(0) {}1880int value;1881};18821883class MockC {1884public:1885MockC() = default;18861887MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,1888const Printable& x, Unprintable y));1889MOCK_METHOD0(NonVoidMethod, int()); // NOLINT18901891private:1892MockC(const MockC&) = delete;1893MockC& operator=(const MockC&) = delete;1894};18951896class VerboseFlagPreservingFixture : public testing::Test {1897protected:1898VerboseFlagPreservingFixture()1899: saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}19001901~VerboseFlagPreservingFixture() override {1902GMOCK_FLAG_SET(verbose, saved_verbose_flag_);1903}19041905private:1906const std::string saved_verbose_flag_;19071908VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;1909VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =1910delete;1911};19121913#if GTEST_HAS_STREAM_REDIRECTION19141915// Tests that an uninteresting mock function call on a naggy mock1916// generates a warning without the stack trace when1917// --gmock_verbose=warning is specified.1918TEST(FunctionCallMessageTest,1919UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {1920GMOCK_FLAG_SET(verbose, kWarningVerbosity);1921NaggyMock<MockC> c;1922CaptureStdout();1923c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());1924const std::string output = GetCapturedStdout();1925EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);1926EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);1927}19281929// Tests that an uninteresting mock function call on a naggy mock1930// generates a warning containing the stack trace when1931// --gmock_verbose=info is specified.1932TEST(FunctionCallMessageTest,1933UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {1934GMOCK_FLAG_SET(verbose, kInfoVerbosity);1935NaggyMock<MockC> c;1936CaptureStdout();1937c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());1938const std::string output = GetCapturedStdout();1939EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);1940EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);19411942#ifndef NDEBUG19431944// We check the stack trace content in dbg-mode only, as opt-mode1945// may inline the call we are interested in seeing.19461947// Verifies that a void mock function's name appears in the stack1948// trace.1949EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);19501951// Verifies that a non-void mock function's name appears in the1952// stack trace.1953CaptureStdout();1954c.NonVoidMethod();1955const std::string output2 = GetCapturedStdout();1956EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);19571958#endif // NDEBUG1959}19601961// Tests that an uninteresting mock function call on a naggy mock1962// causes the function arguments and return value to be printed.1963TEST(FunctionCallMessageTest,1964UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {1965// A non-void mock function.1966NaggyMock<MockB> b;1967CaptureStdout();1968b.DoB();1969const std::string output1 = GetCapturedStdout();1970EXPECT_PRED_FORMAT2(1971IsSubstring,1972"Uninteresting mock function call - returning default value.\n"1973" Function call: DoB()\n"1974" Returns: 0\n",1975output1.c_str());1976// Makes sure the return value is printed.19771978// A void mock function.1979NaggyMock<MockC> c;1980CaptureStdout();1981c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());1982const std::string output2 = GetCapturedStdout();1983EXPECT_THAT(1984output2.c_str(),1985ContainsRegex("Uninteresting mock function call - returning directly\\.\n"1986" Function call: VoidMethod"1987"\\(false, 5, \"Hi\", NULL, @.+ "1988"Printable, 4-byte object <00-00 00-00>\\)"));1989// A void function has no return value to print.1990}19911992// Tests how the --gmock_verbose flag affects Google Mock's output.19931994class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {1995public:1996// Verifies that the given Google Mock output is correct. (When1997// should_print is true, the output should match the given regex and1998// contain the given function name in the stack trace. When it's1999// false, the output should be empty.)2000void VerifyOutput(const std::string& output, bool should_print,2001const std::string& expected_substring,2002const std::string& function_name) {2003if (should_print) {2004EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));2005#ifndef NDEBUG2006// We check the stack trace content in dbg-mode only, as opt-mode2007// may inline the call we are interested in seeing.2008EXPECT_THAT(output.c_str(), HasSubstr(function_name));2009#else2010// Suppresses 'unused function parameter' warnings.2011static_cast<void>(function_name);2012#endif // NDEBUG2013} else {2014EXPECT_STREQ("", output.c_str());2015}2016}20172018// Tests how the flag affects expected calls.2019void TestExpectedCall(bool should_print) {2020MockA a;2021EXPECT_CALL(a, DoA(5));2022EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));20232024// A void-returning function.2025CaptureStdout();2026a.DoA(5);2027VerifyOutput(GetCapturedStdout(), should_print,2028"Mock function call matches EXPECT_CALL(a, DoA(5))...\n"2029" Function call: DoA(5)\n"2030"Stack trace:\n",2031"DoA");20322033// A non-void-returning function.2034CaptureStdout();2035a.Binary(2, 1);2036VerifyOutput(GetCapturedStdout(), should_print,2037"Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"2038" Function call: Binary(2, 1)\n"2039" Returns: true\n"2040"Stack trace:\n",2041"Binary");2042}20432044// Tests how the flag affects uninteresting calls on a naggy mock.2045void TestUninterestingCallOnNaggyMock(bool should_print) {2046NaggyMock<MockA> a;2047const std::string note =2048"NOTE: You can safely ignore the above warning unless this "2049"call should not happen. Do not suppress it by blindly adding "2050"an EXPECT_CALL() if you don't mean to enforce the call. "2051"See "2052"https://github.com/google/googletest/blob/main/docs/"2053"gmock_cook_book.md#"2054"knowing-when-to-expect-useoncall for details.";20552056// A void-returning function.2057CaptureStdout();2058a.DoA(5);2059VerifyOutput(GetCapturedStdout(), should_print,2060"\nGMOCK WARNING:\n"2061"Uninteresting mock function call - returning directly.\n"2062" Function call: DoA(5)\n" +2063note,2064"DoA");20652066// A non-void-returning function.2067CaptureStdout();2068a.Binary(2, 1);2069VerifyOutput(GetCapturedStdout(), should_print,2070"\nGMOCK WARNING:\n"2071"Uninteresting mock function call - returning default value.\n"2072" Function call: Binary(2, 1)\n"2073" Returns: false\n" +2074note,2075"Binary");2076}2077};20782079// Tests that --gmock_verbose=info causes both expected and2080// uninteresting calls to be reported.2081TEST_F(GMockVerboseFlagTest, Info) {2082GMOCK_FLAG_SET(verbose, kInfoVerbosity);2083TestExpectedCall(true);2084TestUninterestingCallOnNaggyMock(true);2085}20862087// Tests that --gmock_verbose=warning causes uninteresting calls to be2088// reported.2089TEST_F(GMockVerboseFlagTest, Warning) {2090GMOCK_FLAG_SET(verbose, kWarningVerbosity);2091TestExpectedCall(false);2092TestUninterestingCallOnNaggyMock(true);2093}20942095// Tests that --gmock_verbose=warning causes neither expected nor2096// uninteresting calls to be reported.2097TEST_F(GMockVerboseFlagTest, Error) {2098GMOCK_FLAG_SET(verbose, kErrorVerbosity);2099TestExpectedCall(false);2100TestUninterestingCallOnNaggyMock(false);2101}21022103// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect2104// as --gmock_verbose=warning.2105TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {2106GMOCK_FLAG_SET(verbose, "invalid"); // Treated as "warning".2107TestExpectedCall(false);2108TestUninterestingCallOnNaggyMock(true);2109}21102111#endif // GTEST_HAS_STREAM_REDIRECTION21122113// A helper class that generates a failure when printed. We use it to2114// ensure that Google Mock doesn't print a value (even to an internal2115// buffer) when it is not supposed to do so.2116class PrintMeNot {};21172118void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {2119ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "2120<< "printed even to an internal buffer.";2121}21222123class LogTestHelper {2124public:2125LogTestHelper() = default;21262127MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));21282129private:2130LogTestHelper(const LogTestHelper&) = delete;2131LogTestHelper& operator=(const LogTestHelper&) = delete;2132};21332134class GMockLogTest : public VerboseFlagPreservingFixture {2135protected:2136LogTestHelper helper_;2137};21382139TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {2140GMOCK_FLAG_SET(verbose, kWarningVerbosity);2141EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));2142helper_.Foo(PrintMeNot()); // This is an expected call.2143}21442145TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {2146GMOCK_FLAG_SET(verbose, kErrorVerbosity);2147EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));2148helper_.Foo(PrintMeNot()); // This is an expected call.2149}21502151TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {2152GMOCK_FLAG_SET(verbose, kErrorVerbosity);2153ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));2154helper_.Foo(PrintMeNot()); // This should generate a warning.2155}21562157// Tests Mock::AllowLeak().21582159TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {2160MockA* a = new MockA;2161Mock::AllowLeak(a);2162}21632164TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {2165MockA* a = new MockA;2166Mock::AllowLeak(a);2167ON_CALL(*a, DoA(_)).WillByDefault(Return());2168a->DoA(0);2169}21702171TEST(AllowLeakTest, CanBeCalledAfterOnCall) {2172MockA* a = new MockA;2173ON_CALL(*a, DoA(_)).WillByDefault(Return());2174Mock::AllowLeak(a);2175}21762177TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {2178MockA* a = new MockA;2179Mock::AllowLeak(a);2180EXPECT_CALL(*a, DoA(_));2181a->DoA(0);2182}21832184TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {2185MockA* a = new MockA;2186EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());2187Mock::AllowLeak(a);2188}21892190TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {2191MockA* a = new MockA;2192ON_CALL(*a, DoA(_)).WillByDefault(Return());2193EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());2194Mock::AllowLeak(a);2195}21962197// Tests that we can verify and clear a mock object's expectations2198// when none of its methods has expectations.2199TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {2200MockB b;2201ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));22022203// There should be no expectations on the methods now, so we can2204// freely call them.2205EXPECT_EQ(0, b.DoB());2206EXPECT_EQ(0, b.DoB(1));2207}22082209// Tests that we can verify and clear a mock object's expectations2210// when some, but not all, of its methods have expectations *and* the2211// verification succeeds.2212TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {2213MockB b;2214EXPECT_CALL(b, DoB()).WillOnce(Return(1));2215b.DoB();2216ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));22172218// There should be no expectations on the methods now, so we can2219// freely call them.2220EXPECT_EQ(0, b.DoB());2221EXPECT_EQ(0, b.DoB(1));2222}22232224// Tests that we can verify and clear a mock object's expectations2225// when some, but not all, of its methods have expectations *and* the2226// verification fails.2227TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {2228MockB b;2229EXPECT_CALL(b, DoB()).WillOnce(Return(1));2230bool result = true;2231EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),2232"Actual: never called");2233ASSERT_FALSE(result);22342235// There should be no expectations on the methods now, so we can2236// freely call them.2237EXPECT_EQ(0, b.DoB());2238EXPECT_EQ(0, b.DoB(1));2239}22402241// Tests that we can verify and clear a mock object's expectations2242// when all of its methods have expectations.2243TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {2244MockB b;2245EXPECT_CALL(b, DoB()).WillOnce(Return(1));2246EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));2247b.DoB();2248b.DoB(1);2249ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));22502251// There should be no expectations on the methods now, so we can2252// freely call them.2253EXPECT_EQ(0, b.DoB());2254EXPECT_EQ(0, b.DoB(1));2255}22562257// Tests that we can verify and clear a mock object's expectations2258// when a method has more than one expectation.2259TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {2260MockB b;2261EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));2262EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));2263b.DoB(1);2264bool result = true;2265EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),2266"Actual: never called");2267ASSERT_FALSE(result);22682269// There should be no expectations on the methods now, so we can2270// freely call them.2271EXPECT_EQ(0, b.DoB());2272EXPECT_EQ(0, b.DoB(1));2273}22742275// Tests that we can call VerifyAndClearExpectations() on the same2276// mock object multiple times.2277TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {2278MockB b;2279EXPECT_CALL(b, DoB());2280b.DoB();2281Mock::VerifyAndClearExpectations(&b);22822283EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));2284b.DoB(1);2285Mock::VerifyAndClearExpectations(&b);2286Mock::VerifyAndClearExpectations(&b);22872288// There should be no expectations on the methods now, so we can2289// freely call them.2290EXPECT_EQ(0, b.DoB());2291EXPECT_EQ(0, b.DoB(1));2292}22932294// Tests that we can clear a mock object's default actions when none2295// of its methods has default actions.2296TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {2297MockB b;2298// If this crashes or generates a failure, the test will catch it.2299Mock::VerifyAndClear(&b);2300EXPECT_EQ(0, b.DoB());2301}23022303// Tests that we can clear a mock object's default actions when some,2304// but not all of its methods have default actions.2305TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {2306MockB b;2307ON_CALL(b, DoB()).WillByDefault(Return(1));23082309Mock::VerifyAndClear(&b);23102311// Verifies that the default action of int DoB() was removed.2312EXPECT_EQ(0, b.DoB());2313}23142315// Tests that we can clear a mock object's default actions when all of2316// its methods have default actions.2317TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {2318MockB b;2319ON_CALL(b, DoB()).WillByDefault(Return(1));2320ON_CALL(b, DoB(_)).WillByDefault(Return(2));23212322Mock::VerifyAndClear(&b);23232324// Verifies that the default action of int DoB() was removed.2325EXPECT_EQ(0, b.DoB());23262327// Verifies that the default action of int DoB(int) was removed.2328EXPECT_EQ(0, b.DoB(0));2329}23302331// Tests that we can clear a mock object's default actions when a2332// method has more than one ON_CALL() set on it.2333TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {2334MockB b;2335ON_CALL(b, DoB(0)).WillByDefault(Return(1));2336ON_CALL(b, DoB(_)).WillByDefault(Return(2));23372338Mock::VerifyAndClear(&b);23392340// Verifies that the default actions (there are two) of int DoB(int)2341// were removed.2342EXPECT_EQ(0, b.DoB(0));2343EXPECT_EQ(0, b.DoB(1));2344}23452346// Tests that we can call VerifyAndClear() on a mock object multiple2347// times.2348TEST(VerifyAndClearTest, CanCallManyTimes) {2349MockB b;2350ON_CALL(b, DoB()).WillByDefault(Return(1));2351Mock::VerifyAndClear(&b);2352Mock::VerifyAndClear(&b);23532354ON_CALL(b, DoB(_)).WillByDefault(Return(1));2355Mock::VerifyAndClear(&b);23562357EXPECT_EQ(0, b.DoB());2358EXPECT_EQ(0, b.DoB(1));2359}23602361// Tests that VerifyAndClear() works when the verification succeeds.2362TEST(VerifyAndClearTest, Success) {2363MockB b;2364ON_CALL(b, DoB()).WillByDefault(Return(1));2365EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));23662367b.DoB();2368b.DoB(1);2369ASSERT_TRUE(Mock::VerifyAndClear(&b));23702371// There should be no expectations on the methods now, so we can2372// freely call them.2373EXPECT_EQ(0, b.DoB());2374EXPECT_EQ(0, b.DoB(1));2375}23762377// Tests that VerifyAndClear() works when the verification fails.2378TEST(VerifyAndClearTest, Failure) {2379MockB b;2380ON_CALL(b, DoB(_)).WillByDefault(Return(1));2381EXPECT_CALL(b, DoB()).WillOnce(Return(2));23822383b.DoB(1);2384bool result = true;2385EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),2386"Actual: never called");2387ASSERT_FALSE(result);23882389// There should be no expectations on the methods now, so we can2390// freely call them.2391EXPECT_EQ(0, b.DoB());2392EXPECT_EQ(0, b.DoB(1));2393}23942395// Tests that VerifyAndClear() works when the default actions and2396// expectations are set on a const mock object.2397TEST(VerifyAndClearTest, Const) {2398MockB b;2399ON_CALL(Const(b), DoB()).WillByDefault(Return(1));24002401EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));24022403b.DoB();2404b.DoB();2405ASSERT_TRUE(Mock::VerifyAndClear(&b));24062407// There should be no expectations on the methods now, so we can2408// freely call them.2409EXPECT_EQ(0, b.DoB());2410EXPECT_EQ(0, b.DoB(1));2411}24122413// Tests that we can set default actions and expectations on a mock2414// object after VerifyAndClear() has been called on it.2415TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {2416MockB b;2417ON_CALL(b, DoB()).WillByDefault(Return(1));2418EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));2419b.DoB(1);24202421Mock::VerifyAndClear(&b);24222423EXPECT_CALL(b, DoB()).WillOnce(Return(3));2424ON_CALL(b, DoB(_)).WillByDefault(Return(4));24252426EXPECT_EQ(3, b.DoB());2427EXPECT_EQ(4, b.DoB(1));2428}24292430// Tests that calling VerifyAndClear() on one mock object does not2431// affect other mock objects (either of the same type or not).2432TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {2433MockA a;2434MockB b1;2435MockB b2;24362437ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));2438EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));24392440ON_CALL(b1, DoB()).WillByDefault(Return(1));2441EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));24422443ON_CALL(b2, DoB()).WillByDefault(Return(3));2444EXPECT_CALL(b2, DoB(_));24452446b2.DoB(0);2447Mock::VerifyAndClear(&b2);24482449// Verifies that the default actions and expectations of a and b12450// are still in effect.2451EXPECT_TRUE(a.Binary(0, 0));2452EXPECT_FALSE(a.Binary(0, 0));24532454EXPECT_EQ(1, b1.DoB());2455EXPECT_EQ(2, b1.DoB(0));2456}24572458TEST(VerifyAndClearTest,2459DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {2460std::shared_ptr<MockA> a(new MockA);2461ReferenceHoldingMock test_mock;24622463// EXPECT_CALL stores a reference to a inside test_mock.2464EXPECT_CALL(test_mock, AcceptReference(_))2465.WillRepeatedly(SetArgPointee<0>(a));24662467// Throw away the reference to the mock that we have in a. After this, the2468// only reference to it is stored by test_mock.2469a.reset();24702471// When test_mock goes out of scope, it destroys the last remaining reference2472// to the mock object originally pointed to by a. This will cause the MockA2473// destructor to be called from inside the ReferenceHoldingMock destructor.2474// The state of all mocks is protected by a single global lock, but there2475// should be no deadlock.2476}24772478TEST(VerifyAndClearTest,2479DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {2480std::shared_ptr<MockA> a(new MockA);2481ReferenceHoldingMock test_mock;24822483// ON_CALL stores a reference to a inside test_mock.2484ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));24852486// Throw away the reference to the mock that we have in a. After this, the2487// only reference to it is stored by test_mock.2488a.reset();24892490// When test_mock goes out of scope, it destroys the last remaining reference2491// to the mock object originally pointed to by a. This will cause the MockA2492// destructor to be called from inside the ReferenceHoldingMock destructor.2493// The state of all mocks is protected by a single global lock, but there2494// should be no deadlock.2495}24962497// Tests that a mock function's action can call a mock function2498// (either the same function or a different one) either as an explicit2499// action or as a default action without causing a dead lock. It2500// verifies that the action is not performed inside the critical2501// section.2502TEST(SynchronizationTest, CanCallMockMethodInAction) {2503MockA a;2504MockC c;2505ON_CALL(a, DoA(_)).WillByDefault(2506IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));2507EXPECT_CALL(a, DoA(1));2508EXPECT_CALL(a, DoA(1))2509.WillOnce(Invoke(&a, &MockA::DoA))2510.RetiresOnSaturation();2511EXPECT_CALL(c, NonVoidMethod());25122513a.DoA(1);2514// This will match the second EXPECT_CALL() and trigger another a.DoA(1),2515// which will in turn match the first EXPECT_CALL() and trigger a call to2516// c.NonVoidMethod() that was specified by the ON_CALL() since the first2517// EXPECT_CALL() did not specify an action.2518}25192520TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {2521MockA a;2522int do_a_arg0 = 0;2523ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));2524int do_a_47_arg0 = 0;2525ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));25262527a.DoA(17);2528EXPECT_THAT(do_a_arg0, 17);2529EXPECT_THAT(do_a_47_arg0, 0);2530a.DoA(47);2531EXPECT_THAT(do_a_arg0, 17);2532EXPECT_THAT(do_a_47_arg0, 47);25332534ON_CALL(a, Binary).WillByDefault(Return(true));2535ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));2536EXPECT_THAT(a.Binary(14, 17), true);2537EXPECT_THAT(a.Binary(17, 14), false);2538}25392540TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {2541MockB b;2542ON_CALL(b, DoB()).WillByDefault(Return(9));2543ON_CALL(b, DoB(5)).WillByDefault(Return(11));25442545EXPECT_THAT(b.DoB(), 9);2546EXPECT_THAT(b.DoB(1), 0); // default value2547EXPECT_THAT(b.DoB(5), 11);2548}25492550struct MockWithConstMethods {2551public:2552MOCK_CONST_METHOD1(Foo, int(int));2553MOCK_CONST_METHOD2(Bar, int(int, const char*));2554};25552556TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {2557MockWithConstMethods mock;2558ON_CALL(mock, Foo).WillByDefault(Return(7));2559ON_CALL(mock, Bar).WillByDefault(Return(33));25602561EXPECT_THAT(mock.Foo(17), 7);2562EXPECT_THAT(mock.Bar(27, "purple"), 33);2563}25642565class MockConstOverload {2566public:2567MOCK_METHOD1(Overloaded, int(int));2568MOCK_CONST_METHOD1(Overloaded, int(int));2569};25702571TEST(ParameterlessExpectationsTest,2572CanSetExpectationsForConstOverloadedMethods) {2573MockConstOverload mock;2574ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));2575ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));2576ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));2577ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));25782579EXPECT_THAT(mock.Overloaded(1), 7);2580EXPECT_THAT(mock.Overloaded(5), 9);2581EXPECT_THAT(mock.Overloaded(7), 7);25822583const MockConstOverload& const_mock = mock;2584EXPECT_THAT(const_mock.Overloaded(1), 0);2585EXPECT_THAT(const_mock.Overloaded(5), 11);2586EXPECT_THAT(const_mock.Overloaded(7), 13);2587}25882589} // namespace2590} // namespace testing25912592int main(int argc, char** argv) {2593testing::InitGoogleMock(&argc, argv);2594// Ensures that the tests pass no matter what value of2595// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.2596GMOCK_FLAG_SET(catch_leaked_mocks, true);2597GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);25982599return RUN_ALL_TESTS();2600}260126022603