107class ExpectationBase;
111class TypedExpectation;
114class ExpectationTester;
117template <
typename MockClass>
119template <
typename MockClass>
121template <
typename MockClass>
142 UntypedFunctionMockerBase();
143 virtual ~UntypedFunctionMockerBase();
148 bool VerifyAndClearExpectationsLocked()
152 virtual void ClearDefaultActionsLocked()
162 virtual void UntypedDescribeUninterestingCall(
const void* untyped_args,
163 ::std::ostream* os)
const
172 virtual const ExpectationBase* UntypedFindMatchingExpectation(
173 const void* untyped_args,
const void** untyped_action,
bool* is_excessive,
174 ::std::ostream* what, ::std::ostream* why)
178 virtual void UntypedPrintArgs(
const void* untyped_args,
179 ::std::ostream* os)
const = 0;
190 void SetOwnerAndName(
const void* mock_obj,
const char* name)
203 typedef std::vector<const void*> UntypedOnCallSpecs;
205 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
207 struct UninterestingCallCleanupHandler;
208 struct FailureCleanupHandler;
212 Expectation GetHandleOf(ExpectationBase* exp);
217 const void* mock_obj_;
224 UntypedOnCallSpecs untyped_on_call_specs_;
235 UntypedExpectations untyped_expectations_;
239class UntypedOnCallSpecBase {
242 UntypedOnCallSpecBase(
const char* a_file,
int a_line)
243 : file_(a_file), line_(a_line), last_clause_(kNone) {}
246 const char* file()
const {
return file_; }
247 int line()
const {
return line_; }
260 void AssertSpecProperty(
bool property,
261 const std::string& failure_message)
const {
262 Assert(property, file_, line_, failure_message);
266 void ExpectSpecProperty(
bool property,
267 const std::string& failure_message)
const {
268 Expect(property, file_, line_, failure_message);
281class OnCallSpec :
public UntypedOnCallSpecBase {
283 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
284 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
288 OnCallSpec(
const char* a_file,
int a_line,
289 const ArgumentMatcherTuple& matchers)
290 : UntypedOnCallSpecBase(a_file, a_line),
295 extra_matcher_(A<const ArgumentTuple&>()) {}
298 OnCallSpec& With(
const Matcher<const ArgumentTuple&>& m) {
300 ExpectSpecProperty(last_clause_ < kWith,
301 ".With() cannot appear "
302 "more than once in an ON_CALL().");
303 last_clause_ = kWith;
310 OnCallSpec& WillByDefault(
const Action<F>& action) {
311 ExpectSpecProperty(last_clause_ < kWillByDefault,
312 ".WillByDefault() must appear "
313 "exactly once in an ON_CALL().");
314 last_clause_ = kWillByDefault;
316 ExpectSpecProperty(!action.IsDoDefault(),
317 "DoDefault() cannot be used in ON_CALL().");
323 bool Matches(
const ArgumentTuple& args)
const {
324 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
328 const Action<F>& GetAction()
const {
329 AssertSpecProperty(last_clause_ == kWillByDefault,
330 ".WillByDefault() must appear exactly "
331 "once in an ON_CALL().");
349 ArgumentMatcherTuple matchers_;
350 Matcher<const ArgumentTuple&> extra_matcher_;
370 static void AllowLeak(
const void* mock_obj)
376 static bool VerifyAndClearExpectations(
void* mock_obj)
382 static bool VerifyAndClear(
void* mock_obj)
386 static bool IsNaggy(
void* mock_obj)
389 static bool IsNice(
void* mock_obj)
392 static bool IsStrict(
void* mock_obj)
396 friend class internal::UntypedFunctionMockerBase;
400 template <
typename F>
401 friend class internal::FunctionMocker;
403 template <
typename MockClass>
404 friend class internal::NiceMockImpl;
405 template <
typename MockClass>
406 friend class internal::NaggyMockImpl;
407 template <
typename MockClass>
408 friend class internal::StrictMockImpl;
412 static void AllowUninterestingCalls(uintptr_t mock_obj)
417 static void WarnUninterestingCalls(uintptr_t mock_obj)
422 static void FailUninterestingCalls(uintptr_t mock_obj)
427 static void UnregisterCallReaction(uintptr_t mock_obj)
432 static internal::CallReaction GetReactionOnUninterestingCalls(
438 static bool VerifyAndClearExpectationsLocked(
void* mock_obj)
442 static void ClearDefaultActionsLocked(
void* mock_obj)
446 static void Register(
const void* mock_obj,
447 internal::UntypedFunctionMockerBase* mocker)
453 static void RegisterUseByOnCallOrExpectCall(
const void* mock_obj,
454 const char* file,
int line)
461 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
485 Expectation(Expectation&&) =
default;
486 Expectation(
const Expectation&) =
default;
487 Expectation& operator=(Expectation&&) =
default;
488 Expectation& operator=(
const Expectation&) =
default;
500 Expectation(internal::ExpectationBase& exp);
507 bool operator==(
const Expectation& rhs)
const {
508 return expectation_base_ == rhs.expectation_base_;
511 bool operator!=(
const Expectation& rhs)
const {
return !(*
this == rhs); }
514 friend class ExpectationSet;
515 friend class Sequence;
516 friend class ::testing::internal::ExpectationBase;
517 friend class ::testing::internal::UntypedFunctionMockerBase;
519 template <
typename F>
520 friend class ::testing::internal::FunctionMocker;
522 template <
typename F>
523 friend class ::testing::internal::TypedExpectation;
528 bool operator()(
const Expectation& lhs,
const Expectation& rhs)
const {
529 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
533 typedef ::std::set<Expectation, Less> Set;
536 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
539 const std::shared_ptr<internal::ExpectationBase>& expectation_base()
const {
540 return expectation_base_;
544 std::shared_ptr<internal::ExpectationBase> expectation_base_;
560class ExpectationSet {
563 typedef Expectation::Set::const_iterator const_iterator;
566 typedef Expectation::Set::value_type value_type;
569 ExpectationSet() =
default;
574 ExpectationSet(internal::ExpectationBase& exp) {
575 *
this += Expectation(exp);
581 ExpectationSet(
const Expectation& e) {
590 bool operator==(
const ExpectationSet& rhs)
const {
591 return expectations_ == rhs.expectations_;
594 bool operator!=(
const ExpectationSet& rhs)
const {
return !(*
this == rhs); }
598 ExpectationSet& operator+=(
const Expectation& e) {
599 expectations_.insert(e);
603 int size()
const {
return static_cast<int>(expectations_.size()); }
605 const_iterator begin()
const {
return expectations_.begin(); }
606 const_iterator end()
const {
return expectations_.end(); }
609 Expectation::Set expectations_;
618 Sequence() : last_expectation_(
new Expectation) {}
622 void AddExpectation(
const Expectation& expectation)
const;
626 std::shared_ptr<Expectation> last_expectation_;
659 bool sequence_created_;
661 InSequence(
const InSequence&) =
delete;
662 InSequence& operator=(
const InSequence&) =
delete;
669GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
688 ExpectationBase(
const char* file,
int line,
const std::string& source_text);
690 virtual ~ExpectationBase();
693 const char* file()
const {
return file_; }
694 int line()
const {
return line_; }
695 const char* source_text()
const {
return source_text_.c_str(); }
697 const Cardinality& cardinality()
const {
return cardinality_; }
700 void DescribeLocationTo(::std::ostream* os)
const {
701 *os << FormatFileLocation(file(), line()) <<
" ";
706 void DescribeCallCountTo(::std::ostream* os)
const
711 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
715 void UntypedDescription(std::string description) {
716 description_ = std::move(description);
720 friend class ::testing::Expectation;
721 friend class UntypedFunctionMockerBase;
735 typedef std::vector<const void*> UntypedActions;
739 virtual Expectation GetHandle() = 0;
742 void AssertSpecProperty(
bool property,
743 const std::string& failure_message)
const {
744 Assert(property, file_, line_, failure_message);
748 void ExpectSpecProperty(
bool property,
749 const std::string& failure_message)
const {
750 Expect(property, file_, line_, failure_message);
755 void SpecifyCardinality(
const Cardinality& cardinality);
759 bool cardinality_specified()
const {
return cardinality_specified_; }
762 void set_cardinality(
const Cardinality& a_cardinality) {
763 cardinality_ = a_cardinality;
775 g_gmock_mutex.AssertHeld();
781 g_gmock_mutex.AssertHeld();
787 const std::string& GetDescription()
const {
return description_; }
791 g_gmock_mutex.AssertHeld();
792 return cardinality().IsSatisfiedByCallCount(call_count_);
797 g_gmock_mutex.AssertHeld();
798 return cardinality().IsSaturatedByCallCount(call_count_);
803 g_gmock_mutex.AssertHeld();
804 return cardinality().IsOverSaturatedByCallCount(call_count_);
809 bool AllPrerequisitesAreSatisfied()
const
813 void FindUnsatisfiedPrerequisites(ExpectationSet* result)
const
818 g_gmock_mutex.AssertHeld();
824 g_gmock_mutex.AssertHeld();
834 friend class ::testing::Sequence;
835 friend class ::testing::internal::ExpectationTester;
837 template <
typename Function>
838 friend class TypedExpectation;
841 void UntypedTimes(
const Cardinality& a_cardinality);
847 const std::string source_text_;
848 std::string description_;
850 bool cardinality_specified_;
851 Cardinality cardinality_;
858 ExpectationSet immediate_prerequisites_;
864 UntypedActions untyped_actions_;
865 bool extra_matcher_specified_;
866 bool repeated_action_specified_;
867 bool retires_on_saturation_;
869 mutable bool action_count_checked_;
870 mutable Mutex mutex_;
874class TypedExpectation;
877template <
typename R,
typename... Args>
878class TypedExpectation<R(Args...)> :
public ExpectationBase {
880 using F = R(Args...);
883 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
884 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
885 typedef typename Function<F>::Result Result;
887 TypedExpectation(FunctionMocker<F>* owner,
const char* a_file,
int a_line,
888 const std::string& a_source_text,
889 const ArgumentMatcherTuple& m)
890 : ExpectationBase(a_file, a_line, a_source_text),
896 extra_matcher_(A<const ArgumentTuple&>()),
897 repeated_action_(DoDefault()) {}
899 ~TypedExpectation()
override {
902 CheckActionCountIfNotDone();
903 for (UntypedActions::const_iterator it = untyped_actions_.begin();
904 it != untyped_actions_.end(); ++it) {
905 delete static_cast<const Action<F>*
>(*it);
910 TypedExpectation& With(
const Matcher<const ArgumentTuple&>& m) {
911 if (last_clause_ == kWith) {
912 ExpectSpecProperty(
false,
913 ".With() cannot appear "
914 "more than once in an EXPECT_CALL().");
916 ExpectSpecProperty(last_clause_ < kWith,
917 ".With() must be the first "
918 "clause in an EXPECT_CALL().");
920 last_clause_ = kWith;
923 extra_matcher_specified_ =
true;
929 TypedExpectation& Description(std::string name) {
930 ExpectationBase::UntypedDescription(std::move(name));
935 TypedExpectation& Times(
const Cardinality& a_cardinality) {
936 ExpectationBase::UntypedTimes(a_cardinality);
941 TypedExpectation& Times(
int n) {
return Times(Exactly(n)); }
944 TypedExpectation& InSequence(
const Sequence& s) {
945 ExpectSpecProperty(last_clause_ <= kInSequence,
946 ".InSequence() cannot appear after .After(),"
947 " .WillOnce(), .WillRepeatedly(), or "
948 ".RetiresOnSaturation().");
949 last_clause_ = kInSequence;
951 s.AddExpectation(GetHandle());
954 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2) {
955 return InSequence(s1).InSequence(s2);
957 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
958 const Sequence& s3) {
959 return InSequence(s1, s2).InSequence(s3);
961 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
962 const Sequence& s3,
const Sequence& s4) {
963 return InSequence(s1, s2, s3).InSequence(s4);
965 TypedExpectation& InSequence(
const Sequence& s1,
const Sequence& s2,
966 const Sequence& s3,
const Sequence& s4,
967 const Sequence& s5) {
968 return InSequence(s1, s2, s3, s4).InSequence(s5);
972 TypedExpectation& After(
const ExpectationSet& s) {
973 ExpectSpecProperty(last_clause_ <= kAfter,
974 ".After() cannot appear after .WillOnce(),"
975 " .WillRepeatedly(), or "
976 ".RetiresOnSaturation().");
977 last_clause_ = kAfter;
979 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
980 immediate_prerequisites_ += *it;
984 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2) {
985 return After(s1).After(s2);
987 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
988 const ExpectationSet& s3) {
989 return After(s1, s2).After(s3);
991 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
992 const ExpectationSet& s3,
const ExpectationSet& s4) {
993 return After(s1, s2, s3).After(s4);
995 TypedExpectation& After(
const ExpectationSet& s1,
const ExpectationSet& s2,
996 const ExpectationSet& s3,
const ExpectationSet& s4,
997 const ExpectationSet& s5) {
998 return After(s1, s2, s3, s4).After(s5);
1003 TypedExpectation& WillOnce(OnceAction<F> once_action) {
1007 return WillOnce(Action<F>(ActionAdaptor{
1008 std::make_shared<OnceAction<F>>(std::move(once_action)),
1017 template <
int&... ExplicitArgumentBarrier,
typename =
void>
1018 TypedExpectation& WillOnce(Action<F> action) {
1019 ExpectSpecProperty(last_clause_ <= kWillOnce,
1020 ".WillOnce() cannot appear after "
1021 ".WillRepeatedly() or .RetiresOnSaturation().");
1022 last_clause_ = kWillOnce;
1024 untyped_actions_.push_back(
new Action<F>(std::move(action)));
1026 if (!cardinality_specified()) {
1027 set_cardinality(Exactly(
static_cast<int>(untyped_actions_.size())));
1033 TypedExpectation& WillRepeatedly(
const Action<F>& action) {
1034 if (last_clause_ == kWillRepeatedly) {
1035 ExpectSpecProperty(
false,
1036 ".WillRepeatedly() cannot appear "
1037 "more than once in an EXPECT_CALL().");
1039 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1040 ".WillRepeatedly() cannot appear "
1041 "after .RetiresOnSaturation().");
1043 last_clause_ = kWillRepeatedly;
1044 repeated_action_specified_ =
true;
1046 repeated_action_ = action;
1047 if (!cardinality_specified()) {
1048 set_cardinality(AtLeast(
static_cast<int>(untyped_actions_.size())));
1053 CheckActionCountIfNotDone();
1058 TypedExpectation& RetiresOnSaturation() {
1059 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1060 ".RetiresOnSaturation() cannot appear "
1062 last_clause_ = kRetiresOnSaturation;
1063 retires_on_saturation_ =
true;
1067 CheckActionCountIfNotDone();
1073 const ArgumentMatcherTuple& matchers()
const {
return matchers_; }
1076 const Matcher<const ArgumentTuple&>& extra_matcher()
const {
1077 return extra_matcher_;
1081 const Action<F>& repeated_action()
const {
return repeated_action_; }
1085 void MaybeDescribeExtraMatcherTo(::std::ostream* os)
override {
1086 if (extra_matcher_specified_) {
1087 *os <<
" Expected args: ";
1088 extra_matcher_.DescribeTo(os);
1094 template <
typename Function>
1095 friend class FunctionMocker;
1099 struct ActionAdaptor {
1100 std::shared_ptr<OnceAction<R(Args...)>> once_action;
1102 R operator()(Args&&... args)
const {
1103 return std::move(*once_action).Call(std::forward<Args>(args)...);
1109 Expectation GetHandle()
override {
return owner_->GetHandleOf(
this); }
1116 bool Matches(
const ArgumentTuple& args)
const
1118 g_gmock_mutex.AssertHeld();
1119 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1124 bool ShouldHandleArguments(
const ArgumentTuple& args)
const
1126 g_gmock_mutex.AssertHeld();
1132 CheckActionCountIfNotDone();
1133 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1138 void ExplainMatchResultTo(
const ArgumentTuple& args, ::std::ostream* os)
const
1140 g_gmock_mutex.AssertHeld();
1143 *os <<
" Expected: the expectation is active\n"
1144 <<
" Actual: it is retired\n";
1145 }
else if (!Matches(args)) {
1146 if (!TupleMatches(matchers_, args)) {
1147 ExplainMatchFailureTupleTo(matchers_, args, os);
1149 StringMatchResultListener listener;
1150 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1151 *os <<
" Expected args: ";
1152 extra_matcher_.DescribeTo(os);
1153 *os <<
"\n Actual: don't match";
1155 internal::PrintIfNotEmpty(listener.str(), os);
1158 }
else if (!AllPrerequisitesAreSatisfied()) {
1159 *os <<
" Expected: all pre-requisites are satisfied\n"
1160 <<
" Actual: the following immediate pre-requisites "
1161 <<
"are not satisfied:\n";
1162 ExpectationSet unsatisfied_prereqs;
1163 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1165 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1166 it != unsatisfied_prereqs.end(); ++it) {
1167 it->expectation_base()->DescribeLocationTo(os);
1168 *os <<
"pre-requisite #" <<
i++ <<
"\n";
1170 *os <<
" (end of pre-requisites)\n";
1176 *os <<
"The call matches the expectation.\n";
1181 const Action<F>& GetCurrentAction(
const FunctionMocker<F>* mocker,
1182 const ArgumentTuple& args)
const
1184 g_gmock_mutex.AssertHeld();
1185 const int count = call_count();
1186 Assert(
count >= 1, __FILE__, __LINE__,
1187 "call_count() is <= 0 when GetCurrentAction() is "
1188 "called - this should never happen.");
1190 const int action_count =
static_cast<int>(untyped_actions_.size());
1191 if (action_count > 0 && !repeated_action_specified_ &&
1192 count > action_count) {
1195 ::std::stringstream ss;
1196 DescribeLocationTo(&ss);
1197 ss <<
"Actions ran out in " << source_text() <<
"...\n"
1198 <<
"Called " <<
count <<
" times, but only " << action_count
1199 <<
" WillOnce()" << (action_count == 1 ?
" is" :
"s are")
1201 mocker->DescribeDefaultActionTo(args, &ss);
1202 Log(kWarning, ss.str(), 1);
1205 return count <= action_count
1206 ? *
static_cast<const Action<F>*
>(
1207 untyped_actions_[
static_cast<size_t>(
count - 1)])
1208 : repeated_action();
1218 const Action<F>* GetActionForArguments(
const FunctionMocker<F>* mocker,
1219 const ArgumentTuple& args,
1220 ::std::ostream* what,
1221 ::std::ostream* why)
1223 g_gmock_mutex.AssertHeld();
1224 const ::std::string& expectation_description = GetDescription();
1225 if (IsSaturated()) {
1227 IncrementCallCount();
1228 *what <<
"Mock function ";
1229 if (!expectation_description.empty()) {
1230 *what <<
"\"" << expectation_description <<
"\" ";
1232 *what <<
"called more times than expected - ";
1233 mocker->DescribeDefaultActionTo(args, what);
1234 DescribeCallCountTo(why);
1239 IncrementCallCount();
1240 RetireAllPreRequisites();
1242 if (retires_on_saturation_ && IsSaturated()) {
1247 *what <<
"Mock function ";
1248 if (!expectation_description.empty()) {
1249 *what <<
"\"" << expectation_description <<
"\" ";
1251 *what <<
"call matches " << source_text() <<
"...\n";
1252 return &(GetCurrentAction(mocker, args));
1257 FunctionMocker<F>*
const owner_;
1258 ArgumentMatcherTuple matchers_;
1259 Matcher<const ArgumentTuple&> extra_matcher_;
1260 Action<F> repeated_action_;
1262 TypedExpectation(
const TypedExpectation&) =
delete;
1263 TypedExpectation& operator=(
const TypedExpectation&) =
delete;
1278 const char* file,
int line,
1279 const std::string& message);
1281template <
typename F>
1284 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1286 typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1290 MockSpec(internal::FunctionMocker<F>* function_mocker,
1291 const ArgumentMatcherTuple& matchers)
1292 : function_mocker_(function_mocker), matchers_(matchers) {}
1296 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
const char* file,
1297 int line,
const char* obj,
1299 LogWithLocation(internal::kInfo, file, line,
1300 std::string(
"ON_CALL(") + obj +
", " + call +
") invoked");
1301 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1306 internal::TypedExpectation<F>& InternalExpectedAt(
const char* file,
int line,
1309 const std::string source_text(std::string(
"EXPECT_CALL(") + obj +
", " +
1311 LogWithLocation(internal::kInfo, file, line, source_text +
" invoked");
1312 return function_mocker_->AddNewExpectation(file, line, source_text,
1319 MockSpec<F>& operator()(
const internal::WithoutMatchers&,
void*
const) {
1324 template <
typename Function>
1325 friend class internal::FunctionMocker;
1328 internal::FunctionMocker<F>*
const function_mocker_;
1330 ArgumentMatcherTuple matchers_;
1342template <
typename T>
1343class ReferenceOrValueWrapper {
1346 explicit ReferenceOrValueWrapper(
T value) : value_(std::move(
value)) {}
1351 T Unwrap() {
return std::move(value_); }
1357 const T& Peek()
const {
return value_; }
1365template <
typename T>
1366class ReferenceOrValueWrapper<
T&> {
1370 typedef T& reference;
1371 explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}
1372 T& Unwrap() {
return *value_ptr_; }
1373 const T& Peek()
const {
return *value_ptr_; }
1380template <
typename T>
1381void PrintAsActionResult(
const T& result, std::ostream& os) {
1382 os <<
"\n Returns: ";
1384 UniversalPrinter<T>::Print(result, &os);
1389GTEST_API_ void ReportUninterestingCall(CallReaction reaction,
1390 const std::string& msg);
1393class Cleanup final {
1395 explicit Cleanup(std::function<
void()> f) : f_(std::move(f)) {}
1396 ~Cleanup() { f_(); }
1399 std::function<void()> f_;
1402struct UntypedFunctionMockerBase::UninterestingCallCleanupHandler {
1403 CallReaction reaction;
1404 std::stringstream& ss;
1406 ~UninterestingCallCleanupHandler() {
1407 ReportUninterestingCall(reaction, ss.str());
1411struct UntypedFunctionMockerBase::FailureCleanupHandler {
1412 std::stringstream& ss;
1413 std::stringstream& why;
1414 std::stringstream& loc;
1415 const ExpectationBase* untyped_expectation;
1419 ~FailureCleanupHandler() {
1420 ss <<
"\n" << why.str();
1424 Expect(
false,
nullptr, -1, ss.str());
1425 }
else if (is_excessive) {
1427 Expect(
false, untyped_expectation->file(), untyped_expectation->line(),
1432 Log(kInfo, loc.str() + ss.str(), 2);
1437template <
typename F>
1438class FunctionMocker;
1440template <
typename R,
typename... Args>
1441class FunctionMocker<R(Args...)> final :
public UntypedFunctionMockerBase {
1442 using F = R(Args...);
1446 using ArgumentTuple = std::tuple<Args...>;
1447 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1449 FunctionMocker() =
default;
1463 FunctionMocker(
const FunctionMocker&) =
delete;
1464 FunctionMocker& operator=(
const FunctionMocker&) =
delete;
1470 MutexLock l(&g_gmock_mutex);
1471 VerifyAndClearExpectationsLocked();
1472 Mock::UnregisterLocked(
this);
1473 ClearDefaultActionsLocked();
1479 const OnCallSpec<F>* FindOnCallSpec(
const ArgumentTuple& args)
const {
1480 for (UntypedOnCallSpecs::const_reverse_iterator it =
1481 untyped_on_call_specs_.rbegin();
1482 it != untyped_on_call_specs_.rend(); ++it) {
1483 const OnCallSpec<F>* spec =
static_cast<const OnCallSpec<F>*
>(*it);
1484 if (spec->Matches(args))
return spec;
1497 Result PerformDefaultAction(ArgumentTuple&& args,
1498 const std::string& call_description)
const {
1499 const OnCallSpec<F>*
const spec = this->FindOnCallSpec(args);
1500 if (spec !=
nullptr) {
1501 return spec->GetAction().Perform(std::move(args));
1503 const std::string message =
1505 "\n The mock function has no default action "
1506 "set, and its return type has no default value set.";
1507#if GTEST_HAS_EXCEPTIONS
1508 if (!DefaultValue<Result>::Exists()) {
1509 throw std::runtime_error(message);
1512 Assert(DefaultValue<Result>::Exists(),
"", -1, message);
1514 return DefaultValue<Result>::Get();
1519 void ClearDefaultActionsLocked()
override
1521 g_gmock_mutex.AssertHeld();
1530 UntypedOnCallSpecs specs_to_delete;
1531 untyped_on_call_specs_.swap(specs_to_delete);
1533 g_gmock_mutex.Unlock();
1534 for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();
1535 it != specs_to_delete.end(); ++it) {
1536 delete static_cast<const OnCallSpec<F>*
>(*it);
1541 g_gmock_mutex.Lock();
1548 return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));
1551 MockSpec<F> With(Matcher<Args>... m) {
1552 return MockSpec<F>(
this, ::std::make_tuple(std::move(m)...));
1556 template <
typename Function>
1557 friend class MockSpec;
1560 OnCallSpec<F>& AddNewOnCallSpec(
const char* file,
int line,
1561 const ArgumentMatcherTuple& m)
1563 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1564 OnCallSpec<F>*
const on_call_spec =
new OnCallSpec<F>(file, line, m);
1565 untyped_on_call_specs_.push_back(on_call_spec);
1566 return *on_call_spec;
1570 TypedExpectation<F>& AddNewExpectation(
const char* file,
int line,
1571 const std::string& source_text,
1572 const ArgumentMatcherTuple& m)
1574 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1575 TypedExpectation<F>*
const expectation =
1576 new TypedExpectation<F>(
this, file, line, source_text, m);
1577 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1580 untyped_expectations_.push_back(untyped_expectation);
1583 Sequence*
const implicit_sequence = g_gmock_implicit_sequence.get();
1584 if (implicit_sequence !=
nullptr) {
1585 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1588 return *expectation;
1592 template <
typename Func>
1593 friend class TypedExpectation;
1600 void DescribeDefaultActionTo(
const ArgumentTuple& args,
1601 ::std::ostream* os)
const {
1602 const OnCallSpec<F>*
const spec = FindOnCallSpec(args);
1604 if (spec ==
nullptr) {
1605 *os << (std::is_void<Result>::value ?
"returning directly.\n"
1606 :
"returning default value.\n");
1608 *os <<
"taking default action specified at:\n"
1609 << FormatFileLocation(spec->file(), spec->line()) <<
"\n";
1616 void UntypedDescribeUninterestingCall(
const void* untyped_args,
1617 ::std::ostream* os)
const override
1619 const ArgumentTuple& args =
1620 *
static_cast<const ArgumentTuple*
>(untyped_args);
1621 *os <<
"Uninteresting mock function call - ";
1622 DescribeDefaultActionTo(args, os);
1623 *os <<
" Function call: " << Name();
1624 UniversalPrint(args, os);
1643 const ExpectationBase* UntypedFindMatchingExpectation(
1644 const void* untyped_args,
const void** untyped_action,
bool* is_excessive,
1645 ::std::ostream* what, ::std::ostream* why)
override
1647 const ArgumentTuple& args =
1648 *
static_cast<const ArgumentTuple*
>(untyped_args);
1649 MutexLock l(&g_gmock_mutex);
1650 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1651 if (exp ==
nullptr) {
1652 this->FormatUnexpectedCallMessageLocked(args, what, why);
1659 *is_excessive = exp->IsSaturated();
1660 const Action<F>* action = exp->GetActionForArguments(
this, args, what, why);
1661 if (action !=
nullptr && action->IsDoDefault())
1663 *untyped_action = action;
1668 void UntypedPrintArgs(
const void* untyped_args,
1669 ::std::ostream* os)
const override {
1670 const ArgumentTuple& args =
1671 *
static_cast<const ArgumentTuple*
>(untyped_args);
1672 UniversalPrint(args, os);
1677 TypedExpectation<F>* FindMatchingExpectationLocked(
const ArgumentTuple& args)
1679 g_gmock_mutex.AssertHeld();
1682 for (
typename UntypedExpectations::const_reverse_iterator it =
1683 untyped_expectations_.rbegin();
1684 it != untyped_expectations_.rend(); ++it) {
1685 TypedExpectation<F>*
const exp =
1686 static_cast<TypedExpectation<F>*
>(it->get());
1687 if (exp->ShouldHandleArguments(args)) {
1695 void FormatUnexpectedCallMessageLocked(
const ArgumentTuple& args,
1697 ::std::ostream* why)
const
1699 g_gmock_mutex.AssertHeld();
1700 *os <<
"\nUnexpected mock function call - ";
1701 DescribeDefaultActionTo(args, os);
1702 PrintTriedExpectationsLocked(args, why);
1707 void PrintTriedExpectationsLocked(
const ArgumentTuple& args,
1708 ::std::ostream* why)
const
1710 g_gmock_mutex.AssertHeld();
1711 const size_t count = untyped_expectations_.size();
1712 *why <<
"Google Mock tried the following " <<
count <<
" "
1713 << (
count == 1 ?
"expectation, but it didn't match"
1714 :
"expectations, but none matched")
1716 for (
size_t i = 0;
i <
count;
i++) {
1717 TypedExpectation<F>*
const expectation =
1718 static_cast<TypedExpectation<F>*
>(untyped_expectations_[
i].get());
1720 expectation->DescribeLocationTo(why);
1722 *why <<
"tried expectation #" <<
i <<
": ";
1724 *why << expectation->source_text() <<
"...\n";
1725 expectation->ExplainMatchResultTo(args, why);
1726 expectation->DescribeCallCountTo(why);
1733 R PerformAction(
const void* untyped_action, ArgumentTuple&& args,
1734 const std::string& call_description)
const {
1735 if (untyped_action ==
nullptr) {
1736 return PerformDefaultAction(std::move(args), call_description);
1741 const Action<F> action = *
static_cast<const Action<F>*
>(untyped_action);
1742 return action.Perform(std::move(args));
1747 template <
typename T>
1748 using can_print_result = internal::conjunction<
1750 internal::negation<std::is_void<T>>,
1753 std::is_move_constructible<T>>;
1756 template <
typename T = R,
1757 typename std::enable_if<can_print_result<T>::value,
int>::type = 0>
1758 R PerformActionAndPrintResult(
const void*
const untyped_action,
1759 ArgumentTuple&& args,
1760 const std::string& call_description,
1762 R result = PerformAction(untyped_action, std::move(args), call_description);
1764 PrintAsActionResult(result, os);
1765 return std::forward<R>(result);
1770 template <
typename T = R,
1771 typename std::enable_if<
1772 internal::negation<can_print_result<T>>
::value,
int>::type = 0>
1773 R PerformActionAndPrintResult(
const void*
const untyped_action,
1774 ArgumentTuple&& args,
1775 const std::string& call_description,
1777 return PerformAction(untyped_action, std::move(args), call_description);
1788template <
typename R,
typename... Args>
1789R FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)
1793 if (untyped_expectations_.size() == 0) {
1801 const CallReaction reaction =
1802 Mock::GetReactionOnUninterestingCalls(MockObject());
1807 const bool need_to_report_uninteresting_call =
1810 reaction == kAllow ? LogIsVisible(kInfo) :
1814 ? LogIsVisible(kWarning)
1820 if (!need_to_report_uninteresting_call) {
1822 return this->PerformDefaultAction(
1823 std::move(args),
"Function call: " + std::string(Name()));
1827 ::std::stringstream ss;
1828 this->UntypedDescribeUninterestingCall(&args, &ss);
1841 const UninterestingCallCleanupHandler report_uninteresting_call = {
1845 return PerformActionAndPrintResult(
nullptr, std::move(args), ss.str(), ss);
1848 bool is_excessive =
false;
1849 ::std::stringstream ss;
1850 ::std::stringstream why;
1851 ::std::stringstream loc;
1852 const void* untyped_action =
nullptr;
1857 const ExpectationBase*
const untyped_expectation =
1858 this->UntypedFindMatchingExpectation(&args, &untyped_action,
1859 &is_excessive, &ss, &why);
1860 const bool found = untyped_expectation !=
nullptr;
1866 const bool need_to_report_call =
1867 !found || is_excessive || LogIsVisible(kInfo);
1868 if (!need_to_report_call) {
1870 return PerformAction(untyped_action, std::move(args),
"");
1873 ss <<
" Function call: " << Name();
1874 this->UntypedPrintArgs(&args, &ss);
1878 if (found && !is_excessive) {
1879 untyped_expectation->DescribeLocationTo(&loc);
1892 const FailureCleanupHandler handle_failures = {
1893 ss, why, loc, untyped_expectation, found, is_excessive
1896 return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),
1904template <
typename F>
1907template <
typename R,
typename... Args>
1908class MockFunction<R(Args...)> {
1910 MockFunction(
const MockFunction&) =
delete;
1911 MockFunction& operator=(
const MockFunction&) =
delete;
1913 std::function<R(Args...)> AsStdFunction() {
1914 return [
this](Args... args) -> R {
1915 return this->Call(std::forward<Args>(args)...);
1920 R Call(Args... args) {
1921 mock_.SetOwnerAndName(
this,
"Call");
1922 return mock_.Invoke(std::forward<Args>(args)...);
1925 MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1926 mock_.RegisterOwner(
this);
1927 return mock_.With(std::move(m)...);
1930 MockSpec<R(Args...)> gmock_Call(
const WithoutMatchers&, R (*)(Args...)) {
1931 return this->gmock_Call(::testing::A<Args>()...);
1935 MockFunction() =
default;
1936 ~MockFunction() =
default;
1939 FunctionMocker<R(Args...)> mock_;
1954template <
typename F,
typename =
void>
1957template <
typename R,
typename... Args>
1958struct SignatureOf<R(Args...)> {
1959 using type = R(Args...);
1962template <
template <
typename>
class C,
typename F>
1963struct SignatureOf<C<F>,
1964 typename
std::enable_if<std::is_function<F>::value>::type>
1965 : SignatureOf<F> {};
1967template <
typename F>
1968using SignatureOfT =
typename SignatureOf<F>::type;
2032template <
typename F>
2033class MockFunction :
public internal::MockFunction<internal::SignatureOfT<F>> {
2034 using Base = internal::MockFunction<internal::SignatureOfT<F>>;
2045using internal::MockSpec;
2062template <
typename T>
2063inline const T& Const(
const T&
x) {
2068inline Expectation::Expectation(internal::ExpectationBase& exp)
2069 : expectation_base_(exp.GetHandle().expectation_base()) {}