61 #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62 #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
70 #include <type_traits>
80 #if GTEST_HAS_EXCEPTIONS
100 template <
typename F>
class FunctionMocker;
103 class ExpectationBase;
106 template <
typename F>
class TypedExpectation;
109 class ExpectationTester;
125 class UntypedActionResultHolderBase;
132 UntypedFunctionMockerBase();
133 virtual ~UntypedFunctionMockerBase();
138 bool VerifyAndClearExpectationsLocked()
142 virtual void ClearDefaultActionsLocked()
154 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
155 void* untyped_args,
const std::string& call_description)
const = 0;
160 virtual UntypedActionResultHolderBase* UntypedPerformAction(
161 const void* untyped_action,
void* untyped_args)
const = 0;
166 virtual void UntypedDescribeUninterestingCall(
167 const void* untyped_args,
168 ::std::ostream* os)
const
177 virtual const ExpectationBase* UntypedFindMatchingExpectation(
178 const void* untyped_args,
179 const void** untyped_action,
bool* is_excessive,
180 ::std::ostream* what, ::std::ostream* why)
184 virtual void UntypedPrintArgs(
const void* untyped_args,
185 ::std::ostream* os)
const = 0;
191 void RegisterOwner(
const void* mock_obj)
197 void SetOwnerAndName(
const void* mock_obj,
const char* name)
203 const void* MockObject()
const
208 const char* Name()
const
215 UntypedActionResultHolderBase* UntypedInvokeWith(
void* untyped_args)
219 typedef std::vector<const void*> UntypedOnCallSpecs;
221 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
225 Expectation GetHandleOf(ExpectationBase*
exp);
230 const void* mock_obj_;
237 UntypedOnCallSpecs untyped_on_call_specs_;
248 UntypedExpectations untyped_expectations_;
252 class UntypedOnCallSpecBase {
255 UntypedOnCallSpecBase(
const char* a_file,
int a_line)
256 : file_(a_file), line_(a_line), last_clause_(kNone) {}
259 const char* file()
const {
return file_; }
260 int line()
const {
return line_; }
273 void AssertSpecProperty(
bool property,
274 const std::string& failure_message)
const {
275 Assert(property, file_, line_, failure_message);
279 void ExpectSpecProperty(
bool property,
280 const std::string& failure_message)
const {
281 Expect(property, file_, line_, failure_message);
293 template <
typename F>
294 class OnCallSpec :
public UntypedOnCallSpecBase {
296 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
297 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
301 OnCallSpec(
const char* a_file,
int a_line,
302 const ArgumentMatcherTuple& matchers)
303 : UntypedOnCallSpecBase(a_file, a_line),
311 OnCallSpec& With(
const Matcher<const ArgumentTuple&>& m) {
313 ExpectSpecProperty(last_clause_ < kWith,
314 ".With() cannot appear "
315 "more than once in an ON_CALL().");
316 last_clause_ = kWith;
323 OnCallSpec& WillByDefault(
const Action<F>& action) {
324 ExpectSpecProperty(last_clause_ < kWillByDefault,
325 ".WillByDefault() must appear "
326 "exactly once in an ON_CALL().");
327 last_clause_ = kWillByDefault;
329 ExpectSpecProperty(!action.IsDoDefault(),
330 "DoDefault() cannot be used in ON_CALL().");
336 bool Matches(
const ArgumentTuple& args)
const {
337 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
341 const Action<F>& GetAction()
const {
342 AssertSpecProperty(last_clause_ == kWillByDefault,
343 ".WillByDefault() must appear exactly "
344 "once in an ON_CALL().");
362 ArgumentMatcherTuple matchers_;
363 Matcher<const ArgumentTuple&> extra_matcher_;
383 static void AllowLeak(
const void* mock_obj)
389 static bool VerifyAndClearExpectations(
void* mock_obj)
395 static bool VerifyAndClear(
void* mock_obj)
399 static bool IsNaggy(
void* mock_obj)
402 static bool IsNice(
void* mock_obj)
405 static bool IsStrict(
void* mock_obj)
409 friend class internal::UntypedFunctionMockerBase;
413 template <
typename F>
414 friend class internal::FunctionMocker;
416 template <
typename M>
417 friend class NiceMock;
419 template <
typename M>
420 friend class NaggyMock;
422 template <
typename M>
423 friend class StrictMock;
427 static void AllowUninterestingCalls(
const void* mock_obj)
432 static void WarnUninterestingCalls(
const void* mock_obj)
437 static void FailUninterestingCalls(
const void* mock_obj)
442 static void UnregisterCallReaction(
const void* mock_obj)
447 static internal::CallReaction GetReactionOnUninterestingCalls(
448 const void* mock_obj)
454 static bool VerifyAndClearExpectationsLocked(
void* mock_obj)
458 static void ClearDefaultActionsLocked(
void* mock_obj)
462 static void Register(
463 const void* mock_obj,
464 internal::UntypedFunctionMockerBase* mocker)
470 static void RegisterUseByOnCallOrExpectCall(
471 const void* mock_obj,
const char* file,
int line)
478 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
502 Expectation(Expectation&&) =
default;
503 Expectation(
const Expectation&) =
default;
504 Expectation& operator=(Expectation&&) =
default;
505 Expectation& operator=(
const Expectation&) =
default;
517 Expectation(internal::ExpectationBase&
exp);
524 bool operator==(
const Expectation& rhs)
const {
525 return expectation_base_ == rhs.expectation_base_;
528 bool operator!=(
const Expectation& rhs)
const {
return !(*
this == rhs); }
531 friend class ExpectationSet;
532 friend class Sequence;
533 friend class ::testing::internal::ExpectationBase;
534 friend class ::testing::internal::UntypedFunctionMockerBase;
536 template <
typename F>
537 friend class ::testing::internal::FunctionMocker;
539 template <
typename F>
540 friend class ::testing::internal::TypedExpectation;
545 bool operator()(
const Expectation& lhs,
const Expectation& rhs)
const {
546 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
550 typedef ::std::set<Expectation, Less> Set;
553 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
556 const std::shared_ptr<internal::ExpectationBase>& expectation_base()
const {
557 return expectation_base_;
561 std::shared_ptr<internal::ExpectationBase> expectation_base_;
577 class ExpectationSet {
580 typedef Expectation::Set::const_iterator const_iterator;
583 typedef Expectation::Set::value_type value_type;
591 ExpectationSet(internal::ExpectationBase&
exp) {
592 *
this += Expectation(exp);
598 ExpectationSet(
const Expectation& e) {
607 bool operator==(
const ExpectationSet& rhs)
const {
608 return expectations_ == rhs.expectations_;
611 bool operator!=(
const ExpectationSet& rhs)
const {
return !(*
this == rhs); }
615 ExpectationSet& operator+=(
const Expectation& e) {
616 expectations_.insert(e);
620 int size()
const {
return static_cast<int>(expectations_.size()); }
622 const_iterator begin()
const {
return expectations_.begin(); }
623 const_iterator end()
const {
return expectations_.end(); }
626 Expectation::Set expectations_;
636 Sequence() : last_expectation_(
new Expectation) {}
640 void AddExpectation(
const Expectation& expectation)
const;
644 std::shared_ptr<Expectation> last_expectation_;
676 bool sequence_created_;
704 ExpectationBase(
const char* file,
int line,
const std::string& source_text);
706 virtual ~ExpectationBase();
709 const char* file()
const {
return file_; }
710 int line()
const {
return line_; }
711 const char* source_text()
const {
return source_text_.c_str(); }
713 const Cardinality& cardinality()
const {
return cardinality_; }
716 void DescribeLocationTo(::std::ostream* os)
const {
722 void DescribeCallCountTo(::std::ostream* os)
const
727 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
730 friend class ::testing::Expectation;
731 friend class UntypedFunctionMockerBase;
745 typedef std::vector<const void*> UntypedActions;
749 virtual Expectation GetHandle() = 0;
752 void AssertSpecProperty(
bool property,
753 const std::string& failure_message)
const {
754 Assert(property, file_, line_, failure_message);
758 void ExpectSpecProperty(
bool property,
759 const std::string& failure_message)
const {
760 Expect(property, file_, line_, failure_message);
765 void SpecifyCardinality(
const Cardinality& cardinality);
769 bool cardinality_specified()
const {
return cardinality_specified_; }
772 void set_cardinality(
const Cardinality& a_cardinality) {
773 cardinality_ = a_cardinality;
781 void RetireAllPreRequisites()
785 bool is_retired()
const
787 g_gmock_mutex.AssertHeld();
794 g_gmock_mutex.AssertHeld();
799 bool IsSatisfied()
const
801 g_gmock_mutex.AssertHeld();
802 return cardinality().IsSatisfiedByCallCount(call_count_);
806 bool IsSaturated()
const
808 g_gmock_mutex.AssertHeld();
809 return cardinality().IsSaturatedByCallCount(call_count_);
813 bool IsOverSaturated()
const
815 g_gmock_mutex.AssertHeld();
816 return cardinality().IsOverSaturatedByCallCount(call_count_);
821 bool AllPrerequisitesAreSatisfied()
const
825 void FindUnsatisfiedPrerequisites(ExpectationSet* result)
const
829 int call_count()
const
831 g_gmock_mutex.AssertHeld();
836 void IncrementCallCount()
838 g_gmock_mutex.AssertHeld();
846 void CheckActionCountIfNotDone()
const
849 friend class ::testing::Sequence;
850 friend class ::testing::internal::ExpectationTester;
852 template <
typename Function>
853 friend class TypedExpectation;
856 void UntypedTimes(
const Cardinality& a_cardinality);
862 const std::string source_text_;
864 bool cardinality_specified_;
865 Cardinality cardinality_;
872 ExpectationSet immediate_prerequisites_;
878 UntypedActions untyped_actions_;
879 bool extra_matcher_specified_;
880 bool repeated_action_specified_;
881 bool retires_on_saturation_;
883 mutable bool action_count_checked_;
884 mutable Mutex mutex_;
888 template <
typename F>
889 class TypedExpectation :
public ExpectationBase {
891 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
892 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
893 typedef typename Function<F>::Result Result;
895 TypedExpectation(FunctionMocker<F>* owner,
const char* a_file,
int a_line,
896 const std::string& a_source_text,
897 const ArgumentMatcherTuple& m)
898 : ExpectationBase(a_file, a_line, a_source_text),
907 ~TypedExpectation()
override {
910 CheckActionCountIfNotDone();
911 for (UntypedActions::const_iterator it = untyped_actions_.begin();
912 it != untyped_actions_.end(); ++it) {
913 delete static_cast<const Action<F>*
>(*it);
918 TypedExpectation& With(
const Matcher<const ArgumentTuple&>& m) {
919 if (last_clause_ == kWith) {
920 ExpectSpecProperty(
false,
921 ".With() cannot appear "
922 "more than once in an EXPECT_CALL().");
924 ExpectSpecProperty(last_clause_ < kWith,
925 ".With() must be the first "
926 "clause in an EXPECT_CALL().");
928 last_clause_ = kWith;
931 extra_matcher_specified_ =
true;
936 TypedExpectation& Times(
const Cardinality& a_cardinality) {
937 ExpectationBase::UntypedTimes(a_cardinality);
942 TypedExpectation& Times(
int n) {
947 TypedExpectation& InSequence(
const Sequence& s) {
948 ExpectSpecProperty(last_clause_ <= kInSequence,
949 ".InSequence() cannot appear after .After(),"
950 " .WillOnce(), .WillRepeatedly(), or "
951 ".RetiresOnSaturation().");
952 last_clause_ = kInSequence;
954 s.AddExpectation(GetHandle());
957 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2) {
958 return InSequence(s1).InSequence(s2);
960 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
961 const Sequence& s3) {
962 return InSequence(s1, s2).InSequence(s3);
964 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
965 const Sequence& s3,
const Sequence& s4) {
966 return InSequence(s1, s2, s3).InSequence(s4);
968 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
969 const Sequence& s3,
const Sequence& s4,
970 const Sequence& s5) {
971 return InSequence(s1, s2, s3, s4).InSequence(s5);
975 TypedExpectation& After(
const ExpectationSet& s) {
976 ExpectSpecProperty(last_clause_ <= kAfter,
977 ".After() cannot appear after .WillOnce(),"
978 " .WillRepeatedly(), or "
979 ".RetiresOnSaturation().");
980 last_clause_ = kAfter;
982 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
983 immediate_prerequisites_ += *it;
987 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2) {
988 return After(s1).After(s2);
990 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
991 const ExpectationSet& s3) {
992 return After(s1, s2).After(s3);
994 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
995 const ExpectationSet& s3,
const ExpectationSet& s4) {
996 return After(s1, s2, s3).After(s4);
998 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
999 const ExpectationSet& s3,
const ExpectationSet& s4,
1000 const ExpectationSet& s5) {
1001 return After(s1, s2, s3, s4).After(s5);
1005 TypedExpectation& WillOnce(
const Action<F>& action) {
1006 ExpectSpecProperty(last_clause_ <= kWillOnce,
1007 ".WillOnce() cannot appear after "
1008 ".WillRepeatedly() or .RetiresOnSaturation().");
1009 last_clause_ = kWillOnce;
1011 untyped_actions_.push_back(
new Action<F>(action));
1012 if (!cardinality_specified()) {
1013 set_cardinality(
Exactly(static_cast<int>(untyped_actions_.size())));
1019 TypedExpectation& WillRepeatedly(
const Action<F>& action) {
1020 if (last_clause_ == kWillRepeatedly) {
1021 ExpectSpecProperty(
false,
1022 ".WillRepeatedly() cannot appear "
1023 "more than once in an EXPECT_CALL().");
1025 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1026 ".WillRepeatedly() cannot appear "
1027 "after .RetiresOnSaturation().");
1029 last_clause_ = kWillRepeatedly;
1030 repeated_action_specified_ =
true;
1032 repeated_action_ = action;
1033 if (!cardinality_specified()) {
1034 set_cardinality(
AtLeast(static_cast<int>(untyped_actions_.size())));
1039 CheckActionCountIfNotDone();
1044 TypedExpectation& RetiresOnSaturation() {
1045 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1046 ".RetiresOnSaturation() cannot appear "
1048 last_clause_ = kRetiresOnSaturation;
1049 retires_on_saturation_ =
true;
1053 CheckActionCountIfNotDone();
1059 const ArgumentMatcherTuple& matchers()
const {
1064 const Matcher<const ArgumentTuple&>& extra_matcher()
const {
1065 return extra_matcher_;
1069 const Action<F>& repeated_action()
const {
return repeated_action_; }
1073 void MaybeDescribeExtraMatcherTo(::std::ostream* os)
override {
1074 if (extra_matcher_specified_) {
1075 *os <<
" Expected args: ";
1076 extra_matcher_.DescribeTo(os);
1082 template <
typename Function>
1083 friend class FunctionMocker;
1087 Expectation GetHandle()
override {
return owner_->GetHandleOf(
this); }
1094 bool Matches(
const ArgumentTuple& args)
const
1096 g_gmock_mutex.AssertHeld();
1097 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1102 bool ShouldHandleArguments(
const ArgumentTuple& args)
const
1104 g_gmock_mutex.AssertHeld();
1110 CheckActionCountIfNotDone();
1111 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1116 void ExplainMatchResultTo(
1117 const ArgumentTuple& args,
1118 ::std::ostream* os)
const
1120 g_gmock_mutex.AssertHeld();
1123 *os <<
" Expected: the expectation is active\n"
1124 <<
" Actual: it is retired\n";
1125 }
else if (!Matches(args)) {
1126 if (!TupleMatches(matchers_, args)) {
1127 ExplainMatchFailureTupleTo(matchers_, args, os);
1129 StringMatchResultListener listener;
1130 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1131 *os <<
" Expected args: ";
1132 extra_matcher_.DescribeTo(os);
1133 *os <<
"\n Actual: don't match";
1135 internal::PrintIfNotEmpty(listener.str(), os);
1138 }
else if (!AllPrerequisitesAreSatisfied()) {
1139 *os <<
" Expected: all pre-requisites are satisfied\n"
1140 <<
" Actual: the following immediate pre-requisites "
1141 <<
"are not satisfied:\n";
1142 ExpectationSet unsatisfied_prereqs;
1143 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1145 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1146 it != unsatisfied_prereqs.end(); ++it) {
1147 it->expectation_base()->DescribeLocationTo(os);
1148 *os <<
"pre-requisite #" << i++ <<
"\n";
1150 *os <<
" (end of pre-requisites)\n";
1156 *os <<
"The call matches the expectation.\n";
1161 const Action<F>& GetCurrentAction(
const FunctionMocker<F>* mocker,
1162 const ArgumentTuple& args)
const
1164 g_gmock_mutex.AssertHeld();
1165 const int count = call_count();
1166 Assert(count >= 1, __FILE__, __LINE__,
1167 "call_count() is <= 0 when GetCurrentAction() is "
1168 "called - this should never happen.");
1170 const int action_count =
static_cast<int>(untyped_actions_.size());
1171 if (action_count > 0 && !repeated_action_specified_ &&
1172 count > action_count) {
1175 ::std::stringstream ss;
1176 DescribeLocationTo(&ss);
1177 ss <<
"Actions ran out in " << source_text() <<
"...\n"
1178 <<
"Called " << count <<
" times, but only "
1179 << action_count <<
" WillOnce()"
1180 << (action_count == 1 ?
" is" :
"s are") <<
" specified - ";
1181 mocker->DescribeDefaultActionTo(args, &ss);
1185 return count <= action_count
1186 ? *
static_cast<const Action<F>*
>(
1187 untyped_actions_[
static_cast<size_t>(count - 1)])
1188 : repeated_action();
1198 const Action<F>* GetActionForArguments(
const FunctionMocker<F>* mocker,
1199 const ArgumentTuple& args,
1200 ::std::ostream* what,
1201 ::std::ostream* why)
1203 g_gmock_mutex.AssertHeld();
1204 if (IsSaturated()) {
1206 IncrementCallCount();
1207 *what <<
"Mock function called more times than expected - ";
1208 mocker->DescribeDefaultActionTo(args, what);
1209 DescribeCallCountTo(why);
1214 IncrementCallCount();
1215 RetireAllPreRequisites();
1217 if (retires_on_saturation_ && IsSaturated()) {
1222 *what <<
"Mock function call matches " << source_text() <<
"...\n";
1223 return &(GetCurrentAction(mocker, args));
1228 FunctionMocker<F>*
const owner_;
1229 ArgumentMatcherTuple matchers_;
1230 Matcher<const ArgumentTuple&> extra_matcher_;
1231 Action<F> repeated_action_;
1248 const char* file,
int line,
1249 const std::string& message);
1251 template <
typename F>
1254 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1255 typedef typename internal::Function<F>::ArgumentMatcherTuple
1256 ArgumentMatcherTuple;
1260 MockSpec(internal::FunctionMocker<F>* function_mocker,
1261 const ArgumentMatcherTuple& matchers)
1262 : function_mocker_(function_mocker), matchers_(matchers) {}
1266 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1267 const char* file,
int line,
const char* obj,
const char* call) {
1269 std::string(
"ON_CALL(") + obj +
", " + call +
") invoked");
1270 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1275 internal::TypedExpectation<F>& InternalExpectedAt(
1276 const char* file,
int line,
const char* obj,
const char* call) {
1277 const std::string source_text(std::string(
"EXPECT_CALL(") + obj +
", " +
1280 return function_mocker_->AddNewExpectation(
1281 file, line, source_text, matchers_);
1287 MockSpec<F>& operator()(
const internal::WithoutMatchers&,
void*
const) {
1292 template <
typename Function>
1293 friend class internal::FunctionMocker;
1296 internal::FunctionMocker<F>*
const function_mocker_;
1298 ArgumentMatcherTuple matchers_;
1310 template <
typename T>
1311 class ReferenceOrValueWrapper {
1314 explicit ReferenceOrValueWrapper(
T value)
1315 :
value_(std::move(value)) {
1321 T Unwrap() {
return std::move(
value_); }
1327 const T& Peek()
const {
1337 template <
typename T>
1338 class ReferenceOrValueWrapper<T&> {
1342 typedef T& reference;
1343 explicit ReferenceOrValueWrapper(reference ref)
1344 : value_ptr_(&ref) {}
1345 T& Unwrap() {
return *value_ptr_; }
1346 const T& Peek()
const {
return *value_ptr_; }
1361 class UntypedActionResultHolderBase {
1363 virtual ~UntypedActionResultHolderBase() {}
1366 virtual void PrintAsActionResult(::std::ostream* os)
const = 0;
1370 template <
typename T>
1371 class ActionResultHolder :
public UntypedActionResultHolderBase {
1375 return result_.Unwrap();
1379 void PrintAsActionResult(::std::ostream* os)
const override {
1380 *os <<
"\n Returns: ";
1387 template <
typename F>
1388 static ActionResultHolder* PerformDefaultAction(
1389 const FunctionMocker<F>* func_mocker,
1390 typename Function<F>::ArgumentTuple&& args,
1391 const std::string& call_description) {
1392 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1393 std::move(args), call_description)));
1398 template <
typename F>
1399 static ActionResultHolder* PerformAction(
1400 const Action<F>& action,
typename Function<F>::ArgumentTuple&& args) {
1401 return new ActionResultHolder(
1402 Wrapper(action.Perform(std::move(args))));
1406 typedef ReferenceOrValueWrapper<T> Wrapper;
1408 explicit ActionResultHolder(Wrapper result)
1409 : result_(std::move(result)) {
1419 class ActionResultHolder<void> :
public UntypedActionResultHolderBase {
1423 void PrintAsActionResult(::std::ostream* )
const override {}
1427 template <
typename F>
1428 static ActionResultHolder* PerformDefaultAction(
1429 const FunctionMocker<F>* func_mocker,
1430 typename Function<F>::ArgumentTuple&& args,
1431 const std::string& call_description) {
1432 func_mocker->PerformDefaultAction(std::move(args), call_description);
1433 return new ActionResultHolder;
1438 template <
typename F>
1439 static ActionResultHolder* PerformAction(
1440 const Action<F>& action,
typename Function<F>::ArgumentTuple&& args) {
1441 action.Perform(std::move(args));
1442 return new ActionResultHolder;
1446 ActionResultHolder() {}
1450 template <
typename F>
1451 class FunctionMocker;
1453 template <
typename R,
typename... Args>
1454 class FunctionMocker<R(Args...)> final :
public UntypedFunctionMockerBase {
1455 using F =
R(Args...);
1459 using ArgumentTuple = std::tuple<Args...>;
1460 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1476 FunctionMocker(
const FunctionMocker&) =
delete;
1477 FunctionMocker& operator=(
const FunctionMocker&) =
delete;
1484 VerifyAndClearExpectationsLocked();
1485 Mock::UnregisterLocked(
this);
1486 ClearDefaultActionsLocked();
1492 const OnCallSpec<F>* FindOnCallSpec(
1493 const ArgumentTuple& args)
const {
1494 for (UntypedOnCallSpecs::const_reverse_iterator it
1495 = untyped_on_call_specs_.rbegin();
1496 it != untyped_on_call_specs_.rend(); ++it) {
1497 const OnCallSpec<F>* spec =
static_cast<const OnCallSpec<F>*
>(*it);
1498 if (spec->Matches(args))
1512 Result PerformDefaultAction(ArgumentTuple&& args,
1513 const std::string& call_description)
const {
1514 const OnCallSpec<F>*
const spec =
1515 this->FindOnCallSpec(args);
1516 if (spec !=
nullptr) {
1517 return spec->GetAction().Perform(std::move(args));
1519 const std::string message =
1521 "\n The mock function has no default action "
1522 "set, and its return type has no default value set.";
1523 #if GTEST_HAS_EXCEPTIONS
1524 if (!DefaultValue<Result>::Exists()) {
1525 throw std::runtime_error(message);
1528 Assert(DefaultValue<Result>::Exists(),
"", -1, message);
1530 return DefaultValue<Result>::Get();
1538 UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1540 const std::string& call_description)
const override {
1541 ArgumentTuple* args =
static_cast<ArgumentTuple*
>(untyped_args);
1542 return ResultHolder::PerformDefaultAction(
this, std::move(*args),
1550 UntypedActionResultHolderBase* UntypedPerformAction(
1551 const void* untyped_action,
void* untyped_args)
const override {
1554 const Action<F> action = *
static_cast<const Action<F>*
>(untyped_action);
1555 ArgumentTuple* args =
static_cast<ArgumentTuple*
>(untyped_args);
1556 return ResultHolder::PerformAction(action, std::move(*args));
1561 void ClearDefaultActionsLocked()
override
1563 g_gmock_mutex.AssertHeld();
1572 UntypedOnCallSpecs specs_to_delete;
1573 untyped_on_call_specs_.swap(specs_to_delete);
1575 g_gmock_mutex.Unlock();
1576 for (UntypedOnCallSpecs::const_iterator it =
1577 specs_to_delete.begin();
1578 it != specs_to_delete.end(); ++it) {
1579 delete static_cast<const OnCallSpec<F>*
>(*it);
1584 g_gmock_mutex.Lock();
1591 ArgumentTuple tuple(std::forward<Args>(args)...);
1592 std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
1593 this->UntypedInvokeWith(static_cast<void*>(&tuple))));
1594 return holder->Unwrap();
1597 MockSpec<F> With(Matcher<Args>... m) {
1598 return MockSpec<F>(
this, ::std::make_tuple(std::move(m)...));
1602 template <
typename Function>
1603 friend class MockSpec;
1605 typedef ActionResultHolder<Result> ResultHolder;
1608 OnCallSpec<F>& AddNewOnCallSpec(
1609 const char* file,
int line,
1610 const ArgumentMatcherTuple& m)
1612 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1613 OnCallSpec<F>*
const on_call_spec =
new OnCallSpec<F>(file, line, m);
1614 untyped_on_call_specs_.push_back(on_call_spec);
1615 return *on_call_spec;
1619 TypedExpectation<F>& AddNewExpectation(
const char* file,
int line,
1620 const std::string& source_text,
1621 const ArgumentMatcherTuple& m)
1623 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1624 TypedExpectation<F>*
const expectation =
1625 new TypedExpectation<F>(
this, file, line, source_text, m);
1626 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1629 untyped_expectations_.push_back(untyped_expectation);
1633 if (implicit_sequence !=
nullptr) {
1634 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1637 return *expectation;
1641 template <
typename Func>
friend class TypedExpectation;
1648 void DescribeDefaultActionTo(
const ArgumentTuple& args,
1649 ::std::ostream* os)
const {
1650 const OnCallSpec<F>*
const spec = FindOnCallSpec(args);
1652 if (spec ==
nullptr) {
1654 :
"returning default value.\n");
1656 *os <<
"taking default action specified at:\n"
1664 void UntypedDescribeUninterestingCall(
const void* untyped_args,
1665 ::std::ostream* os)
const override
1667 const ArgumentTuple& args =
1668 *
static_cast<const ArgumentTuple*
>(untyped_args);
1669 *os <<
"Uninteresting mock function call - ";
1670 DescribeDefaultActionTo(args, os);
1671 *os <<
" Function call: " << Name();
1691 const ExpectationBase* UntypedFindMatchingExpectation(
1692 const void* untyped_args,
const void** untyped_action,
bool* is_excessive,
1693 ::std::ostream* what, ::std::ostream* why)
override
1695 const ArgumentTuple& args =
1696 *
static_cast<const ArgumentTuple*
>(untyped_args);
1698 TypedExpectation<F>*
exp = this->FindMatchingExpectationLocked(args);
1699 if (exp ==
nullptr) {
1700 this->FormatUnexpectedCallMessageLocked(args, what, why);
1707 *is_excessive = exp->IsSaturated();
1708 const Action<F>* action = exp->GetActionForArguments(
this, args, what, why);
1709 if (action !=
nullptr && action->IsDoDefault())
1711 *untyped_action = action;
1716 void UntypedPrintArgs(
const void* untyped_args,
1717 ::std::ostream* os)
const override {
1718 const ArgumentTuple& args =
1719 *
static_cast<const ArgumentTuple*
>(untyped_args);
1725 TypedExpectation<F>* FindMatchingExpectationLocked(
1726 const ArgumentTuple& args)
const
1728 g_gmock_mutex.AssertHeld();
1731 for (
typename UntypedExpectations::const_reverse_iterator it =
1732 untyped_expectations_.rbegin();
1733 it != untyped_expectations_.rend(); ++it) {
1734 TypedExpectation<F>*
const exp =
1735 static_cast<TypedExpectation<F>*
>(it->get());
1736 if (exp->ShouldHandleArguments(args)) {
1744 void FormatUnexpectedCallMessageLocked(
1745 const ArgumentTuple& args,
1747 ::std::ostream* why)
const
1749 g_gmock_mutex.AssertHeld();
1750 *os <<
"\nUnexpected mock function call - ";
1751 DescribeDefaultActionTo(args, os);
1752 PrintTriedExpectationsLocked(args, why);
1757 void PrintTriedExpectationsLocked(
1758 const ArgumentTuple& args,
1759 ::std::ostream* why)
const
1761 g_gmock_mutex.AssertHeld();
1762 const size_t count = untyped_expectations_.size();
1763 *why <<
"Google Mock tried the following " << count <<
" "
1764 << (count == 1 ?
"expectation, but it didn't match" :
1765 "expectations, but none matched")
1767 for (
size_t i = 0;
i <
count;
i++) {
1768 TypedExpectation<F>*
const expectation =
1769 static_cast<TypedExpectation<F>*
>(untyped_expectations_[
i].get());
1771 expectation->DescribeLocationTo(why);
1773 *why <<
"tried expectation #" <<
i <<
": ";
1775 *why << expectation->source_text() <<
"...\n";
1776 expectation->ExplainMatchResultTo(args, why);
1777 expectation->DescribeCallCountTo(why);
1788 namespace internal {
1790 template <
typename F>
1793 template <
typename R,
typename... Args>
1794 class MockFunction<R(Args...)> {
1796 MockFunction(
const MockFunction&) =
delete;
1797 MockFunction& operator=(
const MockFunction&) =
delete;
1799 std::function<
R(Args...)> AsStdFunction() {
1800 return [
this](Args... args) -> R {
1801 return this->Call(std::forward<Args>(args)...);
1806 R Call(Args... args) {
1807 mock_.SetOwnerAndName(
this,
"Call");
1808 return mock_.Invoke(std::forward<Args>(args)...);
1811 MockSpec<
R(Args...)> gmock_Call(Matcher<Args>... m) {
1812 mock_.RegisterOwner(
this);
1813 return mock_.With(std::move(m)...);
1816 MockSpec<
R(Args...)> gmock_Call(
const WithoutMatchers&, R (*)(Args...)) {
1817 return this->gmock_Call(::testing::A<Args>()...);
1821 MockFunction() =
default;
1822 ~MockFunction() =
default;
1825 FunctionMocker<
R(Args...)> mock_;
1840 template <
typename F>
1843 template <
typename R,
typename... Args>
1844 struct SignatureOf<R(Args...)> {
1845 using type =
R(Args...);
1848 template <
typename F>
1849 struct SignatureOf<std::function<F>> : SignatureOf<F> {};
1851 template <
typename F>
1852 using SignatureOfT =
typename SignatureOf<F>::type;
1916 template <
typename F>
1917 class MockFunction :
public internal::MockFunction<internal::SignatureOfT<F>> {
1918 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
1929 using internal::MockSpec;
1946 template <
typename T>
1947 inline const T& Const(
const T&
x) {
return x; }
1950 inline Expectation::Expectation(internal::ExpectationBase&
exp)
1951 : expectation_base_(exp.GetHandle().expectation_base()) {}
2019 #define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
2020 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
2022 .Setter(__FILE__, __LINE__, #mock_expr, #call)
2024 #define ON_CALL(obj, call) \
2025 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
2027 #define EXPECT_CALL(obj, call) \
2028 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
2030 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
GTEST_API_ Cardinality AtLeast(int n)
void ReportUninterestingCall(CallReaction reaction, const std::string &msg)
#define GTEST_ATTRIBUTE_UNUSED_
#define GTEST_DISABLE_MSC_WARNINGS_POP_()
GTEST_API_::std::string FormatFileLocation(const char *file, int line)
std::string Print(const T &value)
#define GTEST_LOCK_EXCLUDED_(locks)
GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char *file, int line, const std::string &message)
Sacado::Rad::ADvar< double > R
bool operator!=(const Allocator< T > &a_t, const Allocator< U > &a_u)
std::decay< FunctionImpl >::type Invoke(FunctionImpl &&function_impl)
#define GTEST_DECLARE_STATIC_MUTEX_(mutex)
#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)
void UniversalPrint(const T &value,::std::ostream *os)
GTEST_API_ Cardinality Exactly(int n)
internal::DoDefaultAction DoDefault()
bool operator==(const Handle< T > &h1, const Handle< T > &h2)
Compare two handles.
void Assert(bool condition, const char *file, int line, const std::string &msg)
#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)
#define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)
GTEST_API_ ThreadLocal< Sequence * > g_gmock_implicit_sequence
void Expect(bool condition, const char *file, int line, const std::string &msg)
GTEST_API_ void Log(LogSeverity severity, const std::string &message, int stack_frames_to_skip)