"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "googlemock/test/gmock-spec-builders_test.cc" between
googletest-release-1.11.0.tar.gz and googletest-release-1.12.0.tar.gz

About: GoogleTest is Google's (unit) testing and mocking framework for C++ tests.

gmock-spec-builders_test.cc  (googletest-release-1.11.0):gmock-spec-builders_test.cc  (googletest-release-1.12.0)
skipping to change at line 40 skipping to change at line 40
// Google Mock - a framework for writing C++ mock classes. // Google Mock - a framework for writing C++ mock classes.
// //
// This file tests the spec builder syntax. // This file tests the spec builder syntax.
#include "gmock/gmock-spec-builders.h" #include "gmock/gmock-spec-builders.h"
#include <memory> #include <memory>
#include <ostream> // NOLINT #include <ostream> // NOLINT
#include <sstream> #include <sstream>
#include <string> #include <string>
#include <type_traits>
#include "gmock/gmock.h" #include "gmock/gmock.h"
#include "gmock/internal/gmock-port.h" #include "gmock/internal/gmock-port.h"
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h" #include "gtest/gtest-spi.h"
#include "gtest/gtest.h"
#include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-port.h"
namespace testing { namespace testing {
namespace internal {
// Helper class for testing the Expectation class template.
class ExpectationTester {
public:
// Sets the call count of the given expectation to the given number.
void SetCallCount(int n, ExpectationBase* exp) {
exp->call_count_ = n;
}
};
} // namespace internal
} // namespace testing
namespace { namespace {
using testing::_; using ::testing::internal::FormatFileLocation;
using testing::AnyNumber; using ::testing::internal::kAllow;
using testing::AtLeast; using ::testing::internal::kErrorVerbosity;
using testing::AtMost; using ::testing::internal::kFail;
using testing::Between; using ::testing::internal::kInfoVerbosity;
using testing::Cardinality; using ::testing::internal::kWarn;
using testing::CardinalityInterface; using ::testing::internal::kWarningVerbosity;
using testing::Const;
using testing::ContainsRegex;
using testing::DoAll;
using testing::DoDefault;
using testing::Eq;
using testing::Expectation;
using testing::ExpectationSet;
using testing::GMOCK_FLAG(verbose);
using testing::Gt;
using testing::IgnoreResult;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::IsNotSubstring;
using testing::IsSubstring;
using testing::Lt;
using testing::Message;
using testing::Mock;
using testing::NaggyMock;
using testing::Ne;
using testing::Return;
using testing::SaveArg;
using testing::Sequence;
using testing::SetArgPointee;
using testing::internal::ExpectationTester;
using testing::internal::FormatFileLocation;
using testing::internal::kAllow;
using testing::internal::kErrorVerbosity;
using testing::internal::kFail;
using testing::internal::kInfoVerbosity;
using testing::internal::kWarn;
using testing::internal::kWarningVerbosity;
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
using testing::HasSubstr; using ::testing::internal::CaptureStdout;
using testing::internal::CaptureStdout; using ::testing::internal::GetCapturedStdout;
using testing::internal::GetCapturedStdout;
#endif #endif
class Incomplete; class Incomplete;
class MockIncomplete { class MockIncomplete {
public: public:
// This line verifies that a mock method can take a by-reference // This line verifies that a mock method can take a by-reference
// argument of an incomplete type. // argument of an incomplete type.
MOCK_METHOD1(ByRefFunc, void(const Incomplete& x)); MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));
}; };
// Tells Google Mock how to print a value of type Incomplete. // Tells Google Mock how to print a value of type Incomplete.
void PrintTo(const Incomplete& x, ::std::ostream* os); void PrintTo(const Incomplete& x, ::std::ostream* os);
TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) { TEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {
// Even though this mock class contains a mock method that takes // Even though this mock class contains a mock method that takes
// by-reference an argument whose type is incomplete, we can still // by-reference an argument whose type is incomplete, we can still
// use the mock, as long as Google Mock knows how to print the // use the mock, as long as Google Mock knows how to print the
// argument. // argument.
MockIncomplete incomplete; MockIncomplete incomplete;
EXPECT_CALL(incomplete, ByRefFunc(_)) EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber());
.Times(AnyNumber());
} }
// The definition of the printer for the argument type doesn't have to // The definition of the printer for the argument type doesn't have to
// be visible where the mock is used. // be visible where the mock is used.
void PrintTo(const Incomplete& /* x */, ::std::ostream* os) { void PrintTo(const Incomplete& /* x */, ::std::ostream* os) {
*os << "incomplete"; *os << "incomplete";
} }
class Result {}; class Result {};
skipping to change at line 157 skipping to change at line 110
public: public:
MockA() {} MockA() {}
MOCK_METHOD1(DoA, void(int n)); MOCK_METHOD1(DoA, void(int n));
MOCK_METHOD1(ReturnResult, Result(int n)); MOCK_METHOD1(ReturnResult, Result(int n));
MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible()); MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());
MOCK_METHOD2(Binary, bool(int x, int y)); MOCK_METHOD2(Binary, bool(int x, int y));
MOCK_METHOD2(ReturnInt, int(int x, int y)); MOCK_METHOD2(ReturnInt, int(int x, int y));
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockA); MockA(const MockA&) = delete;
MockA& operator=(const MockA&) = delete;
}; };
class MockB { class MockB {
public: public:
MockB() {} MockB() {}
MOCK_CONST_METHOD0(DoB, int()); // NOLINT MOCK_CONST_METHOD0(DoB, int()); // NOLINT
MOCK_METHOD1(DoB, int(int n)); // NOLINT MOCK_METHOD1(DoB, int(int n)); // NOLINT
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockB); MockB(const MockB&) = delete;
MockB& operator=(const MockB&) = delete;
}; };
class ReferenceHoldingMock { class ReferenceHoldingMock {
public: public:
ReferenceHoldingMock() {} ReferenceHoldingMock() {}
MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*)); MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(ReferenceHoldingMock); ReferenceHoldingMock(const ReferenceHoldingMock&) = delete;
ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete;
}; };
// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro // Tests that EXPECT_CALL and ON_CALL compile in a presence of macro
// redefining a mock method name. This could happen, for example, when // redefining a mock method name. This could happen, for example, when
// the tested code #includes Win32 API headers which define many APIs // the tested code #includes Win32 API headers which define many APIs
// as macros, e.g. #define TextOut TextOutW. // as macros, e.g. #define TextOut TextOutW.
#define Method MethodW #define Method MethodW
class CC { class CC {
skipping to change at line 200 skipping to change at line 156
virtual ~CC() {} virtual ~CC() {}
virtual int Method() = 0; virtual int Method() = 0;
}; };
class MockCC : public CC { class MockCC : public CC {
public: public:
MockCC() {} MockCC() {}
MOCK_METHOD0(Method, int()); MOCK_METHOD0(Method, int());
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockCC); MockCC(const MockCC&) = delete;
MockCC& operator=(const MockCC&) = delete;
}; };
// Tests that a method with expanded name compiles. // Tests that a method with expanded name compiles.
TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) { TEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {
MockCC cc; MockCC cc;
ON_CALL(cc, Method()); ON_CALL(cc, Method());
} }
// Tests that the method with expanded name not only compiles but runs // Tests that the method with expanded name not only compiles but runs
// and returns a correct value, too. // and returns a correct value, too.
skipping to change at line 256 skipping to change at line 213
ON_CALL(a, DoA(n++)); ON_CALL(a, DoA(n++));
EXPECT_EQ(1, n); EXPECT_EQ(1, n);
} }
// Tests that the syntax of ON_CALL() is enforced at run time. // Tests that the syntax of ON_CALL() is enforced at run time.
TEST(OnCallSyntaxTest, WithIsOptional) { TEST(OnCallSyntaxTest, WithIsOptional) {
MockA a; MockA a;
ON_CALL(a, DoA(5)) ON_CALL(a, DoA(5)).WillByDefault(Return());
.WillByDefault(Return()); ON_CALL(a, DoA(_)).With(_).WillByDefault(Return());
ON_CALL(a, DoA(_))
.With(_)
.WillByDefault(Return());
} }
TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) { TEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
ON_CALL(a, ReturnResult(_)) { // NOLINT
.With(_) ON_CALL(a, ReturnResult(_))
.With(_) .With(_)
.WillByDefault(Return(Result())); .With(_)
}, ".With() cannot appear more than once in an ON_CALL()"); .WillByDefault(Return(Result()));
},
".With() cannot appear more than once in an ON_CALL()");
} }
TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) { TEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {
MockA a; MockA a;
EXPECT_DEATH_IF_SUPPORTED({ EXPECT_DEATH_IF_SUPPORTED(
ON_CALL(a, DoA(5)); {
a.DoA(5); ON_CALL(a, DoA(5));
}, ""); a.DoA(5);
},
"");
} }
TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) { TEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
ON_CALL(a, DoA(5)) { // NOLINT
.WillByDefault(Return()) ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return());
.WillByDefault(Return()); },
}, ".WillByDefault() must appear exactly once in an ON_CALL()"); ".WillByDefault() must appear exactly once in an ON_CALL()");
} }
// Tests that EXPECT_CALL evaluates its arguments exactly once as // Tests that EXPECT_CALL evaluates its arguments exactly once as
// promised by Google Mock. // promised by Google Mock.
TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) { TEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {
MockA a; MockA a;
MockA* pa = &a; MockA* pa = &a;
EXPECT_CALL(*pa++, DoA(_)); EXPECT_CALL(*pa++, DoA(_));
a.DoA(0); a.DoA(0);
skipping to change at line 318 skipping to change at line 276
EXPECT_CALL(a, DoA(n++)); EXPECT_CALL(a, DoA(n++));
a.DoA(0); a.DoA(0);
EXPECT_EQ(1, n); EXPECT_EQ(1, n);
} }
// Tests that the syntax of EXPECT_CALL() is enforced at run time. // Tests that the syntax of EXPECT_CALL() is enforced at run time.
TEST(ExpectCallSyntaxTest, WithIsOptional) { TEST(ExpectCallSyntaxTest, WithIsOptional) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(5)) EXPECT_CALL(a, DoA(5)).Times(0);
.Times(0); EXPECT_CALL(a, DoA(6)).With(_).Times(0);
EXPECT_CALL(a, DoA(6))
.With(_)
.Times(0);
} }
TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) { TEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(6)) { // NOLINT
.With(_) EXPECT_CALL(a, DoA(6)).With(_).With(_);
.With(_); },
}, ".With() cannot appear more than once in an EXPECT_CALL()"); ".With() cannot appear more than once in an EXPECT_CALL()");
a.DoA(6); a.DoA(6);
} }
TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) { TEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(1)) { // NOLINT
.Times(1) EXPECT_CALL(a, DoA(1)).Times(1).With(_);
.With(_); },
}, ".With() must be the first clause in an EXPECT_CALL()"); ".With() must be the first clause in an EXPECT_CALL()");
a.DoA(1); a.DoA(1);
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(2)) { // NOLINT
.WillOnce(Return()) EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_);
.With(_); },
}, ".With() must be the first clause in an EXPECT_CALL()"); ".With() must be the first clause in an EXPECT_CALL()");
a.DoA(2); a.DoA(2);
} }
TEST(ExpectCallSyntaxTest, TimesCanBeInferred) { TEST(ExpectCallSyntaxTest, TimesCanBeInferred) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(1)) EXPECT_CALL(a, DoA(1)).WillOnce(Return());
.WillOnce(Return());
EXPECT_CALL(a, DoA(2)) EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
.WillOnce(Return())
.WillRepeatedly(Return());
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
a.DoA(2); a.DoA(2);
} }
TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) { TEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(1)) { // NOLINT
.Times(1) EXPECT_CALL(a, DoA(1)).Times(1).Times(2);
.Times(2); },
}, ".Times() cannot appear more than once in an EXPECT_CALL()"); ".Times() cannot appear more than once in an EXPECT_CALL()");
a.DoA(1); a.DoA(1);
a.DoA(1); a.DoA(1);
} }
TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) { TEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {
MockA a; MockA a;
Sequence s; Sequence s;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(1)) { // NOLINT
.InSequence(s) EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1);
.Times(1); },
}, ".Times() cannot appear after "); ".Times() may only appear *before* ");
a.DoA(1); a.DoA(1);
} }
TEST(ExpectCallSyntaxTest, InSequenceIsOptional) { TEST(ExpectCallSyntaxTest, InSequenceIsOptional) {
MockA a; MockA a;
Sequence s; Sequence s;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2)) EXPECT_CALL(a, DoA(2)).InSequence(s);
.InSequence(s);
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
} }
TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) { TEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {
MockA a; MockA a;
Sequence s1, s2; Sequence s1, s2;
EXPECT_CALL(a, DoA(1)) EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1);
.InSequence(s1, s2)
.InSequence(s1);
a.DoA(1); a.DoA(1);
} }
TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) { TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {
MockA a; MockA a;
Sequence s; Sequence s;
Expectation e = EXPECT_CALL(a, DoA(1)) Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber());
.Times(AnyNumber()); EXPECT_NONFATAL_FAILURE(
EXPECT_NONFATAL_FAILURE({ // NOLINT { // NOLINT
EXPECT_CALL(a, DoA(2)) EXPECT_CALL(a, DoA(2)).After(e).InSequence(s);
.After(e) },
.InSequence(s); ".InSequence() cannot appear after ");
}, ".InSequence() cannot appear after ");
a.DoA(2); a.DoA(2);
} }
TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) { TEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {
MockA a; MockA a;
Sequence s; Sequence s;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(1)) { // NOLINT
.WillOnce(Return()) EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s);
.InSequence(s); },
}, ".InSequence() cannot appear after "); ".InSequence() cannot appear after ");
a.DoA(1); a.DoA(1);
} }
TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) { TEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {
MockA a; MockA a;
Expectation e = EXPECT_CALL(a, DoA(1)); Expectation e = EXPECT_CALL(a, DoA(1));
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(2)) { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); },
.WillOnce(Return()) ".After() cannot appear after ");
.After(e);
}, ".After() cannot appear after ");
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
} }
TEST(ExpectCallSyntaxTest, WillIsOptional) { TEST(ExpectCallSyntaxTest, WillIsOptional) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2)) EXPECT_CALL(a, DoA(2)).WillOnce(Return());
.WillOnce(Return());
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
} }
TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) { TEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(1)) EXPECT_CALL(a, DoA(1))
.Times(AnyNumber()) .Times(AnyNumber())
.WillOnce(Return()) .WillOnce(Return())
.WillOnce(Return()) .WillOnce(Return())
.WillOnce(Return()); .WillOnce(Return());
} }
TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) { TEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(1)) { // NOLINT
.WillRepeatedly(Return()) EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return());
.WillOnce(Return()); },
}, ".WillOnce() cannot appear after "); ".WillOnce() cannot appear after ");
a.DoA(1); a.DoA(1);
} }
TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) { TEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(1)) EXPECT_CALL(a, DoA(1)).WillOnce(Return());
.WillOnce(Return()); EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());
EXPECT_CALL(a, DoA(2))
.WillOnce(Return())
.WillRepeatedly(Return());
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
a.DoA(2); a.DoA(2);
} }
TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) { TEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(1)) { // NOLINT
.WillRepeatedly(Return()) EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly(
.WillRepeatedly(Return()); Return());
}, ".WillRepeatedly() cannot appear more than once in an " },
"EXPECT_CALL()"); ".WillRepeatedly() cannot appear more than once in an "
"EXPECT_CALL()");
} }
TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) { TEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(1)) { // NOLINT
.RetiresOnSaturation() EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return());
.WillRepeatedly(Return()); },
}, ".WillRepeatedly() cannot appear after "); ".WillRepeatedly() cannot appear after ");
} }
TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) { TEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(1)) EXPECT_CALL(a, DoA(1)).RetiresOnSaturation();
.RetiresOnSaturation();
a.DoA(1); a.DoA(1);
a.DoA(1); a.DoA(1);
} }
TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) { TEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {
MockA a; MockA a;
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
EXPECT_CALL(a, DoA(1)) { // NOLINT
.RetiresOnSaturation() EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation();
.RetiresOnSaturation(); },
}, ".RetiresOnSaturation() cannot appear more than once"); ".RetiresOnSaturation() cannot appear more than once");
a.DoA(1); a.DoA(1);
} }
TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) { TEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {
{ {
MockA a; MockA a;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
a.DoA(1); a.DoA(1);
} }
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
MockA a; { // NOLINT
EXPECT_CALL(a, DoA(1)); MockA a;
}, "to be called once"); EXPECT_CALL(a, DoA(1));
EXPECT_NONFATAL_FAILURE({ // NOLINT },
MockA a; "to be called once");
EXPECT_CALL(a, DoA(1)); EXPECT_NONFATAL_FAILURE(
a.DoA(1); { // NOLINT
a.DoA(1); MockA a;
}, "to be called once"); EXPECT_CALL(a, DoA(1));
a.DoA(1);
a.DoA(1);
},
"to be called once");
} }
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
// Tests that Google Mock doesn't print a warning when the number of // Tests that Google Mock doesn't print a warning when the number of
// WillOnce() is adequate. // WillOnce() is adequate.
TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) { TEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {
CaptureStdout(); CaptureStdout();
{ {
MockB b; MockB b;
// It's always fine to omit WillOnce() entirely. // It's always fine to omit WillOnce() entirely.
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).Times(0);
.Times(0); EXPECT_CALL(b, DoB(1)).Times(AtMost(1));
EXPECT_CALL(b, DoB(1)) EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1));
.Times(AtMost(1));
EXPECT_CALL(b, DoB(2))
.Times(1)
.WillRepeatedly(Return(1));
// It's fine for the number of WillOnce()s to equal the upper bound. // It's fine for the number of WillOnce()s to equal the upper bound.
EXPECT_CALL(b, DoB(3)) EXPECT_CALL(b, DoB(3))
.Times(Between(1, 2)) .Times(Between(1, 2))
.WillOnce(Return(1)) .WillOnce(Return(1))
.WillOnce(Return(2)); .WillOnce(Return(2));
// It's fine for the number of WillOnce()s to be smaller than the // It's fine for the number of WillOnce()s to be smaller than the
// upper bound when there is a WillRepeatedly(). // upper bound when there is a WillRepeatedly().
EXPECT_CALL(b, DoB(4)) EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly(
.Times(AtMost(3)) Return(2));
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
// Satisfies the above expectations. // Satisfies the above expectations.
b.DoB(2); b.DoB(2);
b.DoB(3); b.DoB(3);
} }
EXPECT_STREQ("", GetCapturedStdout().c_str()); EXPECT_STREQ("", GetCapturedStdout().c_str());
} }
// Tests that Google Mock warns on having too many actions in an // Tests that Google Mock warns on having too many actions in an
// expectation compared to its cardinality. // expectation compared to its cardinality.
TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) { TEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {
CaptureStdout(); CaptureStdout();
{ {
MockB b; MockB b;
// Warns when the number of WillOnce()s is larger than the upper bound. // Warns when the number of WillOnce()s is larger than the upper bound.
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1)); // #1
.Times(0) EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce(
.WillOnce(Return(1)); // #1 Return(2)); // #2
EXPECT_CALL(b, DoB())
.Times(AtMost(1))
.WillOnce(Return(1))
.WillOnce(Return(2)); // #2
EXPECT_CALL(b, DoB(1)) EXPECT_CALL(b, DoB(1))
.Times(1) .Times(1)
.WillOnce(Return(1)) .WillOnce(Return(1))
.WillOnce(Return(2)) .WillOnce(Return(2))
.RetiresOnSaturation(); // #3 .RetiresOnSaturation(); // #3
// Warns when the number of WillOnce()s equals the upper bound and // Warns when the number of WillOnce()s equals the upper bound and
// there is a WillRepeatedly(). // there is a WillRepeatedly().
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1)); // #4
.Times(0) EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly(
.WillRepeatedly(Return(1)); // #4 Return(2)); // #5
EXPECT_CALL(b, DoB(2))
.Times(1)
.WillOnce(Return(1))
.WillRepeatedly(Return(2)); // #5
// Satisfies the above expectations. // Satisfies the above expectations.
b.DoB(1); b.DoB(1);
b.DoB(2); b.DoB(2);
} }
const std::string output = GetCapturedStdout(); const std::string output = GetCapturedStdout();
EXPECT_PRED_FORMAT2( EXPECT_PRED_FORMAT2(IsSubstring,
IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
"Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be never called, but has 1 WillOnce().",
"Expected to be never called, but has 1 WillOnce().", output); // #1
output); // #1 EXPECT_PRED_FORMAT2(IsSubstring,
EXPECT_PRED_FORMAT2( "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
IsSubstring, "Expected to be called at most once, "
"Too many actions specified in EXPECT_CALL(b, DoB())...\n" "but has 2 WillOnce()s.",
"Expected to be called at most once, " output); // #2
"but has 2 WillOnce()s.",
output); // #2
EXPECT_PRED_FORMAT2( EXPECT_PRED_FORMAT2(
IsSubstring, IsSubstring,
"Too many actions specified in EXPECT_CALL(b, DoB(1))...\n" "Too many actions specified in EXPECT_CALL(b, DoB(1))...\n"
"Expected to be called once, but has 2 WillOnce()s.", "Expected to be called once, but has 2 WillOnce()s.",
output); // #3 output); // #3
EXPECT_PRED_FORMAT2( EXPECT_PRED_FORMAT2(IsSubstring,
IsSubstring, "Too many actions specified in EXPECT_CALL(b, DoB())...\n"
"Too many actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be never called, but has 0 WillOnce()s "
"Expected to be never called, but has 0 WillOnce()s " "and a WillRepeatedly().",
"and a WillRepeatedly().", output); // #4
output); // #4
EXPECT_PRED_FORMAT2( EXPECT_PRED_FORMAT2(
IsSubstring, IsSubstring,
"Too many actions specified in EXPECT_CALL(b, DoB(2))...\n" "Too many actions specified in EXPECT_CALL(b, DoB(2))...\n"
"Expected to be called once, but has 1 WillOnce() " "Expected to be called once, but has 1 WillOnce() "
"and a WillRepeatedly().", "and a WillRepeatedly().",
output); // #5 output); // #5
} }
// Tests that Google Mock warns on having too few actions in an // Tests that Google Mock warns on having too few actions in an
// expectation compared to its cardinality. // expectation compared to its cardinality.
TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) { TEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1));
.Times(Between(2, 3))
.WillOnce(Return(1));
CaptureStdout(); CaptureStdout();
b.DoB(); b.DoB();
const std::string output = GetCapturedStdout(); const std::string output = GetCapturedStdout();
EXPECT_PRED_FORMAT2( EXPECT_PRED_FORMAT2(IsSubstring,
IsSubstring, "Too few actions specified in EXPECT_CALL(b, DoB())...\n"
"Too few actions specified in EXPECT_CALL(b, DoB())...\n" "Expected to be called between 2 and 3 times, "
"Expected to be called between 2 and 3 times, " "but has only 1 WillOnce().",
"but has only 1 WillOnce().", output);
output);
b.DoB(); b.DoB();
} }
TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) { TEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {
int original_behavior = testing::GMOCK_FLAG(default_mock_behavior); int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);
testing::GMOCK_FLAG(default_mock_behavior) = kAllow; GMOCK_FLAG_SET(default_mock_behavior, kAllow);
CaptureStdout(); CaptureStdout();
{ {
MockA a; MockA a;
a.DoA(0); a.DoA(0);
} }
std::string output = GetCapturedStdout(); std::string output = GetCapturedStdout();
EXPECT_TRUE(output.empty()) << output; EXPECT_TRUE(output.empty()) << output;
testing::GMOCK_FLAG(default_mock_behavior) = kWarn; GMOCK_FLAG_SET(default_mock_behavior, kWarn);
CaptureStdout(); CaptureStdout();
{ {
MockA a; MockA a;
a.DoA(0); a.DoA(0);
} }
std::string warning_output = GetCapturedStdout(); std::string warning_output = GetCapturedStdout();
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
warning_output); warning_output);
testing::GMOCK_FLAG(default_mock_behavior) = kFail; GMOCK_FLAG_SET(default_mock_behavior, kFail);
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE(
MockA a; {
a.DoA(0); MockA a;
}, "Uninteresting mock function call"); a.DoA(0);
},
"Uninteresting mock function call");
// Out of bounds values are converted to kWarn // Out of bounds values are converted to kWarn
testing::GMOCK_FLAG(default_mock_behavior) = -1; GMOCK_FLAG_SET(default_mock_behavior, -1);
CaptureStdout(); CaptureStdout();
{ {
MockA a; MockA a;
a.DoA(0); a.DoA(0);
} }
warning_output = GetCapturedStdout(); warning_output = GetCapturedStdout();
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
warning_output); warning_output);
testing::GMOCK_FLAG(default_mock_behavior) = 3; GMOCK_FLAG_SET(default_mock_behavior, 3);
CaptureStdout(); CaptureStdout();
{ {
MockA a; MockA a;
a.DoA(0); a.DoA(0);
} }
warning_output = GetCapturedStdout(); warning_output = GetCapturedStdout();
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", warning_output);
EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call", EXPECT_PRED_FORMAT2(IsSubstring, "Uninteresting mock function call",
warning_output); warning_output);
testing::GMOCK_FLAG(default_mock_behavior) = original_behavior; GMOCK_FLAG_SET(default_mock_behavior, original_behavior);
} }
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
// Tests the semantics of ON_CALL(). // Tests the semantics of ON_CALL().
// Tests that the built-in default action is taken when no ON_CALL() // Tests that the built-in default action is taken when no ON_CALL()
// is specified. // is specified.
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) { TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {
MockB b; MockB b;
EXPECT_CALL(b, DoB()); EXPECT_CALL(b, DoB());
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
} }
// Tests that the built-in default action is taken when no ON_CALL() // Tests that the built-in default action is taken when no ON_CALL()
// matches the invocation. // matches the invocation.
TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) { TEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {
MockB b; MockB b;
ON_CALL(b, DoB(1)) ON_CALL(b, DoB(1)).WillByDefault(Return(1));
.WillByDefault(Return(1));
EXPECT_CALL(b, DoB(_)); EXPECT_CALL(b, DoB(_));
EXPECT_EQ(0, b.DoB(2)); EXPECT_EQ(0, b.DoB(2));
} }
// Tests that the last matching ON_CALL() action is taken. // Tests that the last matching ON_CALL() action is taken.
TEST(OnCallTest, PicksLastMatchingOnCall) { TEST(OnCallTest, PicksLastMatchingOnCall) {
MockB b; MockB b;
ON_CALL(b, DoB(_)) ON_CALL(b, DoB(_)).WillByDefault(Return(3));
.WillByDefault(Return(3)); ON_CALL(b, DoB(2)).WillByDefault(Return(2));
ON_CALL(b, DoB(2)) ON_CALL(b, DoB(1)).WillByDefault(Return(1));
.WillByDefault(Return(2));
ON_CALL(b, DoB(1))
.WillByDefault(Return(1));
EXPECT_CALL(b, DoB(_)); EXPECT_CALL(b, DoB(_));
EXPECT_EQ(2, b.DoB(2)); EXPECT_EQ(2, b.DoB(2));
} }
// Tests the semantics of EXPECT_CALL(). // Tests the semantics of EXPECT_CALL().
// Tests that any call is allowed when no EXPECT_CALL() is specified. // Tests that any call is allowed when no EXPECT_CALL() is specified.
TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) { TEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {
MockB b; MockB b;
skipping to change at line 807 skipping to change at line 731
b.DoB(); b.DoB();
// DoB(int) can be called any number of times. // DoB(int) can be called any number of times.
b.DoB(1); b.DoB(1);
b.DoB(2); b.DoB(2);
} }
// Tests that the last matching EXPECT_CALL() fires. // Tests that the last matching EXPECT_CALL() fires.
TEST(ExpectCallTest, PicksLastMatchingExpectCall) { TEST(ExpectCallTest, PicksLastMatchingExpectCall) {
MockB b; MockB b;
EXPECT_CALL(b, DoB(_)) EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2));
.WillRepeatedly(Return(2)); EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1));
EXPECT_CALL(b, DoB(1))
.WillRepeatedly(Return(1));
EXPECT_EQ(1, b.DoB(1)); EXPECT_EQ(1, b.DoB(1));
} }
// Tests lower-bound violation. // Tests lower-bound violation.
TEST(ExpectCallTest, CatchesTooFewCalls) { TEST(ExpectCallTest, CatchesTooFewCalls) {
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
MockB b; { // NOLINT
EXPECT_CALL(b, DoB(5)) MockB b;
.Times(AtLeast(2)); EXPECT_CALL(b, DoB(5)).Times(AtLeast(2));
b.DoB(5); b.DoB(5);
}, "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n" },
" Expected: to be called at least twice\n" "Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\n"
" Actual: called once - unsatisfied and active"); " Expected: to be called at least twice\n"
" Actual: called once - unsatisfied and active");
} }
// Tests that the cardinality can be inferred when no Times(...) is // Tests that the cardinality can be inferred when no Times(...) is
// specified. // specified.
TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) { TEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {
{ {
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, b.DoB()); EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB());
} }
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
MockB b; { // NOLINT
EXPECT_CALL(b, DoB()) MockB b;
.WillOnce(Return(1)) EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
.WillOnce(Return(2));
EXPECT_EQ(1, b.DoB());
EXPECT_EQ(1, b.DoB()); },
}, "to be called twice"); "to be called twice");
{ // NOLINT { // NOLINT
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));
.WillOnce(Return(1))
.WillOnce(Return(2));
EXPECT_EQ(1, b.DoB()); EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB());
EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice"); EXPECT_NONFATAL_FAILURE(b.DoB(), "to be called twice");
} }
} }
TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) { TEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {
{ {
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
EXPECT_EQ(1, b.DoB()); EXPECT_EQ(1, b.DoB());
} }
{ // NOLINT { // NOLINT
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
EXPECT_EQ(1, b.DoB()); EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB());
EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB());
} }
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
MockB b; { // NOLINT
EXPECT_CALL(b, DoB()) MockB b;
.WillOnce(Return(1)) EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
.WillRepeatedly(Return(2)); },
}, "to be called at least once"); "to be called at least once");
} }
#if defined(__cplusplus) && __cplusplus >= 201703L
// It should be possible to return a non-moveable type from a mock action in
// C++17 and above, where it's guaranteed that such a type can be initialized
// from a prvalue returned from a function.
TEST(ExpectCallTest, NonMoveableType) {
// Define a non-moveable result type.
struct Result {
explicit Result(int x_in) : x(x_in) {}
Result(Result&&) = delete;
int x;
};
static_assert(!std::is_move_constructible_v<Result>);
static_assert(!std::is_copy_constructible_v<Result>);
static_assert(!std::is_move_assignable_v<Result>);
static_assert(!std::is_copy_assignable_v<Result>);
// We should be able to use a callable that returns that result as both a
// OnceAction and an Action, whether the callable ignores arguments or not.
const auto return_17 = [] { return Result(17); };
static_cast<void>(OnceAction<Result()>{return_17});
static_cast<void>(Action<Result()>{return_17});
static_cast<void>(OnceAction<Result(int)>{return_17});
static_cast<void>(Action<Result(int)>{return_17});
// It should be possible to return the result end to end through an
// EXPECT_CALL statement, with both WillOnce and WillRepeatedly.
MockFunction<Result()> mock;
EXPECT_CALL(mock, Call) //
.WillOnce(return_17) //
.WillRepeatedly(return_17);
EXPECT_EQ(17, mock.AsStdFunction()().x);
EXPECT_EQ(17, mock.AsStdFunction()().x);
EXPECT_EQ(17, mock.AsStdFunction()().x);
}
#endif // C++17 and above
// Tests that the n-th action is taken for the n-th matching // Tests that the n-th action is taken for the n-th matching
// invocation. // invocation.
TEST(ExpectCallTest, NthMatchTakesNthAction) { TEST(ExpectCallTest, NthMatchTakesNthAction) {
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(
.WillOnce(Return(1)) Return(3));
.WillOnce(Return(2))
.WillOnce(Return(3));
EXPECT_EQ(1, b.DoB()); EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB());
EXPECT_EQ(3, b.DoB()); EXPECT_EQ(3, b.DoB());
} }
// Tests that the WillRepeatedly() action is taken when the WillOnce(...) // Tests that the WillRepeatedly() action is taken when the WillOnce(...)
// list is exhausted. // list is exhausted.
TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) { TEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));
.WillOnce(Return(1))
.WillRepeatedly(Return(2));
EXPECT_EQ(1, b.DoB()); EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB());
EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB());
} }
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
// Tests that the default action is taken when the WillOnce(...) list is // Tests that the default action is taken when the WillOnce(...) list is
// exhausted and there is no WillRepeatedly(). // exhausted and there is no WillRepeatedly().
TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) { TEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {
MockB b; MockB b;
EXPECT_CALL(b, DoB(_)) EXPECT_CALL(b, DoB(_)).Times(1);
.Times(1);
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB())
.Times(AnyNumber()) .Times(AnyNumber())
.WillOnce(Return(1)) .WillOnce(Return(1))
.WillOnce(Return(2)); .WillOnce(Return(2));
CaptureStdout(); CaptureStdout();
EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the EXPECT_EQ(0, b.DoB(1)); // Shouldn't generate a warning as the
// expectation has no action clause at all. // expectation has no action clause at all.
EXPECT_EQ(1, b.DoB()); EXPECT_EQ(1, b.DoB());
EXPECT_EQ(2, b.DoB()); EXPECT_EQ(2, b.DoB());
skipping to change at line 987 skipping to change at line 941
EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout()); EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());
} }
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
// Tests that an uninteresting call performs the default action. // Tests that an uninteresting call performs the default action.
TEST(UninterestingCallTest, DoesDefaultAction) { TEST(UninterestingCallTest, DoesDefaultAction) {
// When there is an ON_CALL() statement, the action specified by it // When there is an ON_CALL() statement, the action specified by it
// should be taken. // should be taken.
MockA a; MockA a;
ON_CALL(a, Binary(_, _)) ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
.WillByDefault(Return(true));
EXPECT_TRUE(a.Binary(1, 2)); EXPECT_TRUE(a.Binary(1, 2));
// When there is no ON_CALL(), the default value for the return type // When there is no ON_CALL(), the default value for the return type
// should be returned. // should be returned.
MockB b; MockB b;
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
} }
// Tests that an unexpected call performs the default action. // Tests that an unexpected call performs the default action.
TEST(UnexpectedCallTest, DoesDefaultAction) { TEST(UnexpectedCallTest, DoesDefaultAction) {
// When there is an ON_CALL() statement, the action specified by it // When there is an ON_CALL() statement, the action specified by it
// should be taken. // should be taken.
MockA a; MockA a;
ON_CALL(a, Binary(_, _)) ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
.WillByDefault(Return(true));
EXPECT_CALL(a, Binary(0, 0)); EXPECT_CALL(a, Binary(0, 0));
a.Binary(0, 0); a.Binary(0, 0);
bool result = false; bool result = false;
EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2), EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),
"Unexpected mock function call"); "Unexpected mock function call");
EXPECT_TRUE(result); EXPECT_TRUE(result);
// When there is no ON_CALL(), the default value for the return type // When there is no ON_CALL(), the default value for the return type
// should be returned. // should be returned.
MockB b; MockB b;
EXPECT_CALL(b, DoB(0)) EXPECT_CALL(b, DoB(0)).Times(0);
.Times(0);
int n = -1; int n = -1;
EXPECT_NONFATAL_FAILURE(n = b.DoB(1), EXPECT_NONFATAL_FAILURE(n = b.DoB(1), "Unexpected mock function call");
"Unexpected mock function call");
EXPECT_EQ(0, n); EXPECT_EQ(0, n);
} }
// Tests that when an unexpected void function generates the right // Tests that when an unexpected void function generates the right
// failure message. // failure message.
TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) { TEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {
// First, tests the message when there is only one EXPECT_CALL(). // First, tests the message when there is only one EXPECT_CALL().
MockA a1; MockA a1;
EXPECT_CALL(a1, DoA(1)); EXPECT_CALL(a1, DoA(1));
a1.DoA(1); a1.DoA(1);
skipping to change at line 1095 skipping to change at line 1045
" Expected arg #0: is equal to 1\n" " Expected arg #0: is equal to 1\n"
" Actual: 2\n" " Actual: 2\n"
" Expected: to be called once\n" " Expected: to be called once\n"
" Actual: called once - saturated and active"); " Actual: called once - saturated and active");
} }
// Tests that Google Mock explains that an retired expectation doesn't // Tests that Google Mock explains that an retired expectation doesn't
// match the call. // match the call.
TEST(UnexpectedCallTest, RetiredExpectation) { TEST(UnexpectedCallTest, RetiredExpectation) {
MockB b; MockB b;
EXPECT_CALL(b, DoB(1)) EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();
.RetiresOnSaturation();
b.DoB(1); b.DoB(1);
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(b.DoB(1),
b.DoB(1), " Expected: the expectation is active\n"
" Expected: the expectation is active\n" " Actual: it is retired");
" Actual: it is retired");
} }
// Tests that Google Mock explains that an expectation that doesn't // Tests that Google Mock explains that an expectation that doesn't
// match the arguments doesn't match the call. // match the arguments doesn't match the call.
TEST(UnexpectedCallTest, UnmatchedArguments) { TEST(UnexpectedCallTest, UnmatchedArguments) {
MockB b; MockB b;
EXPECT_CALL(b, DoB(1)); EXPECT_CALL(b, DoB(1));
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(b.DoB(2),
b.DoB(2), " Expected arg #0: is equal to 1\n"
" Expected arg #0: is equal to 1\n" " Actual: 2\n");
" Actual: 2\n");
b.DoB(1); b.DoB(1);
} }
// Tests that Google Mock explains that an expectation with // Tests that Google Mock explains that an expectation with
// unsatisfied pre-requisites doesn't match the call. // unsatisfied pre-requisites doesn't match the call.
TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) { TEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {
Sequence s1, s2; Sequence s1, s2;
MockB b; MockB b;
EXPECT_CALL(b, DoB(1)) EXPECT_CALL(b, DoB(1)).InSequence(s1);
.InSequence(s1); EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);
EXPECT_CALL(b, DoB(2)) EXPECT_CALL(b, DoB(3)).InSequence(s2);
.Times(AnyNumber()) EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);
.InSequence(s1);
EXPECT_CALL(b, DoB(3))
.InSequence(s2);
EXPECT_CALL(b, DoB(4))
.InSequence(s1, s2);
::testing::TestPartResultArray failures; ::testing::TestPartResultArray failures;
{ {
::testing::ScopedFakeTestPartResultReporter reporter(&failures); ::testing::ScopedFakeTestPartResultReporter reporter(&failures);
b.DoB(4); b.DoB(4);
// Now 'failures' contains the Google Test failures generated by // Now 'failures' contains the Google Test failures generated by
// the above statement. // the above statement.
} }
// There should be one non-fatal failure. // There should be one non-fatal failure.
ASSERT_EQ(1, failures.size()); ASSERT_EQ(1, failures.size());
const ::testing::TestPartResult& r = failures.GetTestPartResult(0); const ::testing::TestPartResult& r = failures.GetTestPartResult(0);
EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type()); EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());
// Verifies that the failure message contains the two unsatisfied // Verifies that the failure message contains the two unsatisfied
// pre-requisites but not the satisfied one. // pre-requisites but not the satisfied one.
#if GTEST_USES_PCRE #if GTEST_USES_PCRE
EXPECT_THAT(r.message(), ContainsRegex( EXPECT_THAT(
// PCRE has trouble using (.|\n) to match any character, but r.message(),
// supports the (?s) prefix for using . to match any character. ContainsRegex(
"(?s)the following immediate pre-requisites are not satisfied:\n" // PCRE has trouble using (.|\n) to match any character, but
".*: pre-requisite #0\n" // supports the (?s) prefix for using . to match any character.
".*: pre-requisite #1")); "(?s)the following immediate pre-requisites are not satisfied:\n"
".*: pre-requisite #0\n"
".*: pre-requisite #1"));
#elif GTEST_USES_POSIX_RE #elif GTEST_USES_POSIX_RE
EXPECT_THAT(r.message(), ContainsRegex( EXPECT_THAT(r.message(),
// POSIX RE doesn't understand the (?s) prefix, but has no trouble ContainsRegex(
// with (.|\n). // POSIX RE doesn't understand the (?s) prefix, but has no
"the following immediate pre-requisites are not satisfied:\n" // trouble with (.|\n).
"(.|\n)*: pre-requisite #0\n" "the following immediate pre-requisites are not satisfied:\n"
"(.|\n)*: pre-requisite #1")); "(.|\n)*: pre-requisite #0\n"
"(.|\n)*: pre-requisite #1"));
#else #else
// We can only use Google Test's own simple regex. // We can only use Google Test's own simple regex.
EXPECT_THAT(r.message(), ContainsRegex( EXPECT_THAT(r.message(),
"the following immediate pre-requisites are not satisfied:")); ContainsRegex(
"the following immediate pre-requisites are not satisfied:"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #0"));
EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1")); EXPECT_THAT(r.message(), ContainsRegex(": pre-requisite #1"));
#endif // GTEST_USES_PCRE #endif // GTEST_USES_PCRE
b.DoB(1); b.DoB(1);
b.DoB(3); b.DoB(3);
b.DoB(4); b.DoB(4);
} }
TEST(UndefinedReturnValueTest, TEST(UndefinedReturnValueTest,
skipping to change at line 1194 skipping to change at line 1140
EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), ""); EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), "");
#endif #endif
} }
// Tests that an excessive call (one whose arguments match the // Tests that an excessive call (one whose arguments match the
// matchers but is called too many times) performs the default action. // matchers but is called too many times) performs the default action.
TEST(ExcessiveCallTest, DoesDefaultAction) { TEST(ExcessiveCallTest, DoesDefaultAction) {
// When there is an ON_CALL() statement, the action specified by it // When there is an ON_CALL() statement, the action specified by it
// should be taken. // should be taken.
MockA a; MockA a;
ON_CALL(a, Binary(_, _)) ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
.WillByDefault(Return(true));
EXPECT_CALL(a, Binary(0, 0)); EXPECT_CALL(a, Binary(0, 0));
a.Binary(0, 0); a.Binary(0, 0);
bool result = false; bool result = false;
EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0), EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),
"Mock function called more times than expected"); "Mock function called more times than expected");
EXPECT_TRUE(result); EXPECT_TRUE(result);
// When there is no ON_CALL(), the default value for the return type // When there is no ON_CALL(), the default value for the return type
// should be returned. // should be returned.
MockB b; MockB b;
EXPECT_CALL(b, DoB(0)) EXPECT_CALL(b, DoB(0)).Times(0);
.Times(0);
int n = -1; int n = -1;
EXPECT_NONFATAL_FAILURE(n = b.DoB(0), EXPECT_NONFATAL_FAILURE(n = b.DoB(0),
"Mock function called more times than expected"); "Mock function called more times than expected");
EXPECT_EQ(0, n); EXPECT_EQ(0, n);
} }
// Tests that when a void function is called too many times, // Tests that when a void function is called too many times,
// the failure message contains the argument values. // the failure message contains the argument values.
TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) { TEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(_)) EXPECT_CALL(a, DoA(_)).Times(0);
.Times(0);
EXPECT_NONFATAL_FAILURE( EXPECT_NONFATAL_FAILURE(
a.DoA(9), a.DoA(9),
"Mock function called more times than expected - returning directly.\n" "Mock function called more times than expected - returning directly.\n"
" Function call: DoA(9)\n" " Function call: DoA(9)\n"
" Expected: to be never called\n" " Expected: to be never called\n"
" Actual: called once - over-saturated and active"); " Actual: called once - over-saturated and active");
} }
// Tests that when a non-void function is called too many times, the // Tests that when a non-void function is called too many times, the
// failure message contains the argument values and the return value. // failure message contains the argument values and the return value.
skipping to change at line 1255 skipping to change at line 1198
TEST(InSequenceTest, AllExpectationInScopeAreInSequence) { TEST(InSequenceTest, AllExpectationInScopeAreInSequence) {
MockA a; MockA a;
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2)); EXPECT_CALL(a, DoA(2));
} }
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
a.DoA(2); { // NOLINT
}, "Unexpected mock function call"); a.DoA(2);
},
"Unexpected mock function call");
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
} }
TEST(InSequenceTest, NestedInSequence) { TEST(InSequenceTest, NestedInSequence) {
MockA a; MockA a;
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
{ {
InSequence dummy2; InSequence dummy2;
EXPECT_CALL(a, DoA(2)); EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, DoA(3)); EXPECT_CALL(a, DoA(3));
} }
} }
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
a.DoA(1); { // NOLINT
a.DoA(3); a.DoA(1);
}, "Unexpected mock function call"); a.DoA(3);
},
"Unexpected mock function call");
a.DoA(2); a.DoA(2);
a.DoA(3); a.DoA(3);
} }
TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) { TEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {
MockA a; MockA a;
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2)); EXPECT_CALL(a, DoA(2));
} }
EXPECT_CALL(a, DoA(3)); EXPECT_CALL(a, DoA(3));
EXPECT_NONFATAL_FAILURE({ // NOLINT EXPECT_NONFATAL_FAILURE(
a.DoA(2); { // NOLINT
}, "Unexpected mock function call"); a.DoA(2);
},
"Unexpected mock function call");
a.DoA(3); a.DoA(3);
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
} }
// Tests that any order is allowed when no sequence is used. // Tests that any order is allowed when no sequence is used.
TEST(SequenceTest, AnyOrderIsOkByDefault) { TEST(SequenceTest, AnyOrderIsOkByDefault) {
{ {
MockA a; MockA a;
MockB b; MockB b;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).Times(AnyNumber());
.Times(AnyNumber());
a.DoA(1); a.DoA(1);
b.DoB(); b.DoB();
} }
{ // NOLINT { // NOLINT
MockA a; MockA a;
MockB b; MockB b;
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).Times(AnyNumber());
.Times(AnyNumber());
b.DoB(); b.DoB();
a.DoA(1); a.DoA(1);
} }
} }
// Tests that the calls must be in strict order when a complete order // Tests that the calls must be in strict order when a complete order
// is specified. // is specified.
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) { TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {
MockA a; MockA a;
ON_CALL(a, ReturnResult(_)) ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
.WillByDefault(Return(Result()));
Sequence s; Sequence s;
EXPECT_CALL(a, ReturnResult(1)) EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
.InSequence(s); EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
EXPECT_CALL(a, ReturnResult(2)) EXPECT_CALL(a, ReturnResult(3)).InSequence(s);
.InSequence(s);
EXPECT_CALL(a, ReturnResult(3))
.InSequence(s);
a.ReturnResult(1); a.ReturnResult(1);
// May only be called after a.ReturnResult(2). // May only be called after a.ReturnResult(2).
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
a.ReturnResult(2); a.ReturnResult(2);
a.ReturnResult(3); a.ReturnResult(3);
} }
// Tests that the calls must be in strict order when a complete order // Tests that the calls must be in strict order when a complete order
// is specified. // is specified.
TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) { TEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {
MockA a; MockA a;
ON_CALL(a, ReturnResult(_)) ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
.WillByDefault(Return(Result()));
Sequence s; Sequence s;
EXPECT_CALL(a, ReturnResult(1)) EXPECT_CALL(a, ReturnResult(1)).InSequence(s);
.InSequence(s); EXPECT_CALL(a, ReturnResult(2)).InSequence(s);
EXPECT_CALL(a, ReturnResult(2))
.InSequence(s);
// May only be called after a.ReturnResult(1). // May only be called after a.ReturnResult(1).
EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), "Unexpected mock function call");
a.ReturnResult(1); a.ReturnResult(1);
a.ReturnResult(2); a.ReturnResult(2);
} }
// Tests specifying a DAG using multiple sequences. // Tests specifying a DAG using multiple sequences.
class PartialOrderTest : public testing::Test { class PartialOrderTest : public testing::Test {
protected: protected:
PartialOrderTest() { PartialOrderTest() {
ON_CALL(a_, ReturnResult(_)) ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result()));
.WillByDefault(Return(Result()));
// Specifies this partial ordering: // Specifies this partial ordering:
// //
// a.ReturnResult(1) ==> // a.ReturnResult(1) ==>
// a.ReturnResult(2) * n ==> a.ReturnResult(3) // a.ReturnResult(2) * n ==> a.ReturnResult(3)
// b.DoB() * 2 ==> // b.DoB() * 2 ==>
Sequence x, y; Sequence x, y;
EXPECT_CALL(a_, ReturnResult(1)) EXPECT_CALL(a_, ReturnResult(1)).InSequence(x);
.InSequence(x); EXPECT_CALL(b_, DoB()).Times(2).InSequence(y);
EXPECT_CALL(b_, DoB()) EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y);
.Times(2) EXPECT_CALL(a_, ReturnResult(3)).InSequence(x);
.InSequence(y);
EXPECT_CALL(a_, ReturnResult(2))
.Times(AnyNumber())
.InSequence(x, y);
EXPECT_CALL(a_, ReturnResult(3))
.InSequence(x);
} }
MockA a_; MockA a_;
MockB b_; MockB b_;
}; };
TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) { TEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {
a_.ReturnResult(1); a_.ReturnResult(1);
b_.DoB(); b_.DoB();
skipping to change at line 1450 skipping to change at line 1383
a_.ReturnResult(3); a_.ReturnResult(3);
// May only be called before ReturnResult(3). // May only be called before ReturnResult(3).
EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), "Unexpected mock function call");
} }
TEST(SequenceTest, Retirement) { TEST(SequenceTest, Retirement) {
MockA a; MockA a;
Sequence s; Sequence s;
EXPECT_CALL(a, DoA(1)) EXPECT_CALL(a, DoA(1)).InSequence(s);
.InSequence(s); EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation();
EXPECT_CALL(a, DoA(_)) EXPECT_CALL(a, DoA(1)).InSequence(s);
.InSequence(s)
.RetiresOnSaturation();
EXPECT_CALL(a, DoA(1))
.InSequence(s);
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
a.DoA(1); a.DoA(1);
} }
// Tests Expectation. // Tests Expectation.
TEST(ExpectationTest, ConstrutorsWork) { TEST(ExpectationTest, ConstrutorsWork) {
MockA a; MockA a;
skipping to change at line 1521 skipping to change at line 1450
TEST(ExpectationSetTest, MemberTypesAreCorrect) { TEST(ExpectationSetTest, MemberTypesAreCorrect) {
::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>(); ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();
} }
TEST(ExpectationSetTest, ConstructorsWork) { TEST(ExpectationSetTest, ConstructorsWork) {
MockA a; MockA a;
Expectation e1; Expectation e1;
const Expectation e2; const Expectation e2;
ExpectationSet es1; // Default ctor. ExpectationSet es1; // Default ctor.
ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL. ExpectationSet es2 = EXPECT_CALL(a, DoA(1)); // Ctor from EXPECT_CALL.
ExpectationSet es3 = e1; // Ctor from Expectation. ExpectationSet es3 = e1; // Ctor from Expectation.
ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax. ExpectationSet es4(e1); // Ctor from Expectation; alternative syntax.
ExpectationSet es5 = e2; // Ctor from const Expectation. ExpectationSet es5 = e2; // Ctor from const Expectation.
ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax. ExpectationSet es6(e2); // Ctor from const Expectation; alternative syntax.
ExpectationSet es7 = es2; // Copy ctor. ExpectationSet es7 = es2; // Copy ctor.
EXPECT_EQ(0, es1.size()); EXPECT_EQ(0, es1.size());
EXPECT_EQ(1, es2.size()); EXPECT_EQ(1, es2.size());
EXPECT_EQ(1, es3.size()); EXPECT_EQ(1, es3.size());
EXPECT_EQ(1, es4.size()); EXPECT_EQ(1, es4.size());
EXPECT_EQ(1, es5.size()); EXPECT_EQ(1, es5.size());
EXPECT_EQ(1, es6.size()); EXPECT_EQ(1, es6.size());
EXPECT_EQ(1, es7.size()); EXPECT_EQ(1, es7.size());
skipping to change at line 1598 skipping to change at line 1527
TEST(ExpectationSetTest, IsEnumerable) { TEST(ExpectationSetTest, IsEnumerable) {
ExpectationSet es; ExpectationSet es;
EXPECT_TRUE(es.begin() == es.end()); EXPECT_TRUE(es.begin() == es.end());
es += Expectation(); es += Expectation();
ExpectationSet::const_iterator it = es.begin(); ExpectationSet::const_iterator it = es.begin();
EXPECT_TRUE(it != es.end()); EXPECT_TRUE(it != es.end());
EXPECT_THAT(*it, Eq(Expectation())); EXPECT_THAT(*it, Eq(Expectation()));
++it; ++it;
EXPECT_TRUE(it== es.end()); EXPECT_TRUE(it == es.end());
} }
// Tests the .After() clause. // Tests the .After() clause.
TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) { TEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {
MockA a; MockA a;
ExpectationSet es; ExpectationSet es;
es += EXPECT_CALL(a, DoA(1)); es += EXPECT_CALL(a, DoA(1));
es += EXPECT_CALL(a, DoA(2)); es += EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, DoA(3)) EXPECT_CALL(a, DoA(3)).After(es);
.After(es);
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
a.DoA(3); a.DoA(3);
} }
TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) { TEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {
MockA a; MockA a;
MockB b; MockB b;
// The following also verifies that const Expectation objects work // The following also verifies that const Expectation objects work
// too. Do not remove the const modifiers. // too. Do not remove the const modifiers.
const Expectation e1 = EXPECT_CALL(a, DoA(1)); const Expectation e1 = EXPECT_CALL(a, DoA(1));
const Expectation e2 = EXPECT_CALL(b, DoB()) const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
.Times(2)
.After(e1);
EXPECT_CALL(a, DoA(2)).After(e2); EXPECT_CALL(a, DoA(2)).After(e2);
a.DoA(1); a.DoA(1);
b.DoB(); b.DoB();
b.DoB(); b.DoB();
a.DoA(2); a.DoA(2);
} }
// Calls must be in strict order when specified so using .After(). // Calls must be in strict order when specified so using .After().
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) { TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {
MockA a; MockA a;
MockB b; MockB b;
// Define ordering: // Define ordering:
// a.DoA(1) ==> b.DoB() ==> a.DoA(2) // a.DoA(1) ==> b.DoB() ==> a.DoA(2)
Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(b, DoB()) Expectation e2 = EXPECT_CALL(b, DoB()).After(e1);
.After(e1); EXPECT_CALL(a, DoA(2)).After(e2);
EXPECT_CALL(a, DoA(2))
.After(e2);
a.DoA(1); a.DoA(1);
// May only be called after DoB(). // May only be called after DoB().
EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
b.DoB(); b.DoB();
a.DoA(2); a.DoA(2);
} }
// Calls must be in strict order when specified so using .After(). // Calls must be in strict order when specified so using .After().
TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) { TEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {
MockA a; MockA a;
MockB b; MockB b;
// Define ordering: // Define ordering:
// a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2) // a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)
Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(b, DoB()) Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);
.Times(2) EXPECT_CALL(a, DoA(2)).After(e2);
.After(e1);
EXPECT_CALL(a, DoA(2))
.After(e2);
a.DoA(1); a.DoA(1);
b.DoB(); b.DoB();
// May only be called after the second DoB(). // May only be called after the second DoB().
EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a.DoA(2), "Unexpected mock function call");
b.DoB(); b.DoB();
a.DoA(2); a.DoA(2);
} }
// Calls must satisfy the partial order when specified so. // Calls must satisfy the partial order when specified so.
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) { TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {
MockA a; MockA a;
ON_CALL(a, ReturnResult(_)) ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
.WillByDefault(Return(Result()));
// Define ordering: // Define ordering:
// a.DoA(1) ==> // a.DoA(1) ==>
// a.DoA(2) ==> a.ReturnResult(3) // a.DoA(2) ==> a.ReturnResult(3)
Expectation e = EXPECT_CALL(a, DoA(1)); Expectation e = EXPECT_CALL(a, DoA(1));
const ExpectationSet es = EXPECT_CALL(a, DoA(2)); const ExpectationSet es = EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, ReturnResult(3)) EXPECT_CALL(a, ReturnResult(3)).After(e, es);
.After(e, es);
// May only be called last. // May only be called last.
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
a.DoA(2); a.DoA(2);
a.DoA(1); a.DoA(1);
a.ReturnResult(3); a.ReturnResult(3);
} }
// Calls must satisfy the partial order when specified so. // Calls must satisfy the partial order when specified so.
TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) { TEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {
MockA a; MockA a;
// Define ordering: // Define ordering:
// a.DoA(1) ==> // a.DoA(1) ==>
// a.DoA(2) ==> a.DoA(3) // a.DoA(2) ==> a.DoA(3)
Expectation e = EXPECT_CALL(a, DoA(1)); Expectation e = EXPECT_CALL(a, DoA(1));
const ExpectationSet es = EXPECT_CALL(a, DoA(2)); const ExpectationSet es = EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, DoA(3)) EXPECT_CALL(a, DoA(3)).After(e, es);
.After(e, es);
a.DoA(2); a.DoA(2);
// May only be called last. // May only be called last.
EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
a.DoA(1); a.DoA(1);
a.DoA(3); a.DoA(3);
} }
// .After() can be combined with .InSequence(). // .After() can be combined with .InSequence().
TEST(AfterTest, CanBeUsedWithInSequence) { TEST(AfterTest, CanBeUsedWithInSequence) {
MockA a; MockA a;
Sequence s; Sequence s;
Expectation e = EXPECT_CALL(a, DoA(1)); Expectation e = EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(2)).InSequence(s); EXPECT_CALL(a, DoA(2)).InSequence(s);
EXPECT_CALL(a, DoA(3)) EXPECT_CALL(a, DoA(3)).InSequence(s).After(e);
.InSequence(s)
.After(e);
a.DoA(1); a.DoA(1);
// May only be after DoA(2). // May only be after DoA(2).
EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a.DoA(3), "Unexpected mock function call");
a.DoA(2); a.DoA(2);
a.DoA(3); a.DoA(3);
} }
// .After() can be called multiple times. // .After() can be called multiple times.
TEST(AfterTest, CanBeCalledManyTimes) { TEST(AfterTest, CanBeCalledManyTimes) {
MockA a; MockA a;
Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e2 = EXPECT_CALL(a, DoA(2));
Expectation e3 = EXPECT_CALL(a, DoA(3)); Expectation e3 = EXPECT_CALL(a, DoA(3));
EXPECT_CALL(a, DoA(4)) EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3);
.After(e1)
.After(e2)
.After(e3);
a.DoA(3); a.DoA(3);
a.DoA(1); a.DoA(1);
a.DoA(2); a.DoA(2);
a.DoA(4); a.DoA(4);
} }
// .After() accepts up to 5 arguments. // .After() accepts up to 5 arguments.
TEST(AfterTest, AcceptsUpToFiveArguments) { TEST(AfterTest, AcceptsUpToFiveArguments) {
MockA a; MockA a;
Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e2 = EXPECT_CALL(a, DoA(2));
Expectation e3 = EXPECT_CALL(a, DoA(3)); Expectation e3 = EXPECT_CALL(a, DoA(3));
ExpectationSet es1 = EXPECT_CALL(a, DoA(4)); ExpectationSet es1 = EXPECT_CALL(a, DoA(4));
ExpectationSet es2 = EXPECT_CALL(a, DoA(5)); ExpectationSet es2 = EXPECT_CALL(a, DoA(5));
EXPECT_CALL(a, DoA(6)) EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2);
.After(e1, e2, e3, es1, es2);
a.DoA(5); a.DoA(5);
a.DoA(2); a.DoA(2);
a.DoA(4); a.DoA(4);
a.DoA(1); a.DoA(1);
a.DoA(3); a.DoA(3);
a.DoA(6); a.DoA(6);
} }
// .After() allows input to contain duplicated Expectations. // .After() allows input to contain duplicated Expectations.
TEST(AfterTest, AcceptsDuplicatedInput) { TEST(AfterTest, AcceptsDuplicatedInput) {
MockA a; MockA a;
ON_CALL(a, ReturnResult(_)) ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));
.WillByDefault(Return(Result()));
// Define ordering: // Define ordering:
// DoA(1) ==> // DoA(1) ==>
// DoA(2) ==> ReturnResult(3) // DoA(2) ==> ReturnResult(3)
Expectation e1 = EXPECT_CALL(a, DoA(1)); Expectation e1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e2 = EXPECT_CALL(a, DoA(2));
ExpectationSet es; ExpectationSet es;
es += e1; es += e1;
es += e2; es += e2;
EXPECT_CALL(a, ReturnResult(3)) EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1);
.After(e1, e2, es, e1);
a.DoA(1); a.DoA(1);
// May only be after DoA(2). // May only be after DoA(2).
EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), "Unexpected mock function call");
a.DoA(2); a.DoA(2);
a.ReturnResult(3); a.ReturnResult(3);
} }
// An Expectation added to an ExpectationSet after it has been used in // An Expectation added to an ExpectationSet after it has been used in
// an .After() has no effect. // an .After() has no effect.
TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) { TEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {
MockA a; MockA a;
ExpectationSet es1 = EXPECT_CALL(a, DoA(1)); ExpectationSet es1 = EXPECT_CALL(a, DoA(1));
Expectation e2 = EXPECT_CALL(a, DoA(2)); Expectation e2 = EXPECT_CALL(a, DoA(2));
EXPECT_CALL(a, DoA(3)) EXPECT_CALL(a, DoA(3)).After(es1);
.After(es1);
es1 += e2; es1 += e2;
a.DoA(1); a.DoA(1);
a.DoA(3); a.DoA(3);
a.DoA(2); a.DoA(2);
} }
// Tests that Google Mock correctly handles calls to mock functions // Tests that Google Mock correctly handles calls to mock functions
// after a mock object owning one of their pre-requisites has died. // after a mock object owning one of their pre-requisites has died.
// Tests that calls that satisfy the original spec are successful. // Tests that calls that satisfy the original spec are successful.
TEST(DeletingMockEarlyTest, Success1) { TEST(DeletingMockEarlyTest, Success1) {
MockB* const b1 = new MockB; MockB* const b1 = new MockB;
MockA* const a = new MockA; MockA* const a = new MockA;
MockB* const b2 = new MockB; MockB* const b2 = new MockB;
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(*b1, DoB(_)) EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
.WillOnce(Return(1));
EXPECT_CALL(*a, Binary(_, _)) EXPECT_CALL(*a, Binary(_, _))
.Times(AnyNumber()) .Times(AnyNumber())
.WillRepeatedly(Return(true)); .WillRepeatedly(Return(true));
EXPECT_CALL(*b2, DoB(_)) EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
.Times(AnyNumber())
.WillRepeatedly(Return(2));
} }
EXPECT_EQ(1, b1->DoB(1)); EXPECT_EQ(1, b1->DoB(1));
delete b1; delete b1;
// a's pre-requisite has died. // a's pre-requisite has died.
EXPECT_TRUE(a->Binary(0, 1)); EXPECT_TRUE(a->Binary(0, 1));
delete b2; delete b2;
// a's successor has died. // a's successor has died.
EXPECT_TRUE(a->Binary(1, 2)); EXPECT_TRUE(a->Binary(1, 2));
delete a; delete a;
} }
// Tests that calls that satisfy the original spec are successful. // Tests that calls that satisfy the original spec are successful.
TEST(DeletingMockEarlyTest, Success2) { TEST(DeletingMockEarlyTest, Success2) {
MockB* const b1 = new MockB; MockB* const b1 = new MockB;
MockA* const a = new MockA; MockA* const a = new MockA;
MockB* const b2 = new MockB; MockB* const b2 = new MockB;
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(*b1, DoB(_)) EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
.WillOnce(Return(1)); EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
EXPECT_CALL(*a, Binary(_, _)) EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
.Times(AnyNumber());
EXPECT_CALL(*b2, DoB(_))
.Times(AnyNumber())
.WillRepeatedly(Return(2));
} }
delete a; // a is trivially satisfied. delete a; // a is trivially satisfied.
EXPECT_EQ(1, b1->DoB(1)); EXPECT_EQ(1, b1->DoB(1));
EXPECT_EQ(2, b2->DoB(2)); EXPECT_EQ(2, b2->DoB(2));
delete b1; delete b1;
delete b2; delete b2;
} }
// Tests that it's OK to delete a mock object itself in its action. // Tests that it's OK to delete a mock object itself in its action.
// Suppresses warning on unreferenced formal parameter in MSVC with // Suppresses warning on unreferenced formal parameter in MSVC with
// -W4. // -W4.
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(push) #pragma warning(push)
# pragma warning(disable:4100) #pragma warning(disable : 4100)
#endif #endif
ACTION_P(Delete, ptr) { delete ptr; } ACTION_P(Delete, ptr) { delete ptr; }
#ifdef _MSC_VER #ifdef _MSC_VER
# pragma warning(pop) #pragma warning(pop)
#endif #endif
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) { TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {
MockA* const a = new MockA; MockA* const a = new MockA;
EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a)); EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));
a->DoA(42); // This will cause a to be deleted. a->DoA(42); // This will cause a to be deleted.
} }
TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) { TEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {
MockA* const a = new MockA; MockA* const a = new MockA;
EXPECT_CALL(*a, ReturnResult(_)) EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));
.WillOnce(DoAll(Delete(a), Return(Result())));
a->ReturnResult(42); // This will cause a to be deleted. a->ReturnResult(42); // This will cause a to be deleted.
} }
// Tests that calls that violate the original spec yield failures. // Tests that calls that violate the original spec yield failures.
TEST(DeletingMockEarlyTest, Failure1) { TEST(DeletingMockEarlyTest, Failure1) {
MockB* const b1 = new MockB; MockB* const b1 = new MockB;
MockA* const a = new MockA; MockA* const a = new MockA;
MockB* const b2 = new MockB; MockB* const b2 = new MockB;
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(*b1, DoB(_)) EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));
.WillOnce(Return(1)); EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
EXPECT_CALL(*a, Binary(_, _)) EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));
.Times(AnyNumber());
EXPECT_CALL(*b2, DoB(_))
.Times(AnyNumber())
.WillRepeatedly(Return(2));
} }
delete a; // a is trivially satisfied. delete a; // a is trivially satisfied.
EXPECT_NONFATAL_FAILURE({ EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, "Unexpected mock function call");
b2->DoB(2);
}, "Unexpected mock function call");
EXPECT_EQ(1, b1->DoB(1)); EXPECT_EQ(1, b1->DoB(1));
delete b1; delete b1;
delete b2; delete b2;
} }
// Tests that calls that violate the original spec yield failures. // Tests that calls that violate the original spec yield failures.
TEST(DeletingMockEarlyTest, Failure2) { TEST(DeletingMockEarlyTest, Failure2) {
MockB* const b1 = new MockB; MockB* const b1 = new MockB;
MockA* const a = new MockA; MockA* const a = new MockA;
MockB* const b2 = new MockB; MockB* const b2 = new MockB;
{ {
InSequence dummy; InSequence dummy;
EXPECT_CALL(*b1, DoB(_)); EXPECT_CALL(*b1, DoB(_));
EXPECT_CALL(*a, Binary(_, _)) EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());
.Times(AnyNumber()); EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());
EXPECT_CALL(*b2, DoB(_))
.Times(AnyNumber());
} }
EXPECT_NONFATAL_FAILURE(delete b1, EXPECT_NONFATAL_FAILURE(delete b1, "Actual: never called");
"Actual: never called"); EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), "Unexpected mock function call");
EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), EXPECT_NONFATAL_FAILURE(b2->DoB(1), "Unexpected mock function call");
"Unexpected mock function call");
EXPECT_NONFATAL_FAILURE(b2->DoB(1),
"Unexpected mock function call");
delete a; delete a;
delete b2; delete b2;
} }
class EvenNumberCardinality : public CardinalityInterface { class EvenNumberCardinality : public CardinalityInterface {
public: public:
// Returns true if and only if call_count calls will satisfy this // Returns true if and only if call_count calls will satisfy this
// cardinality. // cardinality.
bool IsSatisfiedByCallCount(int call_count) const override { bool IsSatisfiedByCallCount(int call_count) const override {
return call_count % 2 == 0; return call_count % 2 == 0;
skipping to change at line 1972 skipping to change at line 1862
bool IsSaturatedByCallCount(int /* call_count */) const override { bool IsSaturatedByCallCount(int /* call_count */) const override {
return false; return false;
} }
// Describes self to an ostream. // Describes self to an ostream.
void DescribeTo(::std::ostream* os) const override { void DescribeTo(::std::ostream* os) const override {
*os << "called even number of times"; *os << "called even number of times";
} }
}; };
Cardinality EvenNumber() { Cardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }
return Cardinality(new EvenNumberCardinality);
}
TEST(ExpectationBaseTest, TEST(ExpectationBaseTest,
AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) { AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {
MockA* a = new MockA; MockA* a = new MockA;
Sequence s; Sequence s;
EXPECT_CALL(*a, DoA(1)) EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);
.Times(EvenNumber()) EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);
.InSequence(s); EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());
EXPECT_CALL(*a, DoA(2))
.Times(AnyNumber())
.InSequence(s);
EXPECT_CALL(*a, DoA(3))
.Times(AnyNumber());
a->DoA(3); a->DoA(3);
a->DoA(1); a->DoA(1);
EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call"); EXPECT_NONFATAL_FAILURE(a->DoA(2), "Unexpected mock function call");
EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times"); EXPECT_NONFATAL_FAILURE(delete a, "to be called even number of times");
} }
// The following tests verify the message generated when a mock // The following tests verify the message generated when a mock
// function is called. // function is called.
struct Printable { struct Printable {};
};
inline void operator<<(::std::ostream& os, const Printable&) { inline void operator<<(::std::ostream& os, const Printable&) {
os << "Printable"; os << "Printable";
} }
struct Unprintable { struct Unprintable {
Unprintable() : value(0) {} Unprintable() : value(0) {}
int value; int value;
}; };
class MockC { class MockC {
public: public:
MockC() {} MockC() {}
MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p, MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,
const Printable& x, Unprintable y)); const Printable& x, Unprintable y));
MOCK_METHOD0(NonVoidMethod, int()); // NOLINT MOCK_METHOD0(NonVoidMethod, int()); // NOLINT
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(MockC); MockC(const MockC&) = delete;
MockC& operator=(const MockC&) = delete;
}; };
class VerboseFlagPreservingFixture : public testing::Test { class VerboseFlagPreservingFixture : public testing::Test {
protected: protected:
VerboseFlagPreservingFixture() VerboseFlagPreservingFixture()
: saved_verbose_flag_(GMOCK_FLAG(verbose)) {} : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}
~VerboseFlagPreservingFixture() override { ~VerboseFlagPreservingFixture() override {
GMOCK_FLAG(verbose) = saved_verbose_flag_; GMOCK_FLAG_SET(verbose, saved_verbose_flag_);
} }
private: private:
const std::string saved_verbose_flag_; const std::string saved_verbose_flag_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(VerboseFlagPreservingFixture); VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;
VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =
delete;
}; };
#if GTEST_HAS_STREAM_REDIRECTION #if GTEST_HAS_STREAM_REDIRECTION
// Tests that an uninteresting mock function call on a naggy mock // Tests that an uninteresting mock function call on a naggy mock
// generates a warning without the stack trace when // generates a warning without the stack trace when
// --gmock_verbose=warning is specified. // --gmock_verbose=warning is specified.
TEST(FunctionCallMessageTest, TEST(FunctionCallMessageTest,
UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) { UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {
GMOCK_FLAG(verbose) = kWarningVerbosity; GMOCK_FLAG_SET(verbose, kWarningVerbosity);
NaggyMock<MockC> c; NaggyMock<MockC> c;
CaptureStdout(); CaptureStdout();
c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
const std::string output = GetCapturedStdout(); const std::string output = GetCapturedStdout();
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output); EXPECT_PRED_FORMAT2(IsNotSubstring, "Stack trace:", output);
} }
// Tests that an uninteresting mock function call on a naggy mock // Tests that an uninteresting mock function call on a naggy mock
// generates a warning containing the stack trace when // generates a warning containing the stack trace when
// --gmock_verbose=info is specified. // --gmock_verbose=info is specified.
TEST(FunctionCallMessageTest, TEST(FunctionCallMessageTest,
UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) { UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {
GMOCK_FLAG(verbose) = kInfoVerbosity; GMOCK_FLAG_SET(verbose, kInfoVerbosity);
NaggyMock<MockC> c; NaggyMock<MockC> c;
CaptureStdout(); CaptureStdout();
c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
const std::string output = GetCapturedStdout(); const std::string output = GetCapturedStdout();
EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output); EXPECT_PRED_FORMAT2(IsSubstring, "GMOCK WARNING", output);
EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output); EXPECT_PRED_FORMAT2(IsSubstring, "Stack trace:", output);
# ifndef NDEBUG #ifndef NDEBUG
// We check the stack trace content in dbg-mode only, as opt-mode // We check the stack trace content in dbg-mode only, as opt-mode
// may inline the call we are interested in seeing. // may inline the call we are interested in seeing.
// Verifies that a void mock function's name appears in the stack // Verifies that a void mock function's name appears in the stack
// trace. // trace.
EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output); EXPECT_PRED_FORMAT2(IsSubstring, "VoidMethod(", output);
// Verifies that a non-void mock function's name appears in the // Verifies that a non-void mock function's name appears in the
// stack trace. // stack trace.
CaptureStdout(); CaptureStdout();
c.NonVoidMethod(); c.NonVoidMethod();
const std::string output2 = GetCapturedStdout(); const std::string output2 = GetCapturedStdout();
EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2); EXPECT_PRED_FORMAT2(IsSubstring, "NonVoidMethod(", output2);
# endif // NDEBUG #endif // NDEBUG
} }
// Tests that an uninteresting mock function call on a naggy mock // Tests that an uninteresting mock function call on a naggy mock
// causes the function arguments and return value to be printed. // causes the function arguments and return value to be printed.
TEST(FunctionCallMessageTest, TEST(FunctionCallMessageTest,
UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) { UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {
// A non-void mock function. // A non-void mock function.
NaggyMock<MockB> b; NaggyMock<MockB> b;
CaptureStdout(); CaptureStdout();
b.DoB(); b.DoB();
const std::string output1 = GetCapturedStdout(); const std::string output1 = GetCapturedStdout();
EXPECT_PRED_FORMAT2( EXPECT_PRED_FORMAT2(
IsSubstring, IsSubstring,
"Uninteresting mock function call - returning default value.\n" "Uninteresting mock function call - returning default value.\n"
" Function call: DoB()\n" " Function call: DoB()\n"
" Returns: 0\n", output1.c_str()); " Returns: 0\n",
output1.c_str());
// Makes sure the return value is printed. // Makes sure the return value is printed.
// A void mock function. // A void mock function.
NaggyMock<MockC> c; NaggyMock<MockC> c;
CaptureStdout(); CaptureStdout();
c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable()); c.VoidMethod(false, 5, "Hi", nullptr, Printable(), Unprintable());
const std::string output2 = GetCapturedStdout(); const std::string output2 = GetCapturedStdout();
EXPECT_THAT(output2.c_str(), EXPECT_THAT(
ContainsRegex( output2.c_str(),
"Uninteresting mock function call - returning directly\\.\n" ContainsRegex("Uninteresting mock function call - returning directly\\.\n"
" Function call: VoidMethod" " Function call: VoidMethod"
"\\(false, 5, \"Hi\", NULL, @.+ " "\\(false, 5, \"Hi\", NULL, @.+ "
"Printable, 4-byte object <00-00 00-00>\\)")); "Printable, 4-byte object <00-00 00-00>\\)"));
// A void function has no return value to print. // A void function has no return value to print.
} }
// Tests how the --gmock_verbose flag affects Google Mock's output. // Tests how the --gmock_verbose flag affects Google Mock's output.
class GMockVerboseFlagTest : public VerboseFlagPreservingFixture { class GMockVerboseFlagTest : public VerboseFlagPreservingFixture {
public: public:
// Verifies that the given Google Mock output is correct. (When // Verifies that the given Google Mock output is correct. (When
// should_print is true, the output should match the given regex and // should_print is true, the output should match the given regex and
// contain the given function name in the stack trace. When it's // contain the given function name in the stack trace. When it's
// false, the output should be empty.) // false, the output should be empty.)
void VerifyOutput(const std::string& output, bool should_print, void VerifyOutput(const std::string& output, bool should_print,
const std::string& expected_substring, const std::string& expected_substring,
const std::string& function_name) { const std::string& function_name) {
if (should_print) { if (should_print) {
EXPECT_THAT(output.c_str(), HasSubstr(expected_substring)); EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));
# ifndef NDEBUG #ifndef NDEBUG
// We check the stack trace content in dbg-mode only, as opt-mode // We check the stack trace content in dbg-mode only, as opt-mode
// may inline the call we are interested in seeing. // may inline the call we are interested in seeing.
EXPECT_THAT(output.c_str(), HasSubstr(function_name)); EXPECT_THAT(output.c_str(), HasSubstr(function_name));
# else #else
// Suppresses 'unused function parameter' warnings. // Suppresses 'unused function parameter' warnings.
static_cast<void>(function_name); static_cast<void>(function_name);
# endif // NDEBUG #endif // NDEBUG
} else { } else {
EXPECT_STREQ("", output.c_str()); EXPECT_STREQ("", output.c_str());
} }
} }
// Tests how the flag affects expected calls. // Tests how the flag affects expected calls.
void TestExpectedCall(bool should_print) { void TestExpectedCall(bool should_print) {
MockA a; MockA a;
EXPECT_CALL(a, DoA(5)); EXPECT_CALL(a, DoA(5));
EXPECT_CALL(a, Binary(_, 1)) EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));
.WillOnce(Return(true));
// A void-returning function. // A void-returning function.
CaptureStdout(); CaptureStdout();
a.DoA(5); a.DoA(5);
VerifyOutput( VerifyOutput(GetCapturedStdout(), should_print,
GetCapturedStdout(), "Mock function call matches EXPECT_CALL(a, DoA(5))...\n"
should_print, " Function call: DoA(5)\n"
"Mock function call matches EXPECT_CALL(a, DoA(5))...\n" "Stack trace:\n",
" Function call: DoA(5)\n" "DoA");
"Stack trace:\n",
"DoA");
// A non-void-returning function. // A non-void-returning function.
CaptureStdout(); CaptureStdout();
a.Binary(2, 1); a.Binary(2, 1);
VerifyOutput( VerifyOutput(GetCapturedStdout(), should_print,
GetCapturedStdout(), "Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n"
should_print, " Function call: Binary(2, 1)\n"
"Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\n" " Returns: true\n"
" Function call: Binary(2, 1)\n" "Stack trace:\n",
" Returns: true\n" "Binary");
"Stack trace:\n",
"Binary");
} }
// Tests how the flag affects uninteresting calls on a naggy mock. // Tests how the flag affects uninteresting calls on a naggy mock.
void TestUninterestingCallOnNaggyMock(bool should_print) { void TestUninterestingCallOnNaggyMock(bool should_print) {
NaggyMock<MockA> a; NaggyMock<MockA> a;
const std::string note = const std::string note =
"NOTE: You can safely ignore the above warning unless this " "NOTE: You can safely ignore the above warning unless this "
"call should not happen. Do not suppress it by blindly adding " "call should not happen. Do not suppress it by blindly adding "
"an EXPECT_CALL() if you don't mean to enforce the call. " "an EXPECT_CALL() if you don't mean to enforce the call. "
"See " "See "
"https://github.com/google/googletest/blob/master/docs/" "https://github.com/google/googletest/blob/master/docs/"
"gmock_cook_book.md#" "gmock_cook_book.md#"
"knowing-when-to-expect for details."; "knowing-when-to-expect for details.";
// A void-returning function. // A void-returning function.
CaptureStdout(); CaptureStdout();
a.DoA(5); a.DoA(5);
VerifyOutput( VerifyOutput(GetCapturedStdout(), should_print,
GetCapturedStdout(), "\nGMOCK WARNING:\n"
should_print, "Uninteresting mock function call - returning directly.\n"
"\nGMOCK WARNING:\n" " Function call: DoA(5)\n" +
"Uninteresting mock function call - returning directly.\n" note,
" Function call: DoA(5)\n" + "DoA");
note,
"DoA");
// A non-void-returning function. // A non-void-returning function.
CaptureStdout(); CaptureStdout();
a.Binary(2, 1); a.Binary(2, 1);
VerifyOutput( VerifyOutput(GetCapturedStdout(), should_print,
GetCapturedStdout(), "\nGMOCK WARNING:\n"
should_print, "Uninteresting mock function call - returning default value.\n"
"\nGMOCK WARNING:\n" " Function call: Binary(2, 1)\n"
"Uninteresting mock function call - returning default value.\n" " Returns: false\n" +
" Function call: Binary(2, 1)\n" note,
" Returns: false\n" + "Binary");
note,
"Binary");
} }
}; };
// Tests that --gmock_verbose=info causes both expected and // Tests that --gmock_verbose=info causes both expected and
// uninteresting calls to be reported. // uninteresting calls to be reported.
TEST_F(GMockVerboseFlagTest, Info) { TEST_F(GMockVerboseFlagTest, Info) {
GMOCK_FLAG(verbose) = kInfoVerbosity; GMOCK_FLAG_SET(verbose, kInfoVerbosity);
TestExpectedCall(true); TestExpectedCall(true);
TestUninterestingCallOnNaggyMock(true); TestUninterestingCallOnNaggyMock(true);
} }
// Tests that --gmock_verbose=warning causes uninteresting calls to be // Tests that --gmock_verbose=warning causes uninteresting calls to be
// reported. // reported.
TEST_F(GMockVerboseFlagTest, Warning) { TEST_F(GMockVerboseFlagTest, Warning) {
GMOCK_FLAG(verbose) = kWarningVerbosity; GMOCK_FLAG_SET(verbose, kWarningVerbosity);
TestExpectedCall(false); TestExpectedCall(false);
TestUninterestingCallOnNaggyMock(true); TestUninterestingCallOnNaggyMock(true);
} }
// Tests that --gmock_verbose=warning causes neither expected nor // Tests that --gmock_verbose=warning causes neither expected nor
// uninteresting calls to be reported. // uninteresting calls to be reported.
TEST_F(GMockVerboseFlagTest, Error) { TEST_F(GMockVerboseFlagTest, Error) {
GMOCK_FLAG(verbose) = kErrorVerbosity; GMOCK_FLAG_SET(verbose, kErrorVerbosity);
TestExpectedCall(false); TestExpectedCall(false);
TestUninterestingCallOnNaggyMock(false); TestUninterestingCallOnNaggyMock(false);
} }
// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect // Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect
// as --gmock_verbose=warning. // as --gmock_verbose=warning.
TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) { TEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {
GMOCK_FLAG(verbose) = "invalid"; // Treated as "warning". GMOCK_FLAG_SET(verbose, "invalid"); // Treated as "warning".
TestExpectedCall(false); TestExpectedCall(false);
TestUninterestingCallOnNaggyMock(true); TestUninterestingCallOnNaggyMock(true);
} }
#endif // GTEST_HAS_STREAM_REDIRECTION #endif // GTEST_HAS_STREAM_REDIRECTION
// A helper class that generates a failure when printed. We use it to // A helper class that generates a failure when printed. We use it to
// ensure that Google Mock doesn't print a value (even to an internal // ensure that Google Mock doesn't print a value (even to an internal
// buffer) when it is not supposed to do so. // buffer) when it is not supposed to do so.
class PrintMeNot {}; class PrintMeNot {};
skipping to change at line 2263 skipping to change at line 2140
<< "printed even to an internal buffer."; << "printed even to an internal buffer.";
} }
class LogTestHelper { class LogTestHelper {
public: public:
LogTestHelper() {} LogTestHelper() {}
MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot)); MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));
private: private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(LogTestHelper); LogTestHelper(const LogTestHelper&) = delete;
LogTestHelper& operator=(const LogTestHelper&) = delete;
}; };
class GMockLogTest : public VerboseFlagPreservingFixture { class GMockLogTest : public VerboseFlagPreservingFixture {
protected: protected:
LogTestHelper helper_; LogTestHelper helper_;
}; };
TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) { TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {
GMOCK_FLAG(verbose) = kWarningVerbosity; GMOCK_FLAG_SET(verbose, kWarningVerbosity);
EXPECT_CALL(helper_, Foo(_)) EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
.WillOnce(Return(PrintMeNot()));
helper_.Foo(PrintMeNot()); // This is an expected call. helper_.Foo(PrintMeNot()); // This is an expected call.
} }
TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) { TEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {
GMOCK_FLAG(verbose) = kErrorVerbosity; GMOCK_FLAG_SET(verbose, kErrorVerbosity);
EXPECT_CALL(helper_, Foo(_)) EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));
.WillOnce(Return(PrintMeNot()));
helper_.Foo(PrintMeNot()); // This is an expected call. helper_.Foo(PrintMeNot()); // This is an expected call.
} }
TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) { TEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {
GMOCK_FLAG(verbose) = kErrorVerbosity; GMOCK_FLAG_SET(verbose, kErrorVerbosity);
ON_CALL(helper_, Foo(_)) ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));
.WillByDefault(Return(PrintMeNot()));
helper_.Foo(PrintMeNot()); // This should generate a warning. helper_.Foo(PrintMeNot()); // This should generate a warning.
} }
// Tests Mock::AllowLeak(). // Tests Mock::AllowLeak().
TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) { TEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {
MockA* a = new MockA; MockA* a = new MockA;
Mock::AllowLeak(a); Mock::AllowLeak(a);
} }
skipping to change at line 2349 skipping to change at line 2224
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that we can verify and clear a mock object's expectations // Tests that we can verify and clear a mock object's expectations
// when some, but not all, of its methods have expectations *and* the // when some, but not all, of its methods have expectations *and* the
// verification succeeds. // verification succeeds.
TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) { TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1));
.WillOnce(Return(1));
b.DoB(); b.DoB();
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
// There should be no expectations on the methods now, so we can // There should be no expectations on the methods now, so we can
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that we can verify and clear a mock object's expectations // Tests that we can verify and clear a mock object's expectations
// when some, but not all, of its methods have expectations *and* the // when some, but not all, of its methods have expectations *and* the
// verification fails. // verification fails.
TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) { TEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1));
.WillOnce(Return(1));
bool result = true; bool result = true;
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
"Actual: never called"); "Actual: never called");
ASSERT_FALSE(result); ASSERT_FALSE(result);
// There should be no expectations on the methods now, so we can // There should be no expectations on the methods now, so we can
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that we can verify and clear a mock object's expectations // Tests that we can verify and clear a mock object's expectations
// when all of its methods have expectations. // when all of its methods have expectations.
TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) { TEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {
MockB b; MockB b;
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(1));
.WillOnce(Return(1)); EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
EXPECT_CALL(b, DoB(_))
.WillOnce(Return(2));
b.DoB(); b.DoB();
b.DoB(1); b.DoB(1);
ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b)); ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));
// There should be no expectations on the methods now, so we can // There should be no expectations on the methods now, so we can
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that we can verify and clear a mock object's expectations // Tests that we can verify and clear a mock object's expectations
// when a method has more than one expectation. // when a method has more than one expectation.
TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) { TEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {
MockB b; MockB b;
EXPECT_CALL(b, DoB(0)) EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));
.WillOnce(Return(1)); EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
EXPECT_CALL(b, DoB(_))
.WillOnce(Return(2));
b.DoB(1); b.DoB(1);
bool result = true; bool result = true;
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b), EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),
"Actual: never called"); "Actual: never called");
ASSERT_FALSE(result); ASSERT_FALSE(result);
// There should be no expectations on the methods now, so we can // There should be no expectations on the methods now, so we can
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that we can call VerifyAndClearExpectations() on the same // Tests that we can call VerifyAndClearExpectations() on the same
// mock object multiple times. // mock object multiple times.
TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) { TEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {
MockB b; MockB b;
EXPECT_CALL(b, DoB()); EXPECT_CALL(b, DoB());
b.DoB(); b.DoB();
Mock::VerifyAndClearExpectations(&b); Mock::VerifyAndClearExpectations(&b);
EXPECT_CALL(b, DoB(_)) EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));
.WillOnce(Return(1));
b.DoB(1); b.DoB(1);
Mock::VerifyAndClearExpectations(&b); Mock::VerifyAndClearExpectations(&b);
Mock::VerifyAndClearExpectations(&b); Mock::VerifyAndClearExpectations(&b);
// There should be no expectations on the methods now, so we can // There should be no expectations on the methods now, so we can
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
skipping to change at line 2449 skipping to change at line 2317
MockB b; MockB b;
// If this crashes or generates a failure, the test will catch it. // If this crashes or generates a failure, the test will catch it.
Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b);
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
} }
// Tests that we can clear a mock object's default actions when some, // Tests that we can clear a mock object's default actions when some,
// but not all of its methods have default actions. // but not all of its methods have default actions.
TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) { TEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {
MockB b; MockB b;
ON_CALL(b, DoB()) ON_CALL(b, DoB()).WillByDefault(Return(1));
.WillByDefault(Return(1));
Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b);
// Verifies that the default action of int DoB() was removed. // Verifies that the default action of int DoB() was removed.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
} }
// Tests that we can clear a mock object's default actions when all of // Tests that we can clear a mock object's default actions when all of
// its methods have default actions. // its methods have default actions.
TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) { TEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {
MockB b; MockB b;
ON_CALL(b, DoB()) ON_CALL(b, DoB()).WillByDefault(Return(1));
.WillByDefault(Return(1)); ON_CALL(b, DoB(_)).WillByDefault(Return(2));
ON_CALL(b, DoB(_))
.WillByDefault(Return(2));
Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b);
// Verifies that the default action of int DoB() was removed. // Verifies that the default action of int DoB() was removed.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
// Verifies that the default action of int DoB(int) was removed. // Verifies that the default action of int DoB(int) was removed.
EXPECT_EQ(0, b.DoB(0)); EXPECT_EQ(0, b.DoB(0));
} }
// Tests that we can clear a mock object's default actions when a // Tests that we can clear a mock object's default actions when a
// method has more than one ON_CALL() set on it. // method has more than one ON_CALL() set on it.
TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) { TEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {
MockB b; MockB b;
ON_CALL(b, DoB(0)) ON_CALL(b, DoB(0)).WillByDefault(Return(1));
.WillByDefault(Return(1)); ON_CALL(b, DoB(_)).WillByDefault(Return(2));
ON_CALL(b, DoB(_))
.WillByDefault(Return(2));
Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b);
// Verifies that the default actions (there are two) of int DoB(int) // Verifies that the default actions (there are two) of int DoB(int)
// were removed. // were removed.
EXPECT_EQ(0, b.DoB(0)); EXPECT_EQ(0, b.DoB(0));
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that we can call VerifyAndClear() on a mock object multiple // Tests that we can call VerifyAndClear() on a mock object multiple
// times. // times.
TEST(VerifyAndClearTest, CanCallManyTimes) { TEST(VerifyAndClearTest, CanCallManyTimes) {
MockB b; MockB b;
ON_CALL(b, DoB()) ON_CALL(b, DoB()).WillByDefault(Return(1));
.WillByDefault(Return(1));
Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b);
Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b);
ON_CALL(b, DoB(_)) ON_CALL(b, DoB(_)).WillByDefault(Return(1));
.WillByDefault(Return(1));
Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b);
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that VerifyAndClear() works when the verification succeeds. // Tests that VerifyAndClear() works when the verification succeeds.
TEST(VerifyAndClearTest, Success) { TEST(VerifyAndClearTest, Success) {
MockB b; MockB b;
ON_CALL(b, DoB()) ON_CALL(b, DoB()).WillByDefault(Return(1));
.WillByDefault(Return(1)); EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));
EXPECT_CALL(b, DoB(1))
.WillOnce(Return(2));
b.DoB(); b.DoB();
b.DoB(1); b.DoB(1);
ASSERT_TRUE(Mock::VerifyAndClear(&b)); ASSERT_TRUE(Mock::VerifyAndClear(&b));
// There should be no expectations on the methods now, so we can // There should be no expectations on the methods now, so we can
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that VerifyAndClear() works when the verification fails. // Tests that VerifyAndClear() works when the verification fails.
TEST(VerifyAndClearTest, Failure) { TEST(VerifyAndClearTest, Failure) {
MockB b; MockB b;
ON_CALL(b, DoB(_)) ON_CALL(b, DoB(_)).WillByDefault(Return(1));
.WillByDefault(Return(1)); EXPECT_CALL(b, DoB()).WillOnce(Return(2));
EXPECT_CALL(b, DoB())
.WillOnce(Return(2));
b.DoB(1); b.DoB(1);
bool result = true; bool result = true;
EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b), EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),
"Actual: never called"); "Actual: never called");
ASSERT_FALSE(result); ASSERT_FALSE(result);
// There should be no expectations on the methods now, so we can // There should be no expectations on the methods now, so we can
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that VerifyAndClear() works when the default actions and // Tests that VerifyAndClear() works when the default actions and
// expectations are set on a const mock object. // expectations are set on a const mock object.
TEST(VerifyAndClearTest, Const) { TEST(VerifyAndClearTest, Const) {
MockB b; MockB b;
ON_CALL(Const(b), DoB()) ON_CALL(Const(b), DoB()).WillByDefault(Return(1));
.WillByDefault(Return(1));
EXPECT_CALL(Const(b), DoB()) EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));
.WillOnce(DoDefault())
.WillOnce(Return(2));
b.DoB(); b.DoB();
b.DoB(); b.DoB();
ASSERT_TRUE(Mock::VerifyAndClear(&b)); ASSERT_TRUE(Mock::VerifyAndClear(&b));
// There should be no expectations on the methods now, so we can // There should be no expectations on the methods now, so we can
// freely call them. // freely call them.
EXPECT_EQ(0, b.DoB()); EXPECT_EQ(0, b.DoB());
EXPECT_EQ(0, b.DoB(1)); EXPECT_EQ(0, b.DoB(1));
} }
// Tests that we can set default actions and expectations on a mock // Tests that we can set default actions and expectations on a mock
// object after VerifyAndClear() has been called on it. // object after VerifyAndClear() has been called on it.
TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) { TEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {
MockB b; MockB b;
ON_CALL(b, DoB()) ON_CALL(b, DoB()).WillByDefault(Return(1));
.WillByDefault(Return(1)); EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));
EXPECT_CALL(b, DoB(_))
.WillOnce(Return(2));
b.DoB(1); b.DoB(1);
Mock::VerifyAndClear(&b); Mock::VerifyAndClear(&b);
EXPECT_CALL(b, DoB()) EXPECT_CALL(b, DoB()).WillOnce(Return(3));
.WillOnce(Return(3)); ON_CALL(b, DoB(_)).WillByDefault(Return(4));
ON_CALL(b, DoB(_))
.WillByDefault(Return(4));
EXPECT_EQ(3, b.DoB()); EXPECT_EQ(3, b.DoB());
EXPECT_EQ(4, b.DoB(1)); EXPECT_EQ(4, b.DoB(1));
} }
// Tests that calling VerifyAndClear() on one mock object does not // Tests that calling VerifyAndClear() on one mock object does not
// affect other mock objects (either of the same type or not). // affect other mock objects (either of the same type or not).
TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) { TEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {
MockA a; MockA a;
MockB b1; MockB b1;
MockB b2; MockB b2;
ON_CALL(a, Binary(_, _)) ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));
.WillByDefault(Return(true)); EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));
EXPECT_CALL(a, Binary(_, _))
.WillOnce(DoDefault())
.WillOnce(Return(false));
ON_CALL(b1, DoB())
.WillByDefault(Return(1));
EXPECT_CALL(b1, DoB(_))
.WillOnce(Return(2));
ON_CALL(b2, DoB()) ON_CALL(b1, DoB()).WillByDefault(Return(1));
.WillByDefault(Return(3)); EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));
ON_CALL(b2, DoB()).WillByDefault(Return(3));
EXPECT_CALL(b2, DoB(_)); EXPECT_CALL(b2, DoB(_));
b2.DoB(0); b2.DoB(0);
Mock::VerifyAndClear(&b2); Mock::VerifyAndClear(&b2);
// Verifies that the default actions and expectations of a and b1 // Verifies that the default actions and expectations of a and b1
// are still in effect. // are still in effect.
EXPECT_TRUE(a.Binary(0, 0)); EXPECT_TRUE(a.Binary(0, 0));
EXPECT_FALSE(a.Binary(0, 0)); EXPECT_FALSE(a.Binary(0, 0));
skipping to change at line 2650 skipping to change at line 2494
// The state of all mocks is protected by a single global lock, but there // The state of all mocks is protected by a single global lock, but there
// should be no deadlock. // should be no deadlock.
} }
TEST(VerifyAndClearTest, TEST(VerifyAndClearTest,
DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) { DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {
std::shared_ptr<MockA> a(new MockA); std::shared_ptr<MockA> a(new MockA);
ReferenceHoldingMock test_mock; ReferenceHoldingMock test_mock;
// ON_CALL stores a reference to a inside test_mock. // ON_CALL stores a reference to a inside test_mock.
ON_CALL(test_mock, AcceptReference(_)) ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));
.WillByDefault(SetArgPointee<0>(a));
// Throw away the reference to the mock that we have in a. After this, the // Throw away the reference to the mock that we have in a. After this, the
// only reference to it is stored by test_mock. // only reference to it is stored by test_mock.
a.reset(); a.reset();
// When test_mock goes out of scope, it destroys the last remaining reference // When test_mock goes out of scope, it destroys the last remaining reference
// to the mock object originally pointed to by a. This will cause the MockA // to the mock object originally pointed to by a. This will cause the MockA
// destructor to be called from inside the ReferenceHoldingMock destructor. // destructor to be called from inside the ReferenceHoldingMock destructor.
// The state of all mocks is protected by a single global lock, but there // The state of all mocks is protected by a single global lock, but there
// should be no deadlock. // should be no deadlock.
} }
// Tests that a mock function's action can call a mock function // Tests that a mock function's action can call a mock function
// (either the same function or a different one) either as an explicit // (either the same function or a different one) either as an explicit
// action or as a default action without causing a dead lock. It // action or as a default action without causing a dead lock. It
// verifies that the action is not performed inside the critical // verifies that the action is not performed inside the critical
// section. // section.
TEST(SynchronizationTest, CanCallMockMethodInAction) { TEST(SynchronizationTest, CanCallMockMethodInAction) {
MockA a; MockA a;
MockC c; MockC c;
ON_CALL(a, DoA(_)) ON_CALL(a, DoA(_)).WillByDefault(
.WillByDefault(IgnoreResult(InvokeWithoutArgs(&c, IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));
&MockC::NonVoidMethod)));
EXPECT_CALL(a, DoA(1)); EXPECT_CALL(a, DoA(1));
EXPECT_CALL(a, DoA(1)) EXPECT_CALL(a, DoA(1))
.WillOnce(Invoke(&a, &MockA::DoA)) .WillOnce(Invoke(&a, &MockA::DoA))
.RetiresOnSaturation(); .RetiresOnSaturation();
EXPECT_CALL(c, NonVoidMethod()); EXPECT_CALL(c, NonVoidMethod());
a.DoA(1); a.DoA(1);
// This will match the second EXPECT_CALL() and trigger another a.DoA(1), // This will match the second EXPECT_CALL() and trigger another a.DoA(1),
// which will in turn match the first EXPECT_CALL() and trigger a call to // which will in turn match the first EXPECT_CALL() and trigger a call to
// c.NonVoidMethod() that was specified by the ON_CALL() since the first // c.NonVoidMethod() that was specified by the ON_CALL() since the first
skipping to change at line 2758 skipping to change at line 2600
EXPECT_THAT(mock.Overloaded(5), 9); EXPECT_THAT(mock.Overloaded(5), 9);
EXPECT_THAT(mock.Overloaded(7), 7); EXPECT_THAT(mock.Overloaded(7), 7);
const MockConstOverload& const_mock = mock; const MockConstOverload& const_mock = mock;
EXPECT_THAT(const_mock.Overloaded(1), 0); EXPECT_THAT(const_mock.Overloaded(1), 0);
EXPECT_THAT(const_mock.Overloaded(5), 11); EXPECT_THAT(const_mock.Overloaded(5), 11);
EXPECT_THAT(const_mock.Overloaded(7), 13); EXPECT_THAT(const_mock.Overloaded(7), 13);
} }
} // namespace } // namespace
} // namespace testing
// Allows the user to define their own main and then invoke gmock_main // Allows the user to define their own main and then invoke gmock_main
// from it. This might be necessary on some platforms which require // from it. This might be necessary on some platforms which require
// specific setup and teardown. // specific setup and teardown.
#if GMOCK_RENAME_MAIN #if GMOCK_RENAME_MAIN
int gmock_main(int argc, char **argv) { int gmock_main(int argc, char** argv) {
#else #else
int main(int argc, char **argv) { int main(int argc, char** argv) {
#endif // GMOCK_RENAME_MAIN #endif // GMOCK_RENAME_MAIN
testing::InitGoogleMock(&argc, argv); testing::InitGoogleMock(&argc, argv);
// Ensures that the tests pass no matter what value of // Ensures that the tests pass no matter what value of
// --gmock_catch_leaked_mocks and --gmock_verbose the user specifies. // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.
testing::GMOCK_FLAG(catch_leaked_mocks) = true; GMOCK_FLAG_SET(catch_leaked_mocks, true);
testing::GMOCK_FLAG(verbose) = testing::internal::kWarningVerbosity; GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }
 End of changes. 171 change blocks. 
620 lines changed or deleted 463 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)