61 #ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ 62 #define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ 70 #include <type_traits> 73 #include "gmock/gmock-actions.h" 74 #include "gmock/gmock-cardinalities.h" 75 #include "gmock/gmock-matchers.h" 76 #include "gmock/internal/gmock-internal-utils.h" 77 #include "gmock/internal/gmock-port.h" 78 #include "gtest/gtest.h" 80 #if GTEST_HAS_EXCEPTIONS 84 GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
100 template <
typename F>
class FunctionMocker;
103 class ExpectationBase;
106 template <
typename F>
class TypedExpectation;
109 class ExpectationTester;
112 template <
typename MockClass>
114 template <
typename MockClass>
115 class StrictMockImpl;
116 template <
typename MockClass>
130 GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
133 class UntypedActionResultHolderBase;
138 class GTEST_API_ UntypedFunctionMockerBase {
140 UntypedFunctionMockerBase();
141 virtual ~UntypedFunctionMockerBase();
146 bool VerifyAndClearExpectationsLocked()
147 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
150 virtual
void ClearDefaultActionsLocked()
151 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
162 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
163 void* untyped_args, const
std::
string& call_description) const = 0;
168 virtual UntypedActionResultHolderBase* UntypedPerformAction(
169 const
void* untyped_action,
void* untyped_args) const = 0;
174 virtual
void UntypedDescribeUninterestingCall(
175 const
void* untyped_args,
176 ::
std::ostream* os) const
177 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
185 virtual const ExpectationBase* UntypedFindMatchingExpectation(
186 const
void* untyped_args,
187 const
void** untyped_action,
bool* is_excessive,
188 ::
std::ostream* what, ::
std::ostream* why)
189 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
192 virtual
void UntypedPrintArgs(const
void* untyped_args,
193 ::
std::ostream* os) const = 0;
199 void RegisterOwner(const
void* mock_obj)
200 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
205 void SetOwnerAndName(const
void* mock_obj, const
char* name)
206 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
211 const
void* MockObject() const
212 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
216 const
char* Name() const
217 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
223 UntypedActionResultHolderBase* UntypedInvokeWith(
void* untyped_args)
224 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
227 typedef
std::vector<const
void*> UntypedOnCallSpecs;
229 using UntypedExpectations =
std::vector<
std::shared_ptr<ExpectationBase>>;
233 Expectation GetHandleOf(ExpectationBase* exp);
238 const
void* mock_obj_;
245 UntypedOnCallSpecs untyped_on_call_specs_;
256 UntypedExpectations untyped_expectations_;
260 class UntypedOnCallSpecBase {
263 UntypedOnCallSpecBase(
const char* a_file,
int a_line)
264 : file_(a_file), line_(a_line), last_clause_(kNone) {}
267 const char* file()
const {
return file_; }
268 int line()
const {
return line_; }
281 void AssertSpecProperty(
bool property,
282 const std::string& failure_message)
const {
283 Assert(property, file_, line_, failure_message);
287 void ExpectSpecProperty(
bool property,
288 const std::string& failure_message)
const {
289 Expect(property, file_, line_, failure_message);
301 template <
typename F>
302 class OnCallSpec :
public UntypedOnCallSpecBase {
304 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
305 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
309 OnCallSpec(
const char* a_file,
int a_line,
310 const ArgumentMatcherTuple& matchers)
311 : UntypedOnCallSpecBase(a_file, a_line),
316 extra_matcher_(A<const ArgumentTuple&>()) {}
319 OnCallSpec& With(
const Matcher<const ArgumentTuple&>& m) {
321 ExpectSpecProperty(last_clause_ < kWith,
322 ".With() cannot appear " 323 "more than once in an ON_CALL().");
324 last_clause_ = kWith;
331 OnCallSpec& WillByDefault(
const Action<F>& action) {
332 ExpectSpecProperty(last_clause_ < kWillByDefault,
333 ".WillByDefault() must appear " 334 "exactly once in an ON_CALL().");
335 last_clause_ = kWillByDefault;
337 ExpectSpecProperty(!action.IsDoDefault(),
338 "DoDefault() cannot be used in ON_CALL().");
344 bool Matches(
const ArgumentTuple& args)
const {
345 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
349 const Action<F>& GetAction()
const {
350 AssertSpecProperty(last_clause_ == kWillByDefault,
351 ".WillByDefault() must appear exactly " 352 "once in an ON_CALL().");
370 ArgumentMatcherTuple matchers_;
371 Matcher<const ArgumentTuple&> extra_matcher_;
385 class GTEST_API_ Mock {
391 static void AllowLeak(
const void* mock_obj)
392 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
397 static bool VerifyAndClearExpectations(
void* mock_obj)
398 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
403 static bool VerifyAndClear(
void* mock_obj)
404 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
407 static bool IsNaggy(
void* mock_obj)
408 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
410 static bool IsNice(
void* mock_obj)
411 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
413 static bool IsStrict(
void* mock_obj)
414 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
417 friend class internal::UntypedFunctionMockerBase;
421 template <
typename F>
422 friend class internal::FunctionMocker;
424 template <
typename MockClass>
425 friend class internal::NiceMockImpl;
426 template <
typename MockClass>
427 friend class internal::NaggyMockImpl;
428 template <
typename MockClass>
429 friend class internal::StrictMockImpl;
433 static void AllowUninterestingCalls(
const void* mock_obj)
434 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
438 static void WarnUninterestingCalls(
const void* mock_obj)
439 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
443 static void FailUninterestingCalls(
const void* mock_obj)
444 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
448 static void UnregisterCallReaction(
const void* mock_obj)
449 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
453 static internal::CallReaction GetReactionOnUninterestingCalls(
454 const void* mock_obj)
455 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
460 static bool VerifyAndClearExpectationsLocked(
void* mock_obj)
461 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
464 static void ClearDefaultActionsLocked(
void* mock_obj)
465 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
468 static void Register(
469 const void* mock_obj,
470 internal::UntypedFunctionMockerBase* mocker)
471 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
476 static void RegisterUseByOnCallOrExpectCall(
477 const void* mock_obj,
const char* file,
int line)
478 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
484 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
485 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
504 class GTEST_API_ Expectation {
508 Expectation(Expectation&&) =
default;
509 Expectation(
const Expectation&) =
default;
510 Expectation& operator=(Expectation&&) =
default;
511 Expectation& operator=(
const Expectation&) =
default;
523 Expectation(internal::ExpectationBase& exp);
530 bool operator==(
const Expectation& rhs)
const {
531 return expectation_base_ == rhs.expectation_base_;
534 bool operator!=(
const Expectation& rhs)
const {
return !(*
this == rhs); }
537 friend class ExpectationSet;
538 friend class Sequence;
539 friend class ::testing::internal::ExpectationBase;
540 friend class ::testing::internal::UntypedFunctionMockerBase;
542 template <
typename F>
543 friend class ::testing::internal::FunctionMocker;
545 template <
typename F>
546 friend class ::testing::internal::TypedExpectation;
551 bool operator()(
const Expectation& lhs,
const Expectation& rhs)
const {
552 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
556 typedef ::std::set<Expectation, Less> Set;
559 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
562 const std::shared_ptr<internal::ExpectationBase>& expectation_base()
const {
563 return expectation_base_;
567 std::shared_ptr<internal::ExpectationBase> expectation_base_;
583 class ExpectationSet {
586 typedef Expectation::Set::const_iterator const_iterator;
589 typedef Expectation::Set::value_type value_type;
597 ExpectationSet(internal::ExpectationBase& exp) {
598 *
this += Expectation(exp);
604 ExpectationSet(
const Expectation& e) {
613 bool operator==(
const ExpectationSet& rhs)
const {
614 return expectations_ == rhs.expectations_;
617 bool operator!=(
const ExpectationSet& rhs)
const {
return !(*
this == rhs); }
621 ExpectationSet& operator+=(
const Expectation& e) {
622 expectations_.insert(e);
626 int size()
const {
return static_cast<int>(expectations_.size()); }
628 const_iterator begin()
const {
return expectations_.begin(); }
629 const_iterator end()
const {
return expectations_.end(); }
632 Expectation::Set expectations_;
639 class GTEST_API_ Sequence {
642 Sequence() : last_expectation_(new Expectation) {}
646 void AddExpectation(
const Expectation& expectation)
const;
650 std::shared_ptr<Expectation> last_expectation_;
677 class GTEST_API_ InSequence {
682 bool sequence_created_;
684 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence);
685 } GTEST_ATTRIBUTE_UNUSED_;
691 GTEST_API_
extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
707 class GTEST_API_ ExpectationBase {
710 ExpectationBase(
const char* file,
int line,
const std::string& source_text);
712 virtual ~ExpectationBase();
715 const char* file()
const {
return file_; }
716 int line()
const {
return line_; }
717 const char* source_text()
const {
return source_text_.c_str(); }
719 const Cardinality& cardinality()
const {
return cardinality_; }
722 void DescribeLocationTo(::std::ostream* os)
const {
723 *os << FormatFileLocation(file(), line()) <<
" ";
728 void DescribeCallCountTo(::std::ostream* os)
const 729 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
733 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
736 friend class ::testing::Expectation;
737 friend class UntypedFunctionMockerBase;
751 typedef std::vector<const void*> UntypedActions;
755 virtual Expectation GetHandle() = 0;
758 void AssertSpecProperty(
bool property,
759 const std::string& failure_message)
const {
760 Assert(property, file_, line_, failure_message);
764 void ExpectSpecProperty(
bool property,
765 const std::string& failure_message)
const {
766 Expect(property, file_, line_, failure_message);
771 void SpecifyCardinality(
const Cardinality& cardinality);
775 bool cardinality_specified()
const {
return cardinality_specified_; }
778 void set_cardinality(
const Cardinality& a_cardinality) {
779 cardinality_ = a_cardinality;
787 void RetireAllPreRequisites()
788 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
791 bool is_retired() const
792 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
793 g_gmock_mutex.AssertHeld();
799 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
800 g_gmock_mutex.AssertHeld();
805 bool IsSatisfied() const
806 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
807 g_gmock_mutex.AssertHeld();
808 return cardinality().IsSatisfiedByCallCount(call_count_);
812 bool IsSaturated() const
813 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
814 g_gmock_mutex.AssertHeld();
815 return cardinality().IsSaturatedByCallCount(call_count_);
819 bool IsOverSaturated() const
820 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
821 g_gmock_mutex.AssertHeld();
822 return cardinality().IsOverSaturatedByCallCount(call_count_);
827 bool AllPrerequisitesAreSatisfied() const
828 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
831 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
832 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
835 int call_count() const
836 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
837 g_gmock_mutex.AssertHeld();
842 void IncrementCallCount()
843 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
844 g_gmock_mutex.AssertHeld();
852 void CheckActionCountIfNotDone() const
853 GTEST_LOCK_EXCLUDED_(mutex_);
855 friend class ::testing::Sequence;
856 friend class ::testing::internal::ExpectationTester;
858 template <typename Function>
859 friend class TypedExpectation;
862 void UntypedTimes(const Cardinality& a_cardinality);
868 const
std::
string source_text_;
870 bool cardinality_specified_;
871 Cardinality cardinality_;
878 ExpectationSet immediate_prerequisites_;
884 UntypedActions untyped_actions_;
885 bool extra_matcher_specified_;
886 bool repeated_action_specified_;
887 bool retires_on_saturation_;
889 mutable
bool action_count_checked_;
890 mutable Mutex mutex_;
894 template <typename F>
895 class TypedExpectation : public ExpectationBase {
897 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
898 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
901 TypedExpectation(FunctionMocker<F>* owner,
const char* a_file,
int a_line,
902 const std::string& a_source_text,
903 const ArgumentMatcherTuple& m)
904 : ExpectationBase(a_file, a_line, a_source_text),
910 extra_matcher_(A<const ArgumentTuple&>()),
911 repeated_action_(DoDefault()) {}
913 ~TypedExpectation()
override {
916 CheckActionCountIfNotDone();
917 for (UntypedActions::const_iterator it = untyped_actions_.begin();
918 it != untyped_actions_.end(); ++it) {
919 delete static_cast<const Action<F>*
>(*it);
924 TypedExpectation& With(
const Matcher<const ArgumentTuple&>& m) {
925 if (last_clause_ == kWith) {
926 ExpectSpecProperty(
false,
927 ".With() cannot appear " 928 "more than once in an EXPECT_CALL().");
930 ExpectSpecProperty(last_clause_ < kWith,
931 ".With() must be the first " 932 "clause in an EXPECT_CALL().");
934 last_clause_ = kWith;
937 extra_matcher_specified_ =
true;
942 TypedExpectation& Times(
const Cardinality& a_cardinality) {
943 ExpectationBase::UntypedTimes(a_cardinality);
948 TypedExpectation& Times(
int n) {
949 return Times(Exactly(n));
953 TypedExpectation& InSequence(
const Sequence& s) {
954 ExpectSpecProperty(last_clause_ <= kInSequence,
955 ".InSequence() cannot appear after .After()," 956 " .WillOnce(), .WillRepeatedly(), or " 957 ".RetiresOnSaturation().");
958 last_clause_ = kInSequence;
960 s.AddExpectation(GetHandle());
963 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2) {
964 return InSequence(s1).InSequence(s2);
966 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
967 const Sequence& s3) {
968 return InSequence(s1, s2).InSequence(s3);
970 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
971 const Sequence& s3,
const Sequence& s4) {
972 return InSequence(s1, s2, s3).InSequence(s4);
974 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
975 const Sequence& s3,
const Sequence& s4,
976 const Sequence& s5) {
977 return InSequence(s1, s2, s3, s4).InSequence(s5);
981 TypedExpectation& After(
const ExpectationSet& s) {
982 ExpectSpecProperty(last_clause_ <= kAfter,
983 ".After() cannot appear after .WillOnce()," 984 " .WillRepeatedly(), or " 985 ".RetiresOnSaturation().");
986 last_clause_ = kAfter;
988 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
989 immediate_prerequisites_ += *it;
993 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2) {
994 return After(s1).After(s2);
996 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
997 const ExpectationSet& s3) {
998 return After(s1, s2).After(s3);
1000 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
1001 const ExpectationSet& s3,
const ExpectationSet& s4) {
1002 return After(s1, s2, s3).After(s4);
1004 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
1005 const ExpectationSet& s3,
const ExpectationSet& s4,
1006 const ExpectationSet& s5) {
1007 return After(s1, s2, s3, s4).After(s5);
1011 TypedExpectation& WillOnce(
const Action<F>& action) {
1012 ExpectSpecProperty(last_clause_ <= kWillOnce,
1013 ".WillOnce() cannot appear after " 1014 ".WillRepeatedly() or .RetiresOnSaturation().");
1015 last_clause_ = kWillOnce;
1017 untyped_actions_.push_back(
new Action<F>(action));
1018 if (!cardinality_specified()) {
1019 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1025 TypedExpectation& WillRepeatedly(
const Action<F>& action) {
1026 if (last_clause_ == kWillRepeatedly) {
1027 ExpectSpecProperty(
false,
1028 ".WillRepeatedly() cannot appear " 1029 "more than once in an EXPECT_CALL().");
1031 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1032 ".WillRepeatedly() cannot appear " 1033 "after .RetiresOnSaturation().");
1035 last_clause_ = kWillRepeatedly;
1036 repeated_action_specified_ =
true;
1038 repeated_action_ = action;
1039 if (!cardinality_specified()) {
1040 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1045 CheckActionCountIfNotDone();
1050 TypedExpectation& RetiresOnSaturation() {
1051 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1052 ".RetiresOnSaturation() cannot appear " 1054 last_clause_ = kRetiresOnSaturation;
1055 retires_on_saturation_ =
true;
1059 CheckActionCountIfNotDone();
1065 const ArgumentMatcherTuple& matchers()
const {
1070 const Matcher<const ArgumentTuple&>& extra_matcher()
const {
1071 return extra_matcher_;
1075 const Action<F>& repeated_action()
const {
return repeated_action_; }
1079 void MaybeDescribeExtraMatcherTo(::std::ostream* os)
override {
1080 if (extra_matcher_specified_) {
1081 *os <<
" Expected args: ";
1082 extra_matcher_.DescribeTo(os);
1088 template <
typename Function>
1089 friend class FunctionMocker;
1093 Expectation GetHandle()
override {
return owner_->GetHandleOf(
this); }
1100 bool Matches(
const ArgumentTuple& args)
const 1101 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1102 g_gmock_mutex.AssertHeld();
1103 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1108 bool ShouldHandleArguments(
const ArgumentTuple& args)
const 1109 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1110 g_gmock_mutex.AssertHeld();
1116 CheckActionCountIfNotDone();
1117 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1122 void ExplainMatchResultTo(
1123 const ArgumentTuple& args,
1124 ::std::ostream* os)
const 1125 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1126 g_gmock_mutex.AssertHeld();
1129 *os <<
" Expected: the expectation is active\n" 1130 <<
" Actual: it is retired\n";
1131 }
else if (!Matches(args)) {
1132 if (!TupleMatches(matchers_, args)) {
1133 ExplainMatchFailureTupleTo(matchers_, args, os);
1135 StringMatchResultListener listener;
1136 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1137 *os <<
" Expected args: ";
1138 extra_matcher_.DescribeTo(os);
1139 *os <<
"\n Actual: don't match";
1141 internal::PrintIfNotEmpty(listener.str(), os);
1144 }
else if (!AllPrerequisitesAreSatisfied()) {
1145 *os <<
" Expected: all pre-requisites are satisfied\n" 1146 <<
" Actual: the following immediate pre-requisites " 1147 <<
"are not satisfied:\n";
1148 ExpectationSet unsatisfied_prereqs;
1149 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1151 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1152 it != unsatisfied_prereqs.end(); ++it) {
1153 it->expectation_base()->DescribeLocationTo(os);
1154 *os <<
"pre-requisite #" << i++ <<
"\n";
1156 *os <<
" (end of pre-requisites)\n";
1162 *os <<
"The call matches the expectation.\n";
1167 const Action<F>& GetCurrentAction(
const FunctionMocker<F>* mocker,
1168 const ArgumentTuple& args)
const 1169 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1170 g_gmock_mutex.AssertHeld();
1171 const int count = call_count();
1172 Assert(count >= 1, __FILE__, __LINE__,
1173 "call_count() is <= 0 when GetCurrentAction() is " 1174 "called - this should never happen.");
1176 const int action_count =
static_cast<int>(untyped_actions_.size());
1177 if (action_count > 0 && !repeated_action_specified_ &&
1178 count > action_count) {
1181 ::std::stringstream ss;
1182 DescribeLocationTo(&ss);
1183 ss <<
"Actions ran out in " << source_text() <<
"...\n" 1184 <<
"Called " << count <<
" times, but only " 1185 << action_count <<
" WillOnce()" 1186 << (action_count == 1 ?
" is" :
"s are") <<
" specified - ";
1187 mocker->DescribeDefaultActionTo(args, &ss);
1188 Log(kWarning, ss.str(), 1);
1191 return count <= action_count
1192 ? *
static_cast<const Action<F>*
>(
1193 untyped_actions_[
static_cast<size_t>(count - 1)])
1194 : repeated_action();
1204 const Action<F>* GetActionForArguments(
const FunctionMocker<F>* mocker,
1205 const ArgumentTuple& args,
1206 ::std::ostream* what,
1207 ::std::ostream* why)
1208 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1209 g_gmock_mutex.AssertHeld();
1210 if (IsSaturated()) {
1212 IncrementCallCount();
1213 *what <<
"Mock function called more times than expected - ";
1214 mocker->DescribeDefaultActionTo(args, what);
1215 DescribeCallCountTo(why);
1220 IncrementCallCount();
1221 RetireAllPreRequisites();
1223 if (retires_on_saturation_ && IsSaturated()) {
1228 *what <<
"Mock function call matches " << source_text() <<
"...\n";
1229 return &(GetCurrentAction(mocker, args));
1234 FunctionMocker<F>*
const owner_;
1235 ArgumentMatcherTuple matchers_;
1236 Matcher<const ArgumentTuple&> extra_matcher_;
1237 Action<F> repeated_action_;
1239 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1253 GTEST_API_
void LogWithLocation(testing::internal::LogSeverity severity,
1254 const char* file,
int line,
1255 const std::string& message);
1257 template <
typename F>
1260 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1261 typedef typename internal::Function<F>::ArgumentMatcherTuple
1262 ArgumentMatcherTuple;
1266 MockSpec(internal::FunctionMocker<F>* function_mocker,
1267 const ArgumentMatcherTuple& matchers)
1268 : function_mocker_(function_mocker), matchers_(matchers) {}
1272 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1273 const char* file,
int line,
const char* obj,
const char* call) {
1274 LogWithLocation(internal::kInfo, file, line,
1275 std::string(
"ON_CALL(") + obj +
", " + call +
") invoked");
1276 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1281 internal::TypedExpectation<F>& InternalExpectedAt(
1282 const char* file,
int line,
const char* obj,
const char* call) {
1283 const std::string source_text(std::string(
"EXPECT_CALL(") + obj +
", " +
1285 LogWithLocation(internal::kInfo, file, line, source_text +
" invoked");
1286 return function_mocker_->AddNewExpectation(
1287 file, line, source_text, matchers_);
1293 MockSpec<F>& operator()(
const internal::WithoutMatchers&,
void*
const) {
1298 template <
typename Function>
1299 friend class internal::FunctionMocker;
1302 internal::FunctionMocker<F>*
const function_mocker_;
1304 ArgumentMatcherTuple matchers_;
1316 template <
typename T>
1317 class ReferenceOrValueWrapper {
1320 explicit ReferenceOrValueWrapper(T value)
1321 : value_(
std::move(value)) {
1327 T Unwrap() {
return std::move(value_); }
1333 const T& Peek()
const {
1343 template <
typename T>
1344 class ReferenceOrValueWrapper<T&> {
1348 typedef T& reference;
1349 explicit ReferenceOrValueWrapper(reference ref)
1350 : value_ptr_(&ref) {}
1351 T& Unwrap() {
return *value_ptr_; }
1352 const T& Peek()
const {
return *value_ptr_; }
1367 class UntypedActionResultHolderBase {
1369 virtual ~UntypedActionResultHolderBase() {}
1372 virtual void PrintAsActionResult(::std::ostream* os)
const = 0;
1376 template <
typename T>
1377 class ActionResultHolder :
public UntypedActionResultHolderBase {
1381 return result_.Unwrap();
1385 void PrintAsActionResult(::std::ostream* os)
const override {
1386 *os <<
"\n Returns: ";
1388 UniversalPrinter<T>::Print(result_.Peek(), os);
1393 template <
typename F>
1394 static ActionResultHolder* PerformDefaultAction(
1395 const FunctionMocker<F>* func_mocker,
1396 typename Function<F>::ArgumentTuple&& args,
1397 const std::string& call_description) {
1398 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1399 std::move(args), call_description)));
1404 template <
typename F>
1405 static ActionResultHolder* PerformAction(
1406 const Action<F>& action,
typename Function<F>::ArgumentTuple&& args) {
1407 return new ActionResultHolder(
1408 Wrapper(action.Perform(std::move(args))));
1412 typedef ReferenceOrValueWrapper<T> Wrapper;
1414 explicit ActionResultHolder(Wrapper result)
1415 : result_(
std::move(result)) {
1420 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1425 class ActionResultHolder<void> :
public UntypedActionResultHolderBase {
1429 void PrintAsActionResult(::std::ostream* )
const override {}
1433 template <
typename F>
1434 static ActionResultHolder* PerformDefaultAction(
1435 const FunctionMocker<F>* func_mocker,
1436 typename Function<F>::ArgumentTuple&& args,
1437 const std::string& call_description) {
1438 func_mocker->PerformDefaultAction(std::move(args), call_description);
1439 return new ActionResultHolder;
1444 template <
typename F>
1445 static ActionResultHolder* PerformAction(
1446 const Action<F>& action,
typename Function<F>::ArgumentTuple&& args) {
1447 action.Perform(std::move(args));
1448 return new ActionResultHolder;
1452 ActionResultHolder() {}
1453 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1456 template <
typename F>
1457 class FunctionMocker;
1459 template <
typename R,
typename... Args>
1460 class FunctionMocker<R(Args...)> final :
public UntypedFunctionMockerBase {
1461 using F = R(Args...);
1465 using ArgumentTuple = std::tuple<Args...>;
1466 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1482 FunctionMocker(
const FunctionMocker&) =
delete;
1483 FunctionMocker& operator=(
const FunctionMocker&) =
delete;
1488 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1489 MutexLock l(&g_gmock_mutex);
1490 VerifyAndClearExpectationsLocked();
1491 Mock::UnregisterLocked(
this);
1492 ClearDefaultActionsLocked();
1498 const OnCallSpec<F>* FindOnCallSpec(
1499 const ArgumentTuple& args)
const {
1500 for (UntypedOnCallSpecs::const_reverse_iterator it
1501 = untyped_on_call_specs_.rbegin();
1502 it != untyped_on_call_specs_.rend(); ++it) {
1503 const OnCallSpec<F>* spec =
static_cast<const OnCallSpec<F>*
>(*it);
1504 if (spec->Matches(args))
1518 Result PerformDefaultAction(ArgumentTuple&& args,
1519 const std::string& call_description)
const {
1520 const OnCallSpec<F>*
const spec =
1521 this->FindOnCallSpec(args);
1522 if (spec !=
nullptr) {
1523 return spec->GetAction().Perform(std::move(args));
1525 const std::string message =
1527 "\n The mock function has no default action " 1528 "set, and its return type has no default value set.";
1529 #if GTEST_HAS_EXCEPTIONS 1530 if (!DefaultValue<Result>::Exists()) {
1531 throw std::runtime_error(message);
1534 Assert(DefaultValue<Result>::Exists(),
"", -1, message);
1536 return DefaultValue<Result>::Get();
1544 UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1546 const std::string& call_description)
const override {
1547 ArgumentTuple* args =
static_cast<ArgumentTuple*
>(untyped_args);
1548 return ResultHolder::PerformDefaultAction(
this, std::move(*args),
1556 UntypedActionResultHolderBase* UntypedPerformAction(
1557 const void* untyped_action,
void* untyped_args)
const override {
1560 const Action<F> action = *
static_cast<const Action<F>*
>(untyped_action);
1561 ArgumentTuple* args =
static_cast<ArgumentTuple*
>(untyped_args);
1562 return ResultHolder::PerformAction(action, std::move(*args));
1567 void ClearDefaultActionsLocked() override
1568 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1569 g_gmock_mutex.AssertHeld();
1578 UntypedOnCallSpecs specs_to_delete;
1579 untyped_on_call_specs_.swap(specs_to_delete);
1581 g_gmock_mutex.Unlock();
1582 for (UntypedOnCallSpecs::const_iterator it =
1583 specs_to_delete.begin();
1584 it != specs_to_delete.end(); ++it) {
1585 delete static_cast<const OnCallSpec<F>*
>(*it);
1590 g_gmock_mutex.Lock();
1596 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1597 ArgumentTuple tuple(std::forward<Args>(args)...);
1598 std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
1599 this->UntypedInvokeWith(static_cast<void*>(&tuple))));
1600 return holder->Unwrap();
1603 MockSpec<F> With(Matcher<Args>... m) {
1604 return MockSpec<F>(
this, ::std::make_tuple(std::move(m)...));
1608 template <
typename Function>
1609 friend class MockSpec;
1611 typedef ActionResultHolder<Result> ResultHolder;
1614 OnCallSpec<F>& AddNewOnCallSpec(
1615 const char* file,
int line,
1616 const ArgumentMatcherTuple& m)
1617 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1618 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1619 OnCallSpec<F>*
const on_call_spec =
new OnCallSpec<F>(file, line, m);
1620 untyped_on_call_specs_.push_back(on_call_spec);
1621 return *on_call_spec;
1625 TypedExpectation<F>& AddNewExpectation(
const char* file,
int line,
1626 const std::string& source_text,
1627 const ArgumentMatcherTuple& m)
1628 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1629 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1630 TypedExpectation<F>*
const expectation =
1631 new TypedExpectation<F>(
this, file, line, source_text, m);
1632 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1635 untyped_expectations_.push_back(untyped_expectation);
1638 Sequence*
const implicit_sequence = g_gmock_implicit_sequence.get();
1639 if (implicit_sequence !=
nullptr) {
1640 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1643 return *expectation;
1647 template <
typename Func>
friend class TypedExpectation;
1654 void DescribeDefaultActionTo(
const ArgumentTuple& args,
1655 ::std::ostream* os)
const {
1656 const OnCallSpec<F>*
const spec = FindOnCallSpec(args);
1658 if (spec ==
nullptr) {
1659 *os << (std::is_void<Result>::value ?
"returning directly.\n" 1660 :
"returning default value.\n");
1662 *os <<
"taking default action specified at:\n" 1663 << FormatFileLocation(spec->file(), spec->line()) <<
"\n";
1670 void UntypedDescribeUninterestingCall(
const void* untyped_args,
1671 ::std::ostream* os)
const override 1672 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1673 const ArgumentTuple& args =
1674 *
static_cast<const ArgumentTuple*
>(untyped_args);
1675 *os <<
"Uninteresting mock function call - ";
1676 DescribeDefaultActionTo(args, os);
1677 *os <<
" Function call: " << Name();
1678 UniversalPrint(args, os);
1697 const ExpectationBase* UntypedFindMatchingExpectation(
1698 const void* untyped_args,
const void** untyped_action,
bool* is_excessive,
1699 ::std::ostream* what, ::std::ostream* why)
override 1700 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1701 const ArgumentTuple& args =
1702 *
static_cast<const ArgumentTuple*
>(untyped_args);
1703 MutexLock l(&g_gmock_mutex);
1704 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1705 if (exp ==
nullptr) {
1706 this->FormatUnexpectedCallMessageLocked(args, what, why);
1713 *is_excessive = exp->IsSaturated();
1714 const Action<F>* action = exp->GetActionForArguments(
this, args, what, why);
1715 if (action !=
nullptr && action->IsDoDefault())
1717 *untyped_action = action;
1722 void UntypedPrintArgs(
const void* untyped_args,
1723 ::std::ostream* os)
const override {
1724 const ArgumentTuple& args =
1725 *
static_cast<const ArgumentTuple*
>(untyped_args);
1726 UniversalPrint(args, os);
1731 TypedExpectation<F>* FindMatchingExpectationLocked(
1732 const ArgumentTuple& args)
const 1733 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1734 g_gmock_mutex.AssertHeld();
1737 for (
typename UntypedExpectations::const_reverse_iterator it =
1738 untyped_expectations_.rbegin();
1739 it != untyped_expectations_.rend(); ++it) {
1740 TypedExpectation<F>*
const exp =
1741 static_cast<TypedExpectation<F>*
>(it->get());
1742 if (exp->ShouldHandleArguments(args)) {
1750 void FormatUnexpectedCallMessageLocked(
1751 const ArgumentTuple& args,
1753 ::std::ostream* why)
const 1754 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1755 g_gmock_mutex.AssertHeld();
1756 *os <<
"\nUnexpected mock function call - ";
1757 DescribeDefaultActionTo(args, os);
1758 PrintTriedExpectationsLocked(args, why);
1763 void PrintTriedExpectationsLocked(
1764 const ArgumentTuple& args,
1765 ::std::ostream* why)
const 1766 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1767 g_gmock_mutex.AssertHeld();
1768 const size_t count = untyped_expectations_.size();
1769 *why <<
"Google Mock tried the following " << count <<
" " 1770 << (count == 1 ?
"expectation, but it didn't match" :
1771 "expectations, but none matched")
1773 for (
size_t i = 0; i < count; i++) {
1774 TypedExpectation<F>*
const expectation =
1775 static_cast<TypedExpectation<F>*
>(untyped_expectations_[i].get());
1777 expectation->DescribeLocationTo(why);
1779 *why <<
"tried expectation #" << i <<
": ";
1781 *why << expectation->source_text() <<
"...\n";
1782 expectation->ExplainMatchResultTo(args, why);
1783 expectation->DescribeCallCountTo(why);
1790 void ReportUninterestingCall(CallReaction reaction,
const std::string& msg);
1794 namespace internal {
1796 template <
typename F>
1799 template <
typename R,
typename... Args>
1800 class MockFunction<R(Args...)> {
1802 MockFunction(
const MockFunction&) =
delete;
1803 MockFunction& operator=(
const MockFunction&) =
delete;
1805 std::function<R(Args...)> AsStdFunction() {
1806 return [
this](Args... args) -> R {
1807 return this->Call(std::forward<Args>(args)...);
1812 R Call(Args... args) {
1813 mock_.SetOwnerAndName(
this,
"Call");
1814 return mock_.Invoke(std::forward<Args>(args)...);
1817 MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1818 mock_.RegisterOwner(
this);
1819 return mock_.With(std::move(m)...);
1822 MockSpec<R(Args...)> gmock_Call(
const WithoutMatchers&, R (*)(Args...)) {
1823 return this->gmock_Call(::testing::A<Args>()...);
1827 MockFunction() =
default;
1828 ~MockFunction() =
default;
1831 FunctionMocker<R(Args...)> mock_;
1846 template <
typename F,
typename =
void>
1849 template <
typename R,
typename... Args>
1850 struct SignatureOf<R(Args...)> {
1851 using type = R(Args...);
1854 template <
template <
typename>
class C,
typename F>
1855 struct SignatureOf<C<F>,
1856 typename
std::enable_if<std::is_function<F>::value>::type>
1857 : SignatureOf<F> {};
1859 template <
typename F>
1860 using SignatureOfT =
typename SignatureOf<F>::type;
1924 template <
typename F>
1925 class MockFunction :
public internal::MockFunction<internal::SignatureOfT<F>> {
1926 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
1937 using internal::MockSpec;
1954 template <
typename T>
1955 inline const T& Const(
const T& x) {
return x; }
1958 inline Expectation::Expectation(internal::ExpectationBase& exp)
1959 : expectation_base_(exp.GetHandle().expectation_base()) {}
1963 GTEST_DISABLE_MSC_WARNINGS_POP_()
2027 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \ 2028 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \ 2030 .Setter(__FILE__, __LINE__, #mock_expr, #call) 2032 #define ON_CALL(obj, call) \ 2033 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call) 2035 #define EXPECT_CALL(obj, call) \ 2036 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call) 2038 #endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ Definition: gmock-actions.h:154
Definition: gtest-internal.h:1322