Path: blob/main/contrib/googletest/googlemock/test/gmock-spec-builders_test.cc
109682 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// TODO(b/396121064) - Fix this test under MSVC808#ifndef _MSC_VER809// It should be possible to return a non-moveable type from a mock action in810// C++17 and above, where it's guaranteed that such a type can be initialized811// from a prvalue returned from a function.812TEST(ExpectCallTest, NonMoveableType) {813// Define a non-moveable result type.814struct NonMoveableStruct {815explicit NonMoveableStruct(int x_in) : x(x_in) {}816NonMoveableStruct(NonMoveableStruct&&) = delete;817818int x;819};820821static_assert(!std::is_move_constructible_v<NonMoveableStruct>);822static_assert(!std::is_copy_constructible_v<NonMoveableStruct>);823824static_assert(!std::is_move_assignable_v<NonMoveableStruct>);825static_assert(!std::is_copy_assignable_v<NonMoveableStruct>);826827// We should be able to use a callable that returns that result as both a828// OnceAction and an Action, whether the callable ignores arguments or not.829const auto return_17 = [] { return NonMoveableStruct(17); };830831static_cast<void>(OnceAction<NonMoveableStruct()>{return_17});832static_cast<void>(Action<NonMoveableStruct()>{return_17});833834static_cast<void>(OnceAction<NonMoveableStruct(int)>{return_17});835static_cast<void>(Action<NonMoveableStruct(int)>{return_17});836837// It should be possible to return the result end to end through an838// EXPECT_CALL statement, with both WillOnce and WillRepeatedly.839MockFunction<NonMoveableStruct()> mock;840EXPECT_CALL(mock, Call) //841.WillOnce(return_17) //842.WillRepeatedly(return_17);843844EXPECT_EQ(17, mock.AsStdFunction()().x);845EXPECT_EQ(17, mock.AsStdFunction()().x);846EXPECT_EQ(17, mock.AsStdFunction()().x);847}848849#endif // _MSC_VER850851// Tests that the n-th action is taken for the n-th matching852// invocation.853TEST(ExpectCallTest, NthMatchTakesNthAction) {854MockB b;855EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(856Return(3));857858EXPECT_EQ(1, b.DoB());859EXPECT_EQ(2, b.DoB());860EXPECT_EQ(3, b.DoB());861}862863// Tests that the WillRepeatedly() action is taken when the WillOnce(...)864// list is exhausted.865TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {866MockB b;867EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));868869EXPECT_EQ(1, b.DoB());870EXPECT_EQ(2, b.DoB());871EXPECT_EQ(2, b.DoB());872}873874#if GTEST_HAS_STREAM_REDIRECTION875876// Tests that the default action is taken when the WillOnce(...) list is877// exhausted and there is no WillRepeatedly().878TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {879MockB b;880EXPECT_CALL(b, DoB(_)).Times(1);881EXPECT_CALL(b, DoB())882.Times(AnyNumber())883.WillOnce(Return(1))884.WillOnce(Return(2));885886CaptureStdout();887EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the888// expectation has no action clause at all.889EXPECT_EQ(1, b.DoB());890EXPECT_EQ(2, b.DoB());891const std::string output1 = GetCapturedStdout();892EXPECT_STREQ("", output1.c_str());893894CaptureStdout();895EXPECT_EQ(0, b.DoB());896EXPECT_EQ(0, b.DoB());897const std::string output2 = GetCapturedStdout();898EXPECT_THAT(output2.c_str(),899HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"900"Called 3 times, but only 2 WillOnce()s are specified"901" - returning default value."));902EXPECT_THAT(output2.c_str(),903HasSubstr("Actions ran out in EXPECT_CALL(b, DoB())...\n"904"Called 4 times, but only 2 WillOnce()s are specified"905" - returning default value."));906}907908TEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhaustedActions) {909MockB b;910std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);911EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));912913EXPECT_EQ(1, b.DoB());914915CaptureStdout();916EXPECT_EQ(0, b.DoB());917const std::string output = GetCapturedStdout();918// The warning message should contain the call location.919EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);920}921922TEST(FunctionMockerMessageTest,923ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {924std::string on_call_location;925CaptureStdout();926{927NaggyMock<MockB> b;928on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);929ON_CALL(b, DoB(_)).WillByDefault(Return(0));930b.DoB(0);931}932EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());933}934935#endif // GTEST_HAS_STREAM_REDIRECTION936937// Tests that an uninteresting call performs the default action.938TEST(UninterestingCallTest, DoesDefaultAction) {939// When there is an ON_CALL() statement, the action specified by it940// should be taken.941MockA a;942ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));943EXPECT_TRUE(a.Binary(1, 2));944945// When there is no ON_CALL(), the default value for the return type946// should be returned.947MockB b;948EXPECT_EQ(0, b.DoB());949}950951// Tests that an unexpected call performs the default action.952TEST(UnexpectedCallTest, DoesDefaultAction) {953// When there is an ON_CALL() statement, the action specified by it954// should be taken.955MockA a;956ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));957EXPECT_CALL(a, Binary(0, 0));958a.Binary(0, 0);959bool result = false;960EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),961"Unexpected mock function call");962EXPECT_TRUE(result);963964// When there is no ON_CALL(), the default value for the return type965// should be returned.966MockB b;967EXPECT_CALL(b, DoB(0)).Times(0);968int n = -1;969EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call");970EXPECT_EQ(0, n);971}972973// Tests that when an unexpected void function generates the right974// failure message.975TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {976// First, tests the message when there is only one EXPECT_CALL().977MockA a1;978EXPECT_CALL(a1, DoA(1));979a1.DoA(1);980// Ideally we should match the failure message against a regex, but981// EXPECT_NONFATAL_FAILURE doesn't support that, so we test for982// multiple sub-strings instead.983EXPECT_NONFATAL_FAILURE(984a1.DoA(9),985"Unexpected mock function call - returning directly.\n"986" Function call: DoA(9)\n"987"Google Mock tried the following 1 expectation, but it didn't match:");988EXPECT_NONFATAL_FAILURE(989a1.DoA(9),990" Expected arg #0: is equal to 1\n"991" Actual: 9\n"992" Expected: to be called once\n"993" Actual: called once - saturated and active");994995// Next, tests the message when there are more than one EXPECT_CALL().996MockA a2;997EXPECT_CALL(a2, DoA(1));998EXPECT_CALL(a2, DoA(3));999a2.DoA(1);1000EXPECT_NONFATAL_FAILURE(1001a2.DoA(2),1002"Unexpected mock function call - returning directly.\n"1003" Function call: DoA(2)\n"1004"Google Mock tried the following 2 expectations, but none matched:");1005EXPECT_NONFATAL_FAILURE(1006a2.DoA(2),1007"tried expectation #0: EXPECT_CALL(a2, DoA(1))...\n"1008" Expected arg #0: is equal to 1\n"1009" Actual: 2\n"1010" Expected: to be called once\n"1011" Actual: called once - saturated and active");1012EXPECT_NONFATAL_FAILURE(1013a2.DoA(2),1014"tried expectation #1: EXPECT_CALL(a2, DoA(3))...\n"1015" Expected arg #0: is equal to 3\n"1016" Actual: 2\n"1017" Expected: to be called once\n"1018" Actual: never called - unsatisfied and active");1019a2.DoA(3);1020}10211022// Tests that an unexpected non-void function generates the right1023// failure message.1024TEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {1025MockB b1;1026EXPECT_CALL(b1, DoB(1));1027b1.DoB(1);1028EXPECT_NONFATAL_FAILURE(1029b1.DoB(2),1030"Unexpected mock function call - returning default value.\n"1031" Function call: DoB(2)\n"1032" Returns: 0\n"1033"Google Mock tried the following 1 expectation, but it didn't match:");1034EXPECT_NONFATAL_FAILURE(1035b1.DoB(2),1036" Expected arg #0: is equal to 1\n"1037" Actual: 2\n"1038" Expected: to be called once\n"1039" Actual: called once - saturated and active");1040}10411042// Tests that Google Mock explains that an retired expectation doesn't1043// match the call.1044TEST(UnexpectedCallTest, RetiredExpectation) {1045MockB b;1046EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();10471048b.DoB(1);1049EXPECT_NONFATAL_FAILURE(b.DoB(1),1050" Expected: the expectation is active\n"1051" Actual: it is retired");1052}10531054// Tests that Google Mock explains that an expectation that doesn't1055// match the arguments doesn't match the call.1056TEST(UnexpectedCallTest, UnmatchedArguments) {1057MockB b;1058EXPECT_CALL(b, DoB(1));10591060EXPECT_NONFATAL_FAILURE(b.DoB(2),1061" Expected arg #0: is equal to 1\n"1062" Actual: 2\n");1063b.DoB(1);1064}10651066// Tests that Google Mock explains that an expectation with1067// unsatisfied pre-requisites doesn't match the call.1068TEST(UnexpectedCallTest, UnsatisfiedPrerequisites) {1069Sequence s1, s2;1070MockB b;1071EXPECT_CALL(b, DoB(1)).InSequence(s1);1072EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);1073EXPECT_CALL(b, DoB(3)).InSequence(s2);1074EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);10751076::testing::TestPartResultArray failures;1077{1078::testing::ScopedFakeTestPartResultReporter reporter(&failures);1079b.DoB(4);1080// Now 'failures' contains the Google Test failures generated by1081// the above statement.1082}10831084// There should be one non-fatal failure.1085ASSERT_EQ(1, failures.size());1086const ::testing::TestPartResult& r = failures.GetTestPartResult(0);1087EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());10881089// Verifies that the failure message contains the two unsatisfied1090// pre-requisites but not the satisfied one.1091#ifdef GTEST_USES_POSIX_RE1092EXPECT_THAT(r.message(),1093ContainsRegex(1094// POSIX RE doesn't understand the (?s) prefix, but has no1095// trouble with (.|\n).1096"the following immediate pre-requisites are not satisfied:\n"1097"(.|\n)*: pre-requisite #0\n"1098"(.|\n)*: pre-requisite #1"));1099#else1100// We can only use Google Test's own simple regex.1101EXPECT_THAT(r.message(),1102ContainsRegex(1103"the following immediate pre-requisites are not satisfied:"));1104EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));1105EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));1106#endif // GTEST_USES_POSIX_RE11071108b.DoB(1);1109b.DoB(3);1110b.DoB(4);1111}11121113TEST(UndefinedReturnValueTest,1114ReturnValueIsMandatoryWhenNotDefaultConstructible) {1115MockA a;1116// FIXME: We should really verify the output message,1117// but we cannot yet due to that EXPECT_DEATH only captures stderr1118// while Google Mock logs to stdout.1119#if GTEST_HAS_EXCEPTIONS1120EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());1121#else1122EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");1123#endif1124}11251126// Tests that an excessive call (one whose arguments match the1127// matchers but is called too many times) performs the default action.1128TEST(ExcessiveCallTest, DoesDefaultAction) {1129// When there is an ON_CALL() statement, the action specified by it1130// should be taken.1131MockA a;1132ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));1133EXPECT_CALL(a, Binary(0, 0));1134a.Binary(0, 0);1135bool result = false;1136EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),1137"Mock function called more times than expected");1138EXPECT_TRUE(result);11391140// When there is no ON_CALL(), the default value for the return type1141// should be returned.1142MockB b;1143EXPECT_CALL(b, DoB(0)).Description("DoB Method").Times(0);1144int n = -1;1145EXPECT_NONFATAL_FAILURE(1146n = b.DoB(0),1147"Mock function \"DoB Method\" called more times than expected");1148EXPECT_EQ(0, n);1149}11501151// Tests that when a void function is called too many times,1152// the failure message contains the argument values.1153TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {1154MockA a;1155EXPECT_CALL(a, DoA(_)).Description("DoA Method").Times(0);1156EXPECT_NONFATAL_FAILURE(1157a.DoA(9),1158"Mock function \"DoA Method\" called more times than expected - "1159"returning directly.\n"1160" Function call: DoA(9)\n"1161" Expected: to be never called\n"1162" Actual: called once - over-saturated and active");1163}11641165// Tests that when a non-void function is called too many times, the1166// failure message contains the argument values and the return value.1167TEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {1168MockB b;1169EXPECT_CALL(b, DoB(_));1170b.DoB(1);1171EXPECT_NONFATAL_FAILURE(1172b.DoB(2),1173"Mock function called more times than expected - "1174"returning default value.\n"1175" Function call: DoB(2)\n"1176" Returns: 0\n"1177" Expected: to be called once\n"1178" Actual: called twice - over-saturated and active");1179}11801181// Tests using sequences.11821183TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {1184MockA a;1185{1186InSequence dummy;11871188EXPECT_CALL(a, DoA(1));1189EXPECT_CALL(a, DoA(2));1190}11911192EXPECT_NONFATAL_FAILURE(1193{ // NOLINT1194a.DoA(2);1195},1196"Unexpected mock function call");11971198a.DoA(1);1199a.DoA(2);1200}12011202TEST(InSequenceTest, NestedInSequence) {1203MockA a;1204{1205InSequence dummy;12061207EXPECT_CALL(a, DoA(1));1208{1209InSequence dummy2;12101211EXPECT_CALL(a, DoA(2));1212EXPECT_CALL(a, DoA(3));1213}1214}12151216EXPECT_NONFATAL_FAILURE(1217{ // NOLINT1218a.DoA(1);1219a.DoA(3);1220},1221"Unexpected mock function call");12221223a.DoA(2);1224a.DoA(3);1225}12261227TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {1228MockA a;1229{1230InSequence dummy;12311232EXPECT_CALL(a, DoA(1));1233EXPECT_CALL(a, DoA(2));1234}1235EXPECT_CALL(a, DoA(3));12361237EXPECT_NONFATAL_FAILURE(1238{ // NOLINT1239a.DoA(2);1240},1241"Unexpected mock function call");12421243a.DoA(3);1244a.DoA(1);1245a.DoA(2);1246}12471248// Tests that any order is allowed when no sequence is used.1249TEST(SequenceTest, AnyOrderIsOkByDefault) {1250{1251MockA a;1252MockB b;12531254EXPECT_CALL(a, DoA(1));1255EXPECT_CALL(b, DoB()).Times(AnyNumber());12561257a.DoA(1);1258b.DoB();1259}12601261{ // NOLINT1262MockA a;1263MockB b;12641265EXPECT_CALL(a, DoA(1));1266EXPECT_CALL(b, DoB()).Times(AnyNumber());12671268b.DoB();1269a.DoA(1);1270}1271}12721273// Tests that the calls must be in strict order when a complete order1274// is specified.1275TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {1276MockA a;1277ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));12781279Sequence s;1280EXPECT_CALL(a, ReturnResult(1)).InSequence(s);1281EXPECT_CALL(a, ReturnResult(2)).InSequence(s);1282EXPECT_CALL(a, ReturnResult(3)).InSequence(s);12831284a.ReturnResult(1);12851286// May only be called after a.ReturnResult(2).1287EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");12881289a.ReturnResult(2);1290a.ReturnResult(3);1291}12921293// Tests that the calls must be in strict order when a complete order1294// is specified.1295TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {1296MockA a;1297ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));12981299Sequence s;1300EXPECT_CALL(a, ReturnResult(1)).InSequence(s);1301EXPECT_CALL(a, ReturnResult(2)).InSequence(s);13021303// May only be called after a.ReturnResult(1).1304EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");13051306a.ReturnResult(1);1307a.ReturnResult(2);1308}13091310// Tests specifying a DAG using multiple sequences.1311class PartialOrderTest : public testing::Test {1312protected:1313PartialOrderTest() {1314ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result()));13151316// Specifies this partial ordering:1317//1318// a.ReturnResult(1) ==>1319// a.ReturnResult(2) * n ==> a.ReturnResult(3)1320// b.DoB() * 2 ==>1321Sequence x, y;1322EXPECT_CALL(a_, ReturnResult(1)).InSequence(x);1323EXPECT_CALL(b_, DoB()).Times(2).InSequence(y);1324EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y);1325EXPECT_CALL(a_, ReturnResult(3)).InSequence(x);1326}13271328MockA a_;1329MockB b_;1330};13311332TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {1333a_.ReturnResult(1);1334b_.DoB();13351336// May only be called after the second DoB().1337EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");13381339b_.DoB();1340a_.ReturnResult(3);1341}13421343TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {1344// May only be called after ReturnResult(1).1345EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");13461347a_.ReturnResult(1);1348b_.DoB();1349b_.DoB();1350a_.ReturnResult(3);1351}13521353TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {1354// May only be called last.1355EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), "Unexpected mock function call");13561357a_.ReturnResult(1);1358b_.DoB();1359b_.DoB();1360a_.ReturnResult(3);1361}13621363TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {1364a_.ReturnResult(1);1365b_.DoB();1366b_.DoB();1367a_.ReturnResult(3);13681369// May only be called before ReturnResult(3).1370EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");1371}13721373TEST(SequenceTest, Retirement) {1374MockA a;1375Sequence s;13761377EXPECT_CALL(a, DoA(1)).InSequence(s);1378EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation();1379EXPECT_CALL(a, DoA(1)).InSequence(s);13801381a.DoA(1);1382a.DoA(2);1383a.DoA(1);1384}13851386// Tests Expectation.13871388TEST(ExpectationTest, ConstrutorsWork) {1389MockA a;1390Expectation e1; // Default ctor.13911392// Ctor from various forms of EXPECT_CALL.1393Expectation e2 = EXPECT_CALL(a, DoA(2));1394Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);1395{1396Sequence s;1397Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);1398Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);1399}1400Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);1401Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());1402Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());1403Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();14041405Expectation e10 = e2; // Copy ctor.14061407EXPECT_THAT(e1, Ne(e2));1408EXPECT_THAT(e2, Eq(e10));14091410a.DoA(2);1411a.DoA(3);1412a.DoA(4);1413a.DoA(5);1414a.DoA(6);1415a.DoA(7);1416a.DoA(8);1417a.DoA(9);1418}14191420TEST(ExpectationTest, AssignmentWorks) {1421MockA a;1422Expectation e1;1423Expectation e2 = EXPECT_CALL(a, DoA(1));14241425EXPECT_THAT(e1, Ne(e2));14261427e1 = e2;1428EXPECT_THAT(e1, Eq(e2));14291430a.DoA(1);1431}14321433// Tests ExpectationSet.14341435TEST(ExpectationSetTest, MemberTypesAreCorrect) {1436::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();1437}14381439TEST(ExpectationSetTest, ConstructorsWork) {1440MockA a;14411442Expectation e1;1443const Expectation e2;1444ExpectationSet es1; // Default ctor.1445ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.1446ExpectationSet es3 = e1; // Ctor from Expectation.1447ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.1448ExpectationSet es5 = e2; // Ctor from const Expectation.1449ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.1450ExpectationSet es7 = es2; // Copy ctor.14511452EXPECT_EQ(0, es1.size());1453EXPECT_EQ(1, es2.size());1454EXPECT_EQ(1, es3.size());1455EXPECT_EQ(1, es4.size());1456EXPECT_EQ(1, es5.size());1457EXPECT_EQ(1, es6.size());1458EXPECT_EQ(1, es7.size());14591460EXPECT_THAT(es3, Ne(es2));1461EXPECT_THAT(es4, Eq(es3));1462EXPECT_THAT(es5, Eq(es4));1463EXPECT_THAT(es6, Eq(es5));1464EXPECT_THAT(es7, Eq(es2));1465a.DoA(1);1466}14671468TEST(ExpectationSetTest, AssignmentWorks) {1469ExpectationSet es1;1470ExpectationSet es2 = Expectation();14711472es1 = es2;1473EXPECT_EQ(1, es1.size());1474EXPECT_THAT(*(es1.begin()), Eq(Expectation()));1475EXPECT_THAT(es1, Eq(es2));1476}14771478TEST(ExpectationSetTest, InsertionWorks) {1479ExpectationSet es1;1480Expectation e1;1481es1 += e1;1482EXPECT_EQ(1, es1.size());1483EXPECT_THAT(*(es1.begin()), Eq(e1));14841485MockA a;1486Expectation e2 = EXPECT_CALL(a, DoA(1));1487es1 += e2;1488EXPECT_EQ(2, es1.size());14891490ExpectationSet::const_iterator it1 = es1.begin();1491ExpectationSet::const_iterator it2 = it1;1492++it2;1493EXPECT_TRUE(*it1 == e1 || *it2 == e1); // e1 must be in the set.1494EXPECT_TRUE(*it1 == e2 || *it2 == e2); // e2 must be in the set too.1495a.DoA(1);1496}14971498TEST(ExpectationSetTest, SizeWorks) {1499ExpectationSet es;1500EXPECT_EQ(0, es.size());15011502es += Expectation();1503EXPECT_EQ(1, es.size());15041505MockA a;1506es += EXPECT_CALL(a, DoA(1));1507EXPECT_EQ(2, es.size());15081509a.DoA(1);1510}15111512TEST(ExpectationSetTest, IsEnumerable) {1513ExpectationSet es;1514EXPECT_TRUE(es.begin() == es.end());15151516es += Expectation();1517ExpectationSet::const_iterator it = es.begin();1518EXPECT_TRUE(it != es.end());1519EXPECT_THAT(*it, Eq(Expectation()));1520++it;1521EXPECT_TRUE(it == es.end());1522}15231524// Tests the .After() clause.15251526TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {1527MockA a;1528ExpectationSet es;1529es += EXPECT_CALL(a, DoA(1));1530es += EXPECT_CALL(a, DoA(2));1531EXPECT_CALL(a, DoA(3)).After(es);15321533a.DoA(1);1534a.DoA(2);1535a.DoA(3);1536}15371538TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {1539MockA a;1540MockB b;1541// The following also verifies that const Expectation objects work1542// too. Do not remove the const modifiers.1543const Expectation e1 = EXPECT_CALL(a, DoA(1));1544const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);1545EXPECT_CALL(a, DoA(2)).After(e2);15461547a.DoA(1);1548b.DoB();1549b.DoB();1550a.DoA(2);1551}15521553// Calls must be in strict order when specified so using .After().1554TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {1555MockA a;1556MockB b;15571558// Define ordering:1559// a.DoA(1) ==> b.DoB() ==> a.DoA(2)1560Expectation e1 = EXPECT_CALL(a, DoA(1));1561Expectation e2 = EXPECT_CALL(b, DoB()).After(e1);1562EXPECT_CALL(a, DoA(2)).After(e2);15631564a.DoA(1);15651566// May only be called after DoB().1567EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");15681569b.DoB();1570a.DoA(2);1571}15721573// Calls must be in strict order when specified so using .After().1574TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {1575MockA a;1576MockB b;15771578// Define ordering:1579// a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)1580Expectation e1 = EXPECT_CALL(a, DoA(1));1581Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);1582EXPECT_CALL(a, DoA(2)).After(e2);15831584a.DoA(1);1585b.DoB();15861587// May only be called after the second DoB().1588EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");15891590b.DoB();1591a.DoA(2);1592}15931594// Calls must satisfy the partial order when specified so.1595TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {1596MockA a;1597ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));15981599// Define ordering:1600// a.DoA(1) ==>1601// a.DoA(2) ==> a.ReturnResult(3)1602Expectation e = EXPECT_CALL(a, DoA(1));1603const ExpectationSet es = EXPECT_CALL(a, DoA(2));1604EXPECT_CALL(a, ReturnResult(3)).After(e, es);16051606// May only be called last.1607EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");16081609a.DoA(2);1610a.DoA(1);1611a.ReturnResult(3);1612}16131614// Calls must satisfy the partial order when specified so.1615TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {1616MockA a;16171618// Define ordering:1619// a.DoA(1) ==>1620// a.DoA(2) ==> a.DoA(3)1621Expectation e = EXPECT_CALL(a, DoA(1));1622const ExpectationSet es = EXPECT_CALL(a, DoA(2));1623EXPECT_CALL(a, DoA(3)).After(e, es);16241625a.DoA(2);16261627// May only be called last.1628EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");16291630a.DoA(1);1631a.DoA(3);1632}16331634// .After() can be combined with .InSequence().1635TEST(AfterTest, CanBeUsedWithInSequence) {1636MockA a;1637Sequence s;1638Expectation e = EXPECT_CALL(a, DoA(1));1639EXPECT_CALL(a, DoA(2)).InSequence(s);1640EXPECT_CALL(a, DoA(3)).InSequence(s).After(e);16411642a.DoA(1);16431644// May only be after DoA(2).1645EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");16461647a.DoA(2);1648a.DoA(3);1649}16501651// .After() can be called multiple times.1652TEST(AfterTest, CanBeCalledManyTimes) {1653MockA a;1654Expectation e1 = EXPECT_CALL(a, DoA(1));1655Expectation e2 = EXPECT_CALL(a, DoA(2));1656Expectation e3 = EXPECT_CALL(a, DoA(3));1657EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3);16581659a.DoA(3);1660a.DoA(1);1661a.DoA(2);1662a.DoA(4);1663}16641665// .After() accepts up to 5 arguments.1666TEST(AfterTest, AcceptsUpToFiveArguments) {1667MockA a;1668Expectation e1 = EXPECT_CALL(a, DoA(1));1669Expectation e2 = EXPECT_CALL(a, DoA(2));1670Expectation e3 = EXPECT_CALL(a, DoA(3));1671ExpectationSet es1 = EXPECT_CALL(a, DoA(4));1672ExpectationSet es2 = EXPECT_CALL(a, DoA(5));1673EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2);16741675a.DoA(5);1676a.DoA(2);1677a.DoA(4);1678a.DoA(1);1679a.DoA(3);1680a.DoA(6);1681}16821683// .After() allows input to contain duplicated Expectations.1684TEST(AfterTest, AcceptsDuplicatedInput) {1685MockA a;1686ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));16871688// Define ordering:1689// DoA(1) ==>1690// DoA(2) ==> ReturnResult(3)1691Expectation e1 = EXPECT_CALL(a, DoA(1));1692Expectation e2 = EXPECT_CALL(a, DoA(2));1693ExpectationSet es;1694es += e1;1695es += e2;1696EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1);16971698a.DoA(1);16991700// May only be after DoA(2).1701EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");17021703a.DoA(2);1704a.ReturnResult(3);1705}17061707// An Expectation added to an ExpectationSet after it has been used in1708// an .After() has no effect.1709TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {1710MockA a;1711ExpectationSet es1 = EXPECT_CALL(a, DoA(1));1712Expectation e2 = EXPECT_CALL(a, DoA(2));1713EXPECT_CALL(a, DoA(3)).After(es1);1714es1 += e2;17151716a.DoA(1);1717a.DoA(3);1718a.DoA(2);1719}17201721// Tests that Google Mock correctly handles calls to mock functions1722// after a mock object owning one of their pre-requisites has died.17231724// Tests that calls that satisfy the original spec are successful.1725TEST(DeletingMockEarlyTest, Success1) {1726MockB* const b1 = new MockB;1727MockA* const a = new MockA;1728MockB* const b2 = new MockB;17291730{1731InSequence dummy;1732EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));1733EXPECT_CALL(*a, Binary(_, _))1734.Times(AnyNumber())1735.WillRepeatedly(Return(true));1736EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));1737}17381739EXPECT_EQ(1, b1->DoB(1));1740delete b1;1741// a's pre-requisite has died.1742EXPECT_TRUE(a->Binary(0, 1));1743delete b2;1744// a's successor has died.1745EXPECT_TRUE(a->Binary(1, 2));1746delete a;1747}17481749// Tests that calls that satisfy the original spec are successful.1750TEST(DeletingMockEarlyTest, Success2) {1751MockB* const b1 = new MockB;1752MockA* const a = new MockA;1753MockB* const b2 = new MockB;17541755{1756InSequence dummy;1757EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));1758EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());1759EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));1760}17611762delete a; // a is trivially satisfied.1763EXPECT_EQ(1, b1->DoB(1));1764EXPECT_EQ(2, b2->DoB(2));1765delete b1;1766delete b2;1767}17681769// Tests that it's OK to delete a mock object itself in its action.17701771// Suppresses warning on unreferenced formal parameter in MSVC with1772// -W4.1773GTEST_DISABLE_MSC_WARNINGS_PUSH_(4100)17741775ACTION_P(Delete, ptr) { delete ptr; }17761777GTEST_DISABLE_MSC_WARNINGS_POP_() // 410017781779TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {1780MockA* const a = new MockA;1781EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));1782a->DoA(42); // This will cause a to be deleted.1783}17841785TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {1786MockA* const a = new MockA;1787EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));1788a->ReturnResult(42); // This will cause a to be deleted.1789}17901791// Tests that calls that violate the original spec yield failures.1792TEST(DeletingMockEarlyTest, Failure1) {1793MockB* const b1 = new MockB;1794MockA* const a = new MockA;1795MockB* const b2 = new MockB;17961797{1798InSequence dummy;1799EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));1800EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());1801EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));1802}18031804delete a; // a is trivially satisfied.1805EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call");1806EXPECT_EQ(1, b1->DoB(1));1807delete b1;1808delete b2;1809}18101811// Tests that calls that violate the original spec yield failures.1812TEST(DeletingMockEarlyTest, Failure2) {1813MockB* const b1 = new MockB;1814MockA* const a = new MockA;1815MockB* const b2 = new MockB;18161817{1818InSequence dummy;1819EXPECT_CALL(*b1, DoB(_));1820EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());1821EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());1822}18231824EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called");1825EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call");1826EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call");1827delete a;1828delete b2;1829}18301831class EvenNumberCardinality : public CardinalityInterface {1832public:1833// Returns true if and only if call_count calls will satisfy this1834// cardinality.1835bool IsSatisfiedByCallCount(int call_count) const override {1836return call_count % 2 == 0;1837}18381839// Returns true if and only if call_count calls will saturate this1840// cardinality.1841bool IsSaturatedByCallCount(int /* call_count */) const override {1842return false;1843}18441845// Describes self to an ostream.1846void DescribeTo(::std::ostream* os) const override {1847*os << "called even number of times";1848}1849};18501851Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }18521853TEST(ExpectationBaseTest,1854AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {1855MockA* a = new MockA;1856Sequence s;18571858EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);1859EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);1860EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());18611862a->DoA(3);1863a->DoA(1);1864EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");1865EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");1866}18671868// The following tests verify the message generated when a mock1869// function is called.18701871struct Printable {};18721873inline void operator<<(::std::ostream& os, const Printable&) {1874os << "Printable";1875}18761877struct Unprintable {1878Unprintable() : value(0) {}1879int value;1880};18811882class MockC {1883public:1884MockC() = default;18851886MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,1887const Printable& x, Unprintable y));1888MOCK_METHOD0(NonVoidMethod, int()); // NOLINT18891890private:1891MockC(const MockC&) = delete;1892MockC& operator=(const MockC&) = delete;1893};18941895class VerboseFlagPreservingFixture : public testing::Test {1896protected:1897VerboseFlagPreservingFixture()1898: saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}18991900~VerboseFlagPreservingFixture() override {1901GMOCK_FLAG_SET(verbose, saved_verbose_flag_);1902}19031904private:1905const std::string saved_verbose_flag_;19061907VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;1908VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =1909delete;1910};19111912#if GTEST_HAS_STREAM_REDIRECTION19131914// Tests that an uninteresting mock function call on a naggy mock1915// generates a warning without the stack trace when1916// --gmock_verbose=warning is specified.1917TEST(FunctionCallMessageTest,1918UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {1919GMOCK_FLAG_SET(verbose, kWarningVerbosity);1920NaggyMock<MockC> c;1921CaptureStdout();1922c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());1923const std::string output = GetCapturedStdout();1924EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);1925EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);1926}19271928// Tests that an uninteresting mock function call on a naggy mock1929// generates a warning containing the stack trace when1930// --gmock_verbose=info is specified.1931TEST(FunctionCallMessageTest,1932UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {1933GMOCK_FLAG_SET(verbose, kInfoVerbosity);1934NaggyMock<MockC> c;1935CaptureStdout();1936c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());1937const std::string output = GetCapturedStdout();1938EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);1939EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);19401941#ifndef NDEBUG19421943// We check the stack trace content in dbg-mode only, as opt-mode1944// may inline the call we are interested in seeing.19451946// Verifies that a void mock function's name appears in the stack1947// trace.1948EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);19491950// Verifies that a non-void mock function's name appears in the1951// stack trace.1952CaptureStdout();1953c.NonVoidMethod();1954const std::string output2 = GetCapturedStdout();1955EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);19561957#endif // NDEBUG1958}19591960// Tests that an uninteresting mock function call on a naggy mock1961// causes the function arguments and return value to be printed.1962TEST(FunctionCallMessageTest,1963UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {1964// A non-void mock function.1965NaggyMock<MockB> b;1966CaptureStdout();1967b.DoB();1968const std::string output1 = GetCapturedStdout();1969EXPECT_PRED_FORMAT2(1970IsSubstring,1971"Uninteresting mock function call - returning default value.\n"1972" Function call: DoB()\n"1973" Returns: 0\n",1974output1.c_str());1975// Makes sure the return value is printed.19761977// A void mock function.1978NaggyMock<MockC> c;1979CaptureStdout();1980c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());1981const std::string output2 = GetCapturedStdout();1982EXPECT_THAT(1983output2.c_str(),1984ContainsRegex("Uninteresting mock function call - returning directly\\.\n"1985" Function call: VoidMethod"1986"\\(false, 5, \"Hi\", NULL, @.+ "1987"Printable, 4-byte object <00-00 00-00>\\)"));1988// A void function has no return value to print.1989}19901991// Tests how the --gmock_verbose flag affects Google Mock's output.19921993class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {1994public:1995// Verifies that the given Google Mock output is correct. (When1996// should_print is true, the output should match the given regex and1997// contain the given function name in the stack trace. When it's1998// false, the output should be empty.)1999void VerifyOutput(const std::string& output, bool should_print,2000const std::string& expected_substring,2001const std::string& function_name) {2002if (should_print) {2003EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));2004#ifndef NDEBUG2005// We check the stack trace content in dbg-mode only, as opt-mode2006// may inline the call we are interested in seeing.2007EXPECT_THAT(output.c_str(), HasSubstr(function_name));2008#else2009// Suppresses 'unused function parameter' warnings.2010static_cast<void>(function_name);2011#endif // NDEBUG2012} else {2013EXPECT_STREQ("", output.c_str());2014}2015}20162017// Tests how the flag affects expected calls.2018void TestExpectedCall(bool should_print) {2019MockA a;2020EXPECT_CALL(a, DoA(5));2021EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));20222023// A void-returning function.2024CaptureStdout();2025a.DoA(5);2026VerifyOutput(GetCapturedStdout(), should_print,2027"Mock function call matches EXPECT_CALL(a, DoA(5))...\n"2028" Function call: DoA(5)\n"2029"Stack trace:\n",2030"DoA");20312032// A non-void-returning function.2033CaptureStdout();2034a.Binary(2, 1);2035VerifyOutput(GetCapturedStdout(), should_print,2036"Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"2037" Function call: Binary(2, 1)\n"2038" Returns: true\n"2039"Stack trace:\n",2040"Binary");2041}20422043// Tests how the flag affects uninteresting calls on a naggy mock.2044void TestUninterestingCallOnNaggyMock(bool should_print) {2045NaggyMock<MockA> a;2046const std::string note =2047"NOTE: You can safely ignore the above warning unless this "2048"call should not happen. Do not suppress it by blindly adding "2049"an EXPECT_CALL() if you don't mean to enforce the call. "2050"See "2051"https://github.com/google/googletest/blob/main/docs/"2052"gmock_cook_book.md#"2053"knowing-when-to-expect-useoncall for details.";20542055// A void-returning function.2056CaptureStdout();2057a.DoA(5);2058VerifyOutput(GetCapturedStdout(), should_print,2059"\nGMOCK WARNING:\n"2060"Uninteresting mock function call - returning directly.\n"2061" Function call: DoA(5)\n" +2062note,2063"DoA");20642065// A non-void-returning function.2066CaptureStdout();2067a.Binary(2, 1);2068VerifyOutput(GetCapturedStdout(), should_print,2069"\nGMOCK WARNING:\n"2070"Uninteresting mock function call - returning default value.\n"2071" Function call: Binary(2, 1)\n"2072" Returns: false\n" +2073note,2074"Binary");2075}2076};20772078// Tests that --gmock_verbose=info causes both expected and2079// uninteresting calls to be reported.2080TEST_F(GMockVerboseFlagTest, Info) {2081GMOCK_FLAG_SET(verbose, kInfoVerbosity);2082TestExpectedCall(true);2083TestUninterestingCallOnNaggyMock(true);2084}20852086// Tests that --gmock_verbose=warning causes uninteresting calls to be2087// reported.2088TEST_F(GMockVerboseFlagTest, Warning) {2089GMOCK_FLAG_SET(verbose, kWarningVerbosity);2090TestExpectedCall(false);2091TestUninterestingCallOnNaggyMock(true);2092}20932094// Tests that --gmock_verbose=warning causes neither expected nor2095// uninteresting calls to be reported.2096TEST_F(GMockVerboseFlagTest, Error) {2097GMOCK_FLAG_SET(verbose, kErrorVerbosity);2098TestExpectedCall(false);2099TestUninterestingCallOnNaggyMock(false);2100}21012102// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect2103// as --gmock_verbose=warning.2104TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {2105GMOCK_FLAG_SET(verbose, "invalid"); // Treated as "warning".2106TestExpectedCall(false);2107TestUninterestingCallOnNaggyMock(true);2108}21092110#endif // GTEST_HAS_STREAM_REDIRECTION21112112// A helper class that generates a failure when printed. We use it to2113// ensure that Google Mock doesn't print a value (even to an internal2114// buffer) when it is not supposed to do so.2115class PrintMeNot {};21162117void PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {2118ADD_FAILURE() << "Google Mock is printing a value that shouldn't be "2119<< "printed even to an internal buffer.";2120}21212122class LogTestHelper {2123public:2124LogTestHelper() = default;21252126MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));21272128private:2129LogTestHelper(const LogTestHelper&) = delete;2130LogTestHelper& operator=(const LogTestHelper&) = delete;2131};21322133class GMockLogTest : public VerboseFlagPreservingFixture {2134protected:2135LogTestHelper helper_;2136};21372138TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {2139GMOCK_FLAG_SET(verbose, kWarningVerbosity);2140EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));2141helper_.Foo(PrintMeNot()); // This is an expected call.2142}21432144TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {2145GMOCK_FLAG_SET(verbose, kErrorVerbosity);2146EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));2147helper_.Foo(PrintMeNot()); // This is an expected call.2148}21492150TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {2151GMOCK_FLAG_SET(verbose, kErrorVerbosity);2152ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));2153helper_.Foo(PrintMeNot()); // This should generate a warning.2154}21552156// Tests Mock::AllowLeak().21572158TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {2159MockA* a = new MockA;2160Mock::AllowLeak(a);2161}21622163TEST(AllowLeakTest, CanBeCalledBeforeOnCall) {2164MockA* a = new MockA;2165Mock::AllowLeak(a);2166ON_CALL(*a, DoA(_)).WillByDefault(Return());2167a->DoA(0);2168}21692170TEST(AllowLeakTest, CanBeCalledAfterOnCall) {2171MockA* a = new MockA;2172ON_CALL(*a, DoA(_)).WillByDefault(Return());2173Mock::AllowLeak(a);2174}21752176TEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {2177MockA* a = new MockA;2178Mock::AllowLeak(a);2179EXPECT_CALL(*a, DoA(_));2180a->DoA(0);2181}21822183TEST(AllowLeakTest, CanBeCalledAfterExpectCall) {2184MockA* a = new MockA;2185EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());2186Mock::AllowLeak(a);2187}21882189TEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {2190MockA* a = new MockA;2191ON_CALL(*a, DoA(_)).WillByDefault(Return());2192EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());2193Mock::AllowLeak(a);2194}21952196// Tests that we can verify and clear a mock object's expectations2197// when none of its methods has expectations.2198TEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {2199MockB b;2200ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));22012202// There should be no expectations on the methods now, so we can2203// freely call them.2204EXPECT_EQ(0, b.DoB());2205EXPECT_EQ(0, b.DoB(1));2206}22072208// Tests that we can verify and clear a mock object's expectations2209// when some, but not all, of its methods have expectations *and* the2210// verification succeeds.2211TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {2212MockB b;2213EXPECT_CALL(b, DoB()).WillOnce(Return(1));2214b.DoB();2215ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));22162217// There should be no expectations on the methods now, so we can2218// freely call them.2219EXPECT_EQ(0, b.DoB());2220EXPECT_EQ(0, b.DoB(1));2221}22222223// Tests that we can verify and clear a mock object's expectations2224// when some, but not all, of its methods have expectations *and* the2225// verification fails.2226TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {2227MockB b;2228EXPECT_CALL(b, DoB()).WillOnce(Return(1));2229bool result = true;2230EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),2231"Actual: never called");2232ASSERT_FALSE(result);22332234// There should be no expectations on the methods now, so we can2235// freely call them.2236EXPECT_EQ(0, b.DoB());2237EXPECT_EQ(0, b.DoB(1));2238}22392240// Tests that we can verify and clear a mock object's expectations2241// when all of its methods have expectations.2242TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {2243MockB b;2244EXPECT_CALL(b, DoB()).WillOnce(Return(1));2245EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));2246b.DoB();2247b.DoB(1);2248ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));22492250// There should be no expectations on the methods now, so we can2251// freely call them.2252EXPECT_EQ(0, b.DoB());2253EXPECT_EQ(0, b.DoB(1));2254}22552256// Tests that we can verify and clear a mock object's expectations2257// when a method has more than one expectation.2258TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {2259MockB b;2260EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));2261EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));2262b.DoB(1);2263bool result = true;2264EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),2265"Actual: never called");2266ASSERT_FALSE(result);22672268// There should be no expectations on the methods now, so we can2269// freely call them.2270EXPECT_EQ(0, b.DoB());2271EXPECT_EQ(0, b.DoB(1));2272}22732274// Tests that we can call VerifyAndClearExpectations() on the same2275// mock object multiple times.2276TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {2277MockB b;2278EXPECT_CALL(b, DoB());2279b.DoB();2280Mock::VerifyAndClearExpectations(&b);22812282EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));2283b.DoB(1);2284Mock::VerifyAndClearExpectations(&b);2285Mock::VerifyAndClearExpectations(&b);22862287// There should be no expectations on the methods now, so we can2288// freely call them.2289EXPECT_EQ(0, b.DoB());2290EXPECT_EQ(0, b.DoB(1));2291}22922293// Tests that we can clear a mock object's default actions when none2294// of its methods has default actions.2295TEST(VerifyAndClearTest, NoMethodHasDefaultActions) {2296MockB b;2297// If this crashes or generates a failure, the test will catch it.2298Mock::VerifyAndClear(&b);2299EXPECT_EQ(0, b.DoB());2300}23012302// Tests that we can clear a mock object's default actions when some,2303// but not all of its methods have default actions.2304TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {2305MockB b;2306ON_CALL(b, DoB()).WillByDefault(Return(1));23072308Mock::VerifyAndClear(&b);23092310// Verifies that the default action of int DoB() was removed.2311EXPECT_EQ(0, b.DoB());2312}23132314// Tests that we can clear a mock object's default actions when all of2315// its methods have default actions.2316TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {2317MockB b;2318ON_CALL(b, DoB()).WillByDefault(Return(1));2319ON_CALL(b, DoB(_)).WillByDefault(Return(2));23202321Mock::VerifyAndClear(&b);23222323// Verifies that the default action of int DoB() was removed.2324EXPECT_EQ(0, b.DoB());23252326// Verifies that the default action of int DoB(int) was removed.2327EXPECT_EQ(0, b.DoB(0));2328}23292330// Tests that we can clear a mock object's default actions when a2331// method has more than one ON_CALL() set on it.2332TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {2333MockB b;2334ON_CALL(b, DoB(0)).WillByDefault(Return(1));2335ON_CALL(b, DoB(_)).WillByDefault(Return(2));23362337Mock::VerifyAndClear(&b);23382339// Verifies that the default actions (there are two) of int DoB(int)2340// were removed.2341EXPECT_EQ(0, b.DoB(0));2342EXPECT_EQ(0, b.DoB(1));2343}23442345// Tests that we can call VerifyAndClear() on a mock object multiple2346// times.2347TEST(VerifyAndClearTest, CanCallManyTimes) {2348MockB b;2349ON_CALL(b, DoB()).WillByDefault(Return(1));2350Mock::VerifyAndClear(&b);2351Mock::VerifyAndClear(&b);23522353ON_CALL(b, DoB(_)).WillByDefault(Return(1));2354Mock::VerifyAndClear(&b);23552356EXPECT_EQ(0, b.DoB());2357EXPECT_EQ(0, b.DoB(1));2358}23592360// Tests that VerifyAndClear() works when the verification succeeds.2361TEST(VerifyAndClearTest, Success) {2362MockB b;2363ON_CALL(b, DoB()).WillByDefault(Return(1));2364EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));23652366b.DoB();2367b.DoB(1);2368ASSERT_TRUE(Mock::VerifyAndClear(&b));23692370// There should be no expectations on the methods now, so we can2371// freely call them.2372EXPECT_EQ(0, b.DoB());2373EXPECT_EQ(0, b.DoB(1));2374}23752376// Tests that VerifyAndClear() works when the verification fails.2377TEST(VerifyAndClearTest, Failure) {2378MockB b;2379ON_CALL(b, DoB(_)).WillByDefault(Return(1));2380EXPECT_CALL(b, DoB()).WillOnce(Return(2));23812382b.DoB(1);2383bool result = true;2384EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),2385"Actual: never called");2386ASSERT_FALSE(result);23872388// There should be no expectations on the methods now, so we can2389// freely call them.2390EXPECT_EQ(0, b.DoB());2391EXPECT_EQ(0, b.DoB(1));2392}23932394// Tests that VerifyAndClear() works when the default actions and2395// expectations are set on a const mock object.2396TEST(VerifyAndClearTest, Const) {2397MockB b;2398ON_CALL(Const(b), DoB()).WillByDefault(Return(1));23992400EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));24012402b.DoB();2403b.DoB();2404ASSERT_TRUE(Mock::VerifyAndClear(&b));24052406// There should be no expectations on the methods now, so we can2407// freely call them.2408EXPECT_EQ(0, b.DoB());2409EXPECT_EQ(0, b.DoB(1));2410}24112412// Tests that we can set default actions and expectations on a mock2413// object after VerifyAndClear() has been called on it.2414TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {2415MockB b;2416ON_CALL(b, DoB()).WillByDefault(Return(1));2417EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));2418b.DoB(1);24192420Mock::VerifyAndClear(&b);24212422EXPECT_CALL(b, DoB()).WillOnce(Return(3));2423ON_CALL(b, DoB(_)).WillByDefault(Return(4));24242425EXPECT_EQ(3, b.DoB());2426EXPECT_EQ(4, b.DoB(1));2427}24282429// Tests that calling VerifyAndClear() on one mock object does not2430// affect other mock objects (either of the same type or not).2431TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {2432MockA a;2433MockB b1;2434MockB b2;24352436ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));2437EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));24382439ON_CALL(b1, DoB()).WillByDefault(Return(1));2440EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));24412442ON_CALL(b2, DoB()).WillByDefault(Return(3));2443EXPECT_CALL(b2, DoB(_));24442445b2.DoB(0);2446Mock::VerifyAndClear(&b2);24472448// Verifies that the default actions and expectations of a and b12449// are still in effect.2450EXPECT_TRUE(a.Binary(0, 0));2451EXPECT_FALSE(a.Binary(0, 0));24522453EXPECT_EQ(1, b1.DoB());2454EXPECT_EQ(2, b1.DoB(0));2455}24562457TEST(VerifyAndClearTest,2458DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {2459std::shared_ptr<MockA> a(new MockA);2460ReferenceHoldingMock test_mock;24612462// EXPECT_CALL stores a reference to a inside test_mock.2463EXPECT_CALL(test_mock, AcceptReference(_))2464.WillRepeatedly(SetArgPointee<0>(a));24652466// Throw away the reference to the mock that we have in a. After this, the2467// only reference to it is stored by test_mock.2468a.reset();24692470// When test_mock goes out of scope, it destroys the last remaining reference2471// to the mock object originally pointed to by a. This will cause the MockA2472// destructor to be called from inside the ReferenceHoldingMock destructor.2473// The state of all mocks is protected by a single global lock, but there2474// should be no deadlock.2475}24762477TEST(VerifyAndClearTest,2478DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {2479std::shared_ptr<MockA> a(new MockA);2480ReferenceHoldingMock test_mock;24812482// ON_CALL stores a reference to a inside test_mock.2483ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));24842485// Throw away the reference to the mock that we have in a. After this, the2486// only reference to it is stored by test_mock.2487a.reset();24882489// When test_mock goes out of scope, it destroys the last remaining reference2490// to the mock object originally pointed to by a. This will cause the MockA2491// destructor to be called from inside the ReferenceHoldingMock destructor.2492// The state of all mocks is protected by a single global lock, but there2493// should be no deadlock.2494}24952496// Tests that a mock function's action can call a mock function2497// (either the same function or a different one) either as an explicit2498// action or as a default action without causing a dead lock. It2499// verifies that the action is not performed inside the critical2500// section.2501TEST(SynchronizationTest, CanCallMockMethodInAction) {2502MockA a;2503MockC c;2504ON_CALL(a, DoA(_)).WillByDefault(2505IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));2506EXPECT_CALL(a, DoA(1));2507EXPECT_CALL(a, DoA(1))2508.WillOnce(Invoke(&a, &MockA::DoA))2509.RetiresOnSaturation();2510EXPECT_CALL(c, NonVoidMethod());25112512a.DoA(1);2513// This will match the second EXPECT_CALL() and trigger another a.DoA(1),2514// which will in turn match the first EXPECT_CALL() and trigger a call to2515// c.NonVoidMethod() that was specified by the ON_CALL() since the first2516// EXPECT_CALL() did not specify an action.2517}25182519TEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {2520MockA a;2521int do_a_arg0 = 0;2522ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));2523int do_a_47_arg0 = 0;2524ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));25252526a.DoA(17);2527EXPECT_THAT(do_a_arg0, 17);2528EXPECT_THAT(do_a_47_arg0, 0);2529a.DoA(47);2530EXPECT_THAT(do_a_arg0, 17);2531EXPECT_THAT(do_a_47_arg0, 47);25322533ON_CALL(a, Binary).WillByDefault(Return(true));2534ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));2535EXPECT_THAT(a.Binary(14, 17), true);2536EXPECT_THAT(a.Binary(17, 14), false);2537}25382539TEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {2540MockB b;2541ON_CALL(b, DoB()).WillByDefault(Return(9));2542ON_CALL(b, DoB(5)).WillByDefault(Return(11));25432544EXPECT_THAT(b.DoB(), 9);2545EXPECT_THAT(b.DoB(1), 0); // default value2546EXPECT_THAT(b.DoB(5), 11);2547}25482549struct MockWithConstMethods {2550public:2551MOCK_CONST_METHOD1(Foo, int(int));2552MOCK_CONST_METHOD2(Bar, int(int, const char*));2553};25542555TEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {2556MockWithConstMethods mock;2557ON_CALL(mock, Foo).WillByDefault(Return(7));2558ON_CALL(mock, Bar).WillByDefault(Return(33));25592560EXPECT_THAT(mock.Foo(17), 7);2561EXPECT_THAT(mock.Bar(27, "purple"), 33);2562}25632564class MockConstOverload {2565public:2566MOCK_METHOD1(Overloaded, int(int));2567MOCK_CONST_METHOD1(Overloaded, int(int));2568};25692570TEST(ParameterlessExpectationsTest,2571CanSetExpectationsForConstOverloadedMethods) {2572MockConstOverload mock;2573ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));2574ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));2575ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));2576ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));25772578EXPECT_THAT(mock.Overloaded(1), 7);2579EXPECT_THAT(mock.Overloaded(5), 9);2580EXPECT_THAT(mock.Overloaded(7), 7);25812582const MockConstOverload& const_mock = mock;2583EXPECT_THAT(const_mock.Overloaded(1), 0);2584EXPECT_THAT(const_mock.Overloaded(5), 11);2585EXPECT_THAT(const_mock.Overloaded(7), 13);2586}25872588} // namespace2589} // namespace testing25902591int main(int argc, char** argv) {2592testing::InitGoogleMock(&argc, argv);2593// Ensures that the tests pass no matter what value of2594// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.2595GMOCK_FLAG_SET(catch_leaked_mocks, true);2596GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);25972598return RUN_ALL_TESTS();2599}260026012602