106class ExpectationBase;
110class TypedExpectation;
113class ExpectationTester;
116template <
typename MockClass>
118template <
typename MockClass>
120template <
typename MockClass>
134GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
139class GTEST_API_ UntypedFunctionMockerBase {
141 UntypedFunctionMockerBase();
142 virtual ~UntypedFunctionMockerBase();
147 bool VerifyAndClearExpectationsLocked()
148 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
151 virtual void ClearDefaultActionsLocked()
152 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
161 virtual void UntypedDescribeUninterestingCall(
const void* untyped_args,
162 ::std::ostream* os)
const
163 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
171 virtual const ExpectationBase* UntypedFindMatchingExpectation(
172 const void* untyped_args,
const void** untyped_action,
bool* is_excessive,
173 ::std::ostream* what, ::std::ostream* why)
174 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
177 virtual void UntypedPrintArgs(
const void* untyped_args,
178 ::std::ostream* os)
const = 0;
184 void RegisterOwner(
const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
189 void SetOwnerAndName(
const void* mock_obj,
const char* name)
190 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
195 const void* MockObject()
const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
199 const char* Name()
const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
202 typedef std::vector<const void*> UntypedOnCallSpecs;
204 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
208 Expectation GetHandleOf(ExpectationBase* exp);
213 const void* mock_obj_;
220 UntypedOnCallSpecs untyped_on_call_specs_;
231 UntypedExpectations untyped_expectations_;
235class UntypedOnCallSpecBase {
238 UntypedOnCallSpecBase(
const char* a_file,
int a_line)
239 : file_(a_file), line_(a_line), last_clause_(kNone) {}
242 const char* file()
const {
return file_; }
243 int line()
const {
return line_; }
256 void AssertSpecProperty(
bool property,
257 const std::string& failure_message)
const {
258 Assert(property, file_, line_, failure_message);
262 void ExpectSpecProperty(
bool property,
263 const std::string& failure_message)
const {
264 Expect(property, file_, line_, failure_message);
277class OnCallSpec :
public UntypedOnCallSpecBase {
279 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
280 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
284 OnCallSpec(
const char* a_file,
int a_line,
285 const ArgumentMatcherTuple& matchers)
286 : UntypedOnCallSpecBase(a_file, a_line),
291 extra_matcher_(A<const ArgumentTuple&>()) {}
294 OnCallSpec& With(
const Matcher<const ArgumentTuple&>& m) {
296 ExpectSpecProperty(last_clause_ < kWith,
297 ".With() cannot appear "
298 "more than once in an ON_CALL().");
299 last_clause_ = kWith;
306 OnCallSpec& WillByDefault(
const Action<F>& action) {
307 ExpectSpecProperty(last_clause_ < kWillByDefault,
308 ".WillByDefault() must appear "
309 "exactly once in an ON_CALL().");
310 last_clause_ = kWillByDefault;
312 ExpectSpecProperty(!action.IsDoDefault(),
313 "DoDefault() cannot be used in ON_CALL().");
319 bool Matches(
const ArgumentTuple& args)
const {
320 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
324 const Action<F>& GetAction()
const {
325 AssertSpecProperty(last_clause_ == kWillByDefault,
326 ".WillByDefault() must appear exactly "
327 "once in an ON_CALL().");
345 ArgumentMatcherTuple matchers_;
346 Matcher<const ArgumentTuple&> extra_matcher_;
360class GTEST_API_ Mock {
366 static void AllowLeak(
const void* mock_obj)
367 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
372 static bool VerifyAndClearExpectations(
void* mock_obj)
373 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
378 static bool VerifyAndClear(
void* mock_obj)
379 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
382 static bool IsNaggy(
void* mock_obj)
383 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
385 static bool IsNice(
void* mock_obj)
386 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
388 static bool IsStrict(
void* mock_obj)
389 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
392 friend class internal::UntypedFunctionMockerBase;
396 template <
typename F>
397 friend class internal::FunctionMocker;
399 template <
typename MockClass>
400 friend class internal::NiceMockImpl;
401 template <
typename MockClass>
402 friend class internal::NaggyMockImpl;
403 template <
typename MockClass>
404 friend class internal::StrictMockImpl;
408 static void AllowUninterestingCalls(uintptr_t mock_obj)
409 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
413 static void WarnUninterestingCalls(uintptr_t mock_obj)
414 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
418 static void FailUninterestingCalls(uintptr_t mock_obj)
419 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
423 static void UnregisterCallReaction(uintptr_t mock_obj)
424 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
428 static internal::CallReaction GetReactionOnUninterestingCalls(
429 const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
434 static bool VerifyAndClearExpectationsLocked(
void* mock_obj)
435 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
438 static void ClearDefaultActionsLocked(
void* mock_obj)
439 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
442 static void Register(
const void* mock_obj,
443 internal::UntypedFunctionMockerBase* mocker)
444 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
449 static void RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
450 const char* file,
int line)
451 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
457 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
458 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
477class GTEST_API_ Expectation {
481 Expectation(Expectation&&) =
default;
482 Expectation(
const Expectation&) =
default;
483 Expectation& operator=(Expectation&&) =
default;
484 Expectation& operator=(
const Expectation&) =
default;
496 Expectation(internal::ExpectationBase& exp);
503 bool operator==(
const Expectation& rhs)
const {
504 return expectation_base_ == rhs.expectation_base_;
507 bool operator!=(
const Expectation& rhs)
const {
return !(*
this == rhs); }
510 friend class ExpectationSet;
511 friend class Sequence;
512 friend class ::testing::internal::ExpectationBase;
513 friend class ::testing::internal::UntypedFunctionMockerBase;
515 template <
typename F>
516 friend class ::testing::internal::FunctionMocker;
518 template <
typename F>
519 friend class ::testing::internal::TypedExpectation;
524 bool operator()(
const Expectation& lhs,
const Expectation& rhs)
const {
525 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
529 typedef ::std::set<Expectation, Less> Set;
532 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
535 const std::shared_ptr<internal::ExpectationBase>& expectation_base()
const {
536 return expectation_base_;
540 std::shared_ptr<internal::ExpectationBase> expectation_base_;
556class ExpectationSet {
559 typedef Expectation::Set::const_iterator const_iterator;
562 typedef Expectation::Set::value_type value_type;
570 ExpectationSet(internal::ExpectationBase& exp) {
571 *
this += Expectation(exp);
577 ExpectationSet(
const Expectation& e) {
586 bool operator==(
const ExpectationSet& rhs)
const {
587 return expectations_ == rhs.expectations_;
590 bool operator!=(
const ExpectationSet& rhs)
const {
return !(*
this == rhs); }
594 ExpectationSet& operator+=(
const Expectation& e) {
595 expectations_.insert(e);
599 int size()
const {
return static_cast<int>(expectations_.size()); }
601 const_iterator begin()
const {
return expectations_.begin(); }
602 const_iterator end()
const {
return expectations_.end(); }
605 Expectation::Set expectations_;
611class GTEST_API_ Sequence {
614 Sequence() : last_expectation_(
new Expectation) {}
618 void AddExpectation(
const Expectation& expectation)
const;
622 std::shared_ptr<Expectation> last_expectation_;
649class GTEST_API_ InSequence {
655 bool sequence_created_;
657 InSequence(
const InSequence&) =
delete;
658 InSequence& operator=(
const InSequence&) =
delete;
659} GTEST_ATTRIBUTE_UNUSED_;
665GTEST_API_
extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
681class GTEST_API_ ExpectationBase {
684 ExpectationBase(
const char* file,
int line,
const std::string& source_text);
686 virtual ~ExpectationBase();
689 const char* file()
const {
return file_; }
690 int line()
const {
return line_; }
691 const char* source_text()
const {
return source_text_.c_str(); }
693 const Cardinality& cardinality()
const {
return cardinality_; }
696 void DescribeLocationTo(::std::ostream* os)
const {
697 *os << FormatFileLocation(file(), line()) <<
" ";
702 void DescribeCallCountTo(::std::ostream* os)
const
703 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
707 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
710 friend class ::testing::Expectation;
711 friend class UntypedFunctionMockerBase;
725 typedef std::vector<const void*> UntypedActions;
729 virtual Expectation GetHandle() = 0;
732 void AssertSpecProperty(
bool property,
733 const std::string& failure_message)
const {
734 Assert(property, file_, line_, failure_message);
738 void ExpectSpecProperty(
bool property,
739 const std::string& failure_message)
const {
740 Expect(property, file_, line_, failure_message);
745 void SpecifyCardinality(
const Cardinality& cardinality);
749 bool cardinality_specified()
const {
return cardinality_specified_; }
752 void set_cardinality(
const Cardinality& a_cardinality) {
753 cardinality_ = a_cardinality;
761 void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
764 bool is_retired()
const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
765 g_gmock_mutex.AssertHeld();
770 void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
771 g_gmock_mutex.AssertHeld();
776 bool IsSatisfied()
const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
777 g_gmock_mutex.AssertHeld();
778 return cardinality().IsSatisfiedByCallCount(call_count_);
782 bool IsSaturated()
const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
783 g_gmock_mutex.AssertHeld();
784 return cardinality().IsSaturatedByCallCount(call_count_);
788 bool IsOverSaturated()
const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
789 g_gmock_mutex.AssertHeld();
790 return cardinality().IsOverSaturatedByCallCount(call_count_);
795 bool AllPrerequisitesAreSatisfied()
const
796 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
799 void FindUnsatisfiedPrerequisites(ExpectationSet* result)
const
800 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
803 int call_count()
const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
804 g_gmock_mutex.AssertHeld();
809 void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
810 g_gmock_mutex.AssertHeld();
818 void CheckActionCountIfNotDone()
const GTEST_LOCK_EXCLUDED_(mutex_);
820 friend class ::testing::Sequence;
821 friend class ::testing::internal::ExpectationTester;
823 template <
typename Function>
824 friend class TypedExpectation;
827 void UntypedTimes(
const Cardinality& a_cardinality);
833 const std::string source_text_;
835 bool cardinality_specified_;
836 Cardinality cardinality_;
843 ExpectationSet immediate_prerequisites_;
849 UntypedActions untyped_actions_;
850 bool extra_matcher_specified_;
851 bool repeated_action_specified_;
852 bool retires_on_saturation_;
854 mutable bool action_count_checked_;
855 mutable Mutex mutex_;
859class TypedExpectation;
862template <
typename R,
typename... Args>
863class TypedExpectation<R(Args...)> :
public ExpectationBase {
865 using F = R(Args...);
868 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
869 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
870 typedef typename Function<F>::Result Result;
872 TypedExpectation(FunctionMocker<F>* owner,
const char* a_file,
int a_line,
873 const std::string& a_source_text,
874 const ArgumentMatcherTuple& m)
875 : ExpectationBase(a_file, a_line, a_source_text),
881 extra_matcher_(A<const ArgumentTuple&>()),
882 repeated_action_(DoDefault()) {}
884 ~TypedExpectation()
override {
887 CheckActionCountIfNotDone();
888 for (UntypedActions::const_iterator it = untyped_actions_.begin();
889 it != untyped_actions_.end(); ++it) {
890 delete static_cast<const Action<F>*
>(*it);
895 TypedExpectation& With(
const Matcher<const ArgumentTuple&>& m) {
896 if (last_clause_ == kWith) {
897 ExpectSpecProperty(
false,
898 ".With() cannot appear "
899 "more than once in an EXPECT_CALL().");
901 ExpectSpecProperty(last_clause_ < kWith,
902 ".With() must be the first "
903 "clause in an EXPECT_CALL().");
905 last_clause_ = kWith;
908 extra_matcher_specified_ =
true;
913 TypedExpectation& Times(
const Cardinality& a_cardinality) {
914 ExpectationBase::UntypedTimes(a_cardinality);
919 TypedExpectation& Times(
int n) {
return Times(Exactly(n)); }
922 TypedExpectation& InSequence(
const Sequence& s) {
923 ExpectSpecProperty(last_clause_ <= kInSequence,
924 ".InSequence() cannot appear after .After(),"
925 " .WillOnce(), .WillRepeatedly(), or "
926 ".RetiresOnSaturation().");
927 last_clause_ = kInSequence;
929 s.AddExpectation(GetHandle());
932 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2) {
933 return InSequence(s1).InSequence(s2);
935 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
936 const Sequence& s3) {
937 return InSequence(s1, s2).InSequence(s3);
939 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
940 const Sequence& s3,
const Sequence& s4) {
941 return InSequence(s1, s2, s3).InSequence(s4);
943 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
944 const Sequence& s3,
const Sequence& s4,
945 const Sequence& s5) {
946 return InSequence(s1, s2, s3, s4).InSequence(s5);
950 TypedExpectation& After(
const ExpectationSet& s) {
951 ExpectSpecProperty(last_clause_ <= kAfter,
952 ".After() cannot appear after .WillOnce(),"
953 " .WillRepeatedly(), or "
954 ".RetiresOnSaturation().");
955 last_clause_ = kAfter;
957 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
958 immediate_prerequisites_ += *it;
962 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2) {
963 return After(s1).After(s2);
965 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
966 const ExpectationSet& s3) {
967 return After(s1, s2).After(s3);
969 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
970 const ExpectationSet& s3,
const ExpectationSet& s4) {
971 return After(s1, s2, s3).After(s4);
973 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
974 const ExpectationSet& s3,
const ExpectationSet& s4,
975 const ExpectationSet& s5) {
976 return After(s1, s2, s3, s4).After(s5);
981 TypedExpectation& WillOnce(OnceAction<F> once_action) {
985 return WillOnce(Action<F>(ActionAdaptor{
986 std::make_shared<OnceAction<F>>(std::move(once_action)),
995 template <
int&... ExplicitArgumentBarrier,
typename =
void>
996 TypedExpectation& WillOnce(Action<F> action) {
997 ExpectSpecProperty(last_clause_ <= kWillOnce,
998 ".WillOnce() cannot appear after "
999 ".WillRepeatedly() or .RetiresOnSaturation().");
1000 last_clause_ = kWillOnce;
1002 untyped_actions_.push_back(
new Action<F>(std::move(action)));
1004 if (!cardinality_specified()) {
1005 set_cardinality(Exactly(
static_cast<int>(untyped_actions_.size())));
1011 TypedExpectation& WillRepeatedly(
const Action<F>& action) {
1012 if (last_clause_ == kWillRepeatedly) {
1013 ExpectSpecProperty(
false,
1014 ".WillRepeatedly() cannot appear "
1015 "more than once in an EXPECT_CALL().");
1017 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1018 ".WillRepeatedly() cannot appear "
1019 "after .RetiresOnSaturation().");
1021 last_clause_ = kWillRepeatedly;
1022 repeated_action_specified_ =
true;
1024 repeated_action_ = action;
1025 if (!cardinality_specified()) {
1026 set_cardinality(AtLeast(
static_cast<int>(untyped_actions_.size())));
1031 CheckActionCountIfNotDone();
1036 TypedExpectation& RetiresOnSaturation() {
1037 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1038 ".RetiresOnSaturation() cannot appear "
1040 last_clause_ = kRetiresOnSaturation;
1041 retires_on_saturation_ =
true;
1045 CheckActionCountIfNotDone();
1051 const ArgumentMatcherTuple& matchers()
const {
return matchers_; }
1054 const Matcher<const ArgumentTuple&>& extra_matcher()
const {
1055 return extra_matcher_;
1059 const Action<F>& repeated_action()
const {
return repeated_action_; }
1063 void MaybeDescribeExtraMatcherTo(::std::ostream* os)
override {
1064 if (extra_matcher_specified_) {
1065 *os <<
" Expected args: ";
1066 extra_matcher_.DescribeTo(os);
1072 template <
typename Function>
1073 friend class FunctionMocker;
1077 struct ActionAdaptor {
1078 std::shared_ptr<OnceAction<R(Args...)>> once_action;
1080 R operator()(Args&&... args)
const {
1081 return std::move(*once_action).Call(std::forward<Args>(args)...);
1087 Expectation GetHandle()
override {
return owner_->GetHandleOf(
this); }
1094 bool Matches(
const ArgumentTuple& args)
const
1095 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1096 g_gmock_mutex.AssertHeld();
1097 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1102 bool ShouldHandleArguments(
const ArgumentTuple& args)
const
1103 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1104 g_gmock_mutex.AssertHeld();
1110 CheckActionCountIfNotDone();
1111 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1116 void ExplainMatchResultTo(
const ArgumentTuple& args, ::std::ostream* os)
const
1117 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1118 g_gmock_mutex.AssertHeld();
1121 *os <<
" Expected: the expectation is active\n"
1122 <<
" Actual: it is retired\n";
1123 }
else if (!Matches(args)) {
1124 if (!TupleMatches(matchers_, args)) {
1125 ExplainMatchFailureTupleTo(matchers_, args, os);
1127 StringMatchResultListener listener;
1128 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1129 *os <<
" Expected args: ";
1130 extra_matcher_.DescribeTo(os);
1131 *os <<
"\n Actual: don't match";
1133 internal::PrintIfNotEmpty(listener.str(), os);
1136 }
else if (!AllPrerequisitesAreSatisfied()) {
1137 *os <<
" Expected: all pre-requisites are satisfied\n"
1138 <<
" Actual: the following immediate pre-requisites "
1139 <<
"are not satisfied:\n";
1140 ExpectationSet unsatisfied_prereqs;
1141 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1143 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1144 it != unsatisfied_prereqs.end(); ++it) {
1145 it->expectation_base()->DescribeLocationTo(os);
1146 *os <<
"pre-requisite #" << i++ <<
"\n";
1148 *os <<
" (end of pre-requisites)\n";
1154 *os <<
"The call matches the expectation.\n";
1159 const Action<F>& GetCurrentAction(
const FunctionMocker<F>* mocker,
1160 const ArgumentTuple& args)
const
1161 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1162 g_gmock_mutex.AssertHeld();
1163 const int count = call_count();
1164 Assert(count >= 1, __FILE__, __LINE__,
1165 "call_count() is <= 0 when GetCurrentAction() is "
1166 "called - this should never happen.");
1168 const int action_count =
static_cast<int>(untyped_actions_.size());
1169 if (action_count > 0 && !repeated_action_specified_ &&
1170 count > action_count) {
1173 ::std::stringstream ss;
1174 DescribeLocationTo(&ss);
1175 ss <<
"Actions ran out in " << source_text() <<
"...\n"
1176 <<
"Called " << count <<
" times, but only " << action_count
1177 <<
" WillOnce()" << (action_count == 1 ?
" is" :
"s are")
1179 mocker->DescribeDefaultActionTo(args, &ss);
1180 Log(kWarning, ss.str(), 1);
1183 return count <= action_count
1184 ? *
static_cast<const Action<F>*
>(
1185 untyped_actions_[
static_cast<size_t>(count - 1)])
1186 : repeated_action();
1196 const Action<F>* GetActionForArguments(
const FunctionMocker<F>* mocker,
1197 const ArgumentTuple& args,
1198 ::std::ostream* what,
1199 ::std::ostream* why)
1200 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1201 g_gmock_mutex.AssertHeld();
1202 if (IsSaturated()) {
1204 IncrementCallCount();
1205 *what <<
"Mock function called more times than expected - ";
1206 mocker->DescribeDefaultActionTo(args, what);
1207 DescribeCallCountTo(why);
1212 IncrementCallCount();
1213 RetireAllPreRequisites();
1215 if (retires_on_saturation_ && IsSaturated()) {
1220 *what <<
"Mock function call matches " << source_text() <<
"...\n";
1221 return &(GetCurrentAction(mocker, args));
1226 FunctionMocker<F>*
const owner_;
1227 ArgumentMatcherTuple matchers_;
1228 Matcher<const ArgumentTuple&> extra_matcher_;
1229 Action<F> repeated_action_;
1231 TypedExpectation(
const TypedExpectation&) =
delete;
1232 TypedExpectation& operator=(
const TypedExpectation&) =
delete;
1247 const char* file,
int line,
1248 const std::string& message);
1250template <
typename F>
1253 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1255 typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1259 MockSpec(internal::FunctionMocker<F>* function_mocker,
1260 const ArgumentMatcherTuple& matchers)
1261 : function_mocker_(function_mocker), matchers_(matchers) {}
1265 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
const char* file,
1266 int line,
const char* obj,
1268 LogWithLocation(internal::kInfo, file, line,
1269 std::string(
"ON_CALL(") + obj +
", " + call +
") invoked");
1270 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1275 internal::TypedExpectation<F>& InternalExpectedAt(
const char* file,
int line,
1278 const std::string source_text(std::string(
"EXPECT_CALL(") + obj +
", " +
1280 LogWithLocation(internal::kInfo, file, line, source_text +
" invoked");
1281 return function_mocker_->AddNewExpectation(file, line, source_text,
1288 MockSpec<F>& operator()(
const internal::WithoutMatchers&,
void*
const) {
1293 template <
typename Function>
1294 friend class internal::FunctionMocker;
1297 internal::FunctionMocker<F>*
const function_mocker_;
1299 ArgumentMatcherTuple matchers_;
1311template <
typename T>
1312class ReferenceOrValueWrapper {
1315 explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}
1320 T Unwrap() {
return std::move(value_); }
1326 const T& Peek()
const {
return value_; }
1334template <
typename T>
1335class ReferenceOrValueWrapper<T&> {
1339 typedef T& reference;
1340 explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
1341 T& Unwrap() {
return *value_ptr_; }
1342 const T& Peek()
const {
return *value_ptr_; }
1349template <
typename T>
1350void PrintAsActionResult(
const T& result, std::ostream& os) {
1351 os <<
"\n Returns: ";
1353 UniversalPrinter<T>::Print(result, &os);
1358GTEST_API_
void ReportUninterestingCall(CallReaction reaction,
1359 const std::string& msg);
1362class Cleanup final {
1364 explicit Cleanup(std::function<
void()> f) : f_(std::move(f)) {}
1365 ~Cleanup() { f_(); }
1368 std::function<void()> f_;
1371template <
typename F>
1372class FunctionMocker;
1374template <
typename R,
typename... Args>
1375class FunctionMocker<R(Args...)> final :
public UntypedFunctionMockerBase {
1376 using F = R(Args...);
1380 using ArgumentTuple = std::tuple<Args...>;
1381 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1397 FunctionMocker(
const FunctionMocker&) =
delete;
1398 FunctionMocker& operator=(
const FunctionMocker&) =
delete;
1403 ~FunctionMocker()
override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1404 MutexLock l(&g_gmock_mutex);
1405 VerifyAndClearExpectationsLocked();
1406 Mock::UnregisterLocked(
this);
1407 ClearDefaultActionsLocked();
1413 const OnCallSpec<F>* FindOnCallSpec(
const ArgumentTuple& args)
const {
1414 for (UntypedOnCallSpecs::const_reverse_iterator it =
1415 untyped_on_call_specs_.rbegin();
1416 it != untyped_on_call_specs_.rend(); ++it) {
1417 const OnCallSpec<F>* spec =
static_cast<const OnCallSpec<F>*
>(*it);
1418 if (spec->Matches(args))
return spec;
1431 Result PerformDefaultAction(ArgumentTuple&& args,
1432 const std::string& call_description)
const {
1433 const OnCallSpec<F>*
const spec = this->FindOnCallSpec(args);
1434 if (spec !=
nullptr) {
1435 return spec->GetAction().Perform(std::move(args));
1437 const std::string message =
1439 "\n The mock function has no default action "
1440 "set, and its return type has no default value set.";
1441#if GTEST_HAS_EXCEPTIONS
1442 if (!DefaultValue<Result>::Exists()) {
1443 throw std::runtime_error(message);
1446 Assert(DefaultValue<Result>::Exists(),
"", -1, message);
1448 return DefaultValue<Result>::Get();
1453 void ClearDefaultActionsLocked()
override
1454 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1455 g_gmock_mutex.AssertHeld();
1464 UntypedOnCallSpecs specs_to_delete;
1465 untyped_on_call_specs_.swap(specs_to_delete);
1467 g_gmock_mutex.Unlock();
1468 for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
1469 it != specs_to_delete.end(); ++it) {
1470 delete static_cast<const OnCallSpec<F>*
>(*it);
1475 g_gmock_mutex.Lock();
1481 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1482 return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));
1485 MockSpec<F> With(Matcher<Args>... m) {
1486 return MockSpec<F>(
this, ::std::make_tuple(std::move(m)...));
1490 template <
typename Function>
1491 friend class MockSpec;
1494 OnCallSpec<F>& AddNewOnCallSpec(
const char* file,
int line,
1495 const ArgumentMatcherTuple& m)
1496 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1497 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1498 OnCallSpec<F>*
const on_call_spec =
new OnCallSpec<F>(file, line, m);
1499 untyped_on_call_specs_.push_back(on_call_spec);
1500 return *on_call_spec;
1504 TypedExpectation<F>& AddNewExpectation(
const char* file,
int line,
1505 const std::string& source_text,
1506 const ArgumentMatcherTuple& m)
1507 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1508 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1509 TypedExpectation<F>*
const expectation =
1510 new TypedExpectation<F>(
this, file, line, source_text, m);
1511 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1514 untyped_expectations_.push_back(untyped_expectation);
1517 Sequence*
const implicit_sequence = g_gmock_implicit_sequence.get();
1518 if (implicit_sequence !=
nullptr) {
1519 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1522 return *expectation;
1526 template <
typename Func>
1527 friend class TypedExpectation;
1534 void DescribeDefaultActionTo(
const ArgumentTuple& args,
1535 ::std::ostream* os)
const {
1536 const OnCallSpec<F>*
const spec = FindOnCallSpec(args);
1538 if (spec ==
nullptr) {
1539 *os << (std::is_void<Result>::value ?
"returning directly.\n"
1540 :
"returning default value.\n");
1542 *os <<
"taking default action specified at:\n"
1543 << FormatFileLocation(spec->file(), spec->line()) <<
"\n";
1550 void UntypedDescribeUninterestingCall(
const void* untyped_args,
1551 ::std::ostream* os)
const override
1552 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1553 const ArgumentTuple& args =
1554 *
static_cast<const ArgumentTuple*
>(untyped_args);
1555 *os <<
"Uninteresting mock function call - ";
1556 DescribeDefaultActionTo(args, os);
1557 *os <<
" Function call: " << Name();
1558 UniversalPrint(args, os);
1577 const ExpectationBase* UntypedFindMatchingExpectation(
1578 const void* untyped_args,
const void** untyped_action,
bool* is_excessive,
1579 ::std::ostream* what, ::std::ostream* why)
override
1580 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1581 const ArgumentTuple& args =
1582 *
static_cast<const ArgumentTuple*
>(untyped_args);
1583 MutexLock l(&g_gmock_mutex);
1584 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1585 if (exp ==
nullptr) {
1586 this->FormatUnexpectedCallMessageLocked(args, what, why);
1593 *is_excessive = exp->IsSaturated();
1594 const Action<F>* action = exp->GetActionForArguments(
this, args, what, why);
1595 if (action !=
nullptr && action->IsDoDefault())
1597 *untyped_action = action;
1602 void UntypedPrintArgs(
const void* untyped_args,
1603 ::std::ostream* os)
const override {
1604 const ArgumentTuple& args =
1605 *
static_cast<const ArgumentTuple*
>(untyped_args);
1606 UniversalPrint(args, os);
1611 TypedExpectation<F>* FindMatchingExpectationLocked(
const ArgumentTuple& args)
1612 const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1613 g_gmock_mutex.AssertHeld();
1616 for (
typename UntypedExpectations::const_reverse_iterator it =
1617 untyped_expectations_.rbegin();
1618 it != untyped_expectations_.rend(); ++it) {
1619 TypedExpectation<F>*
const exp =
1620 static_cast<TypedExpectation<F>*
>(it->get());
1621 if (exp->ShouldHandleArguments(args)) {
1629 void FormatUnexpectedCallMessageLocked(
const ArgumentTuple& args,
1631 ::std::ostream* why)
const
1632 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1633 g_gmock_mutex.AssertHeld();
1634 *os <<
"\nUnexpected mock function call - ";
1635 DescribeDefaultActionTo(args, os);
1636 PrintTriedExpectationsLocked(args, why);
1641 void PrintTriedExpectationsLocked(
const ArgumentTuple& args,
1642 ::std::ostream* why)
const
1643 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1644 g_gmock_mutex.AssertHeld();
1645 const size_t count = untyped_expectations_.size();
1646 *why <<
"Google Mock tried the following " << count <<
" "
1647 << (count == 1 ?
"expectation, but it didn't match"
1648 :
"expectations, but none matched")
1650 for (
size_t i = 0; i < count; i++) {
1651 TypedExpectation<F>*
const expectation =
1652 static_cast<TypedExpectation<F>*
>(untyped_expectations_[i].get());
1654 expectation->DescribeLocationTo(why);
1656 *why <<
"tried expectation #" << i <<
": ";
1658 *why << expectation->source_text() <<
"...\n";
1659 expectation->ExplainMatchResultTo(args, why);
1660 expectation->DescribeCallCountTo(why);
1667 R PerformAction(
const void* untyped_action, ArgumentTuple&& args,
1668 const std::string& call_description)
const {
1669 if (untyped_action ==
nullptr) {
1670 return PerformDefaultAction(std::move(args), call_description);
1675 const Action<F> action = *
static_cast<const Action<F>*
>(untyped_action);
1676 return action.Perform(std::move(args));
1681 template <
typename T>
1682 using can_print_result = internal::conjunction<
1684 internal::negation<std::is_void<T>>,
1687 std::is_move_constructible<T>>;
1690 template <
typename T = R,
1691 typename std::enable_if<can_print_result<T>::value,
int>::type = 0>
1692 R PerformActionAndPrintResult(
const void*
const untyped_action,
1693 ArgumentTuple&& args,
1694 const std::string& call_description,
1696 R result = PerformAction(untyped_action, std::move(args), call_description);
1698 PrintAsActionResult(result, os);
1699 return std::forward<R>(result);
1704 template <
typename T = R,
1705 typename std::enable_if<
1706 internal::negation<can_print_result<T>>::value,
int>::type = 0>
1707 R PerformActionAndPrintResult(
const void*
const untyped_action,
1708 ArgumentTuple&& args,
1709 const std::string& call_description,
1711 return PerformAction(untyped_action, std::move(args), call_description);
1717 R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
1722template <
typename R,
typename... Args>
1723R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
1724 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1727 if (untyped_expectations_.size() == 0) {
1735 const CallReaction reaction =
1736 Mock::GetReactionOnUninterestingCalls(MockObject());
1741 const bool need_to_report_uninteresting_call =
1744 reaction == kAllow ? LogIsVisible(kInfo) :
1748 ? LogIsVisible(kWarning)
1754 if (!need_to_report_uninteresting_call) {
1756 return this->PerformDefaultAction(
1757 std::move(args),
"Function call: " + std::string(Name()));
1761 ::std::stringstream ss;
1762 this->UntypedDescribeUninterestingCall(&args, &ss);
1769 const Cleanup report_uninteresting_call(
1770 [&] { ReportUninterestingCall(reaction, ss.str()); });
1772 return PerformActionAndPrintResult(
nullptr, std::move(args), ss.str(), ss);
1775 bool is_excessive =
false;
1776 ::std::stringstream ss;
1777 ::std::stringstream why;
1778 ::std::stringstream loc;
1779 const void* untyped_action =
nullptr;
1784 const ExpectationBase*
const untyped_expectation =
1785 this->UntypedFindMatchingExpectation(&args, &untyped_action,
1786 &is_excessive, &ss, &why);
1787 const bool found = untyped_expectation !=
nullptr;
1793 const bool need_to_report_call =
1794 !found || is_excessive || LogIsVisible(kInfo);
1795 if (!need_to_report_call) {
1797 return PerformAction(untyped_action, std::move(args),
"");
1800 ss <<
" Function call: " << Name();
1801 this->UntypedPrintArgs(&args, &ss);
1805 if (found && !is_excessive) {
1806 untyped_expectation->DescribeLocationTo(&loc);
1814 const Cleanup handle_failures([&] {
1815 ss <<
"\n" << why.str();
1819 Expect(
false,
nullptr, -1, ss.str());
1820 }
else if (is_excessive) {
1822 Expect(
false, untyped_expectation->file(), untyped_expectation->line(),
1827 Log(kInfo, loc.str() + ss.str(), 2);
1831 return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
1839template <
typename F>
1842template <
typename R,
typename... Args>
1843class MockFunction<R(Args...)> {
1845 MockFunction(
const MockFunction&) =
delete;
1846 MockFunction& operator=(
const MockFunction&) =
delete;
1848 std::function<R(Args...)> AsStdFunction() {
1849 return [
this](Args... args) -> R {
1850 return this->Call(std::forward<Args>(args)...);
1855 R Call(Args... args) {
1856 mock_.SetOwnerAndName(
this,
"Call");
1857 return mock_.Invoke(std::forward<Args>(args)...);
1860 MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1861 mock_.RegisterOwner(
this);
1862 return mock_.With(std::move(m)...);
1865 MockSpec<R(Args...)> gmock_Call(
const WithoutMatchers&, R (*)(Args...)) {
1866 return this->gmock_Call(::testing::A<Args>()...);
1870 MockFunction() =
default;
1871 ~MockFunction() =
default;
1874 FunctionMocker<R(Args...)> mock_;
1889template <
typename F,
typename =
void>
1892template <
typename R,
typename... Args>
1893struct SignatureOf<R(Args...)> {
1894 using type = R(Args...);
1897template <
template <
typename>
class C,
typename F>
1898struct SignatureOf<C<F>,
1899 typename std::enable_if<std::is_function<F>::value>::type>
1900 : SignatureOf<F> {};
1902template <
typename F>
1903using SignatureOfT =
typename SignatureOf<F>::type;
1967template <
typename F>
1968class MockFunction :
public internal::MockFunction<internal::SignatureOfT<F>> {
1969 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
1980using internal::MockSpec;
1997template <
typename T>
1998inline const T& Const(
const T& x) {
2003inline Expectation::Expectation(internal::ExpectationBase& exp)
2004 : expectation_base_(exp.GetHandle().expectation_base()) {}