1 // Copyright 2007, Google Inc.
2 // All rights reserved.
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
14 // * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Google Mock - a framework for writing C++ mock classes.
33 // This file implements the spec builder syntax (ON_CALL and
36 #include "gmock/gmock-spec-builders.h"
39 #include <iostream> // NOLINT
45 #include "gmock/gmock.h"
46 #include "gtest/gtest.h"
48 #if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC
49 # include <unistd.h> // NOLINT
52 // Silence C4800 (C4800: 'int *const ': forcing value
53 // to bool 'true' or 'false') for MSVC 15
56 # pragma warning(push)
57 # pragma warning(disable:4800)
64 // Protects the mock object registry (in class Mock), all function
65 // mockers, and all expectations.
66 GTEST_API_
GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex
);
68 // Logs a message including file and line number information.
69 GTEST_API_
void LogWithLocation(testing::internal::LogSeverity severity
,
70 const char* file
, int line
,
71 const std::string
& message
) {
72 ::std::ostringstream s
;
73 s
<< file
<< ":" << line
<< ": " << message
<< ::std::endl
;
74 Log(severity
, s
.str(), 0);
77 // Constructs an ExpectationBase object.
78 ExpectationBase::ExpectationBase(const char* a_file
, int a_line
,
79 const std::string
& a_source_text
)
82 source_text_(a_source_text
),
83 cardinality_specified_(false),
84 cardinality_(Exactly(1)),
87 extra_matcher_specified_(false),
88 repeated_action_specified_(false),
89 retires_on_saturation_(false),
91 action_count_checked_(false) {}
93 // Destructs an ExpectationBase object.
94 ExpectationBase::~ExpectationBase() {}
96 // Explicitly specifies the cardinality of this expectation. Used by
97 // the subclasses to implement the .Times() clause.
98 void ExpectationBase::SpecifyCardinality(const Cardinality
& a_cardinality
) {
99 cardinality_specified_
= true;
100 cardinality_
= a_cardinality
;
103 // Retires all pre-requisites of this expectation.
104 void ExpectationBase::RetireAllPreRequisites()
105 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
107 // We can take this short-cut as we never retire an expectation
108 // until we have retired all its pre-requisites.
112 ::std::vector
<ExpectationBase
*> expectations(1, this);
113 while (!expectations
.empty()) {
114 ExpectationBase
* exp
= expectations
.back();
115 expectations
.pop_back();
117 for (ExpectationSet::const_iterator it
=
118 exp
->immediate_prerequisites_
.begin();
119 it
!= exp
->immediate_prerequisites_
.end(); ++it
) {
120 ExpectationBase
* next
= it
->expectation_base().get();
121 if (!next
->is_retired()) {
123 expectations
.push_back(next
);
129 // Returns true if and only if all pre-requisites of this expectation
130 // have been satisfied.
131 bool ExpectationBase::AllPrerequisitesAreSatisfied() const
132 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
133 g_gmock_mutex
.AssertHeld();
134 ::std::vector
<const ExpectationBase
*> expectations(1, this);
135 while (!expectations
.empty()) {
136 const ExpectationBase
* exp
= expectations
.back();
137 expectations
.pop_back();
139 for (ExpectationSet::const_iterator it
=
140 exp
->immediate_prerequisites_
.begin();
141 it
!= exp
->immediate_prerequisites_
.end(); ++it
) {
142 const ExpectationBase
* next
= it
->expectation_base().get();
143 if (!next
->IsSatisfied()) return false;
144 expectations
.push_back(next
);
150 // Adds unsatisfied pre-requisites of this expectation to 'result'.
151 void ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet
* result
) const
152 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
153 g_gmock_mutex
.AssertHeld();
154 ::std::vector
<const ExpectationBase
*> expectations(1, this);
155 while (!expectations
.empty()) {
156 const ExpectationBase
* exp
= expectations
.back();
157 expectations
.pop_back();
159 for (ExpectationSet::const_iterator it
=
160 exp
->immediate_prerequisites_
.begin();
161 it
!= exp
->immediate_prerequisites_
.end(); ++it
) {
162 const ExpectationBase
* next
= it
->expectation_base().get();
164 if (next
->IsSatisfied()) {
165 // If *it is satisfied and has a call count of 0, some of its
166 // pre-requisites may not be satisfied yet.
167 if (next
->call_count_
== 0) {
168 expectations
.push_back(next
);
171 // Now that we know next is unsatisfied, we are not so interested
172 // in whether its pre-requisites are satisfied. Therefore we
173 // don't iterate into it here.
180 // Describes how many times a function call matching this
181 // expectation has occurred.
182 void ExpectationBase::DescribeCallCountTo(::std::ostream
* os
) const
183 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
184 g_gmock_mutex
.AssertHeld();
186 // Describes how many times the function is expected to be called.
187 *os
<< " Expected: to be ";
188 cardinality().DescribeTo(os
);
189 *os
<< "\n Actual: ";
190 Cardinality::DescribeActualCallCountTo(call_count(), os
);
192 // Describes the state of the expectation (e.g. is it satisfied?
194 *os
<< " - " << (IsOverSaturated() ? "over-saturated" :
195 IsSaturated() ? "saturated" :
196 IsSatisfied() ? "satisfied" : "unsatisfied")
198 << (is_retired() ? "retired" : "active");
201 // Checks the action count (i.e. the number of WillOnce() and
202 // WillRepeatedly() clauses) against the cardinality if this hasn't
203 // been done before. Prints a warning if there are too many or too
205 void ExpectationBase::CheckActionCountIfNotDone() const
206 GTEST_LOCK_EXCLUDED_(mutex_
) {
207 bool should_check
= false;
209 MutexLock
l(&mutex_
);
210 if (!action_count_checked_
) {
211 action_count_checked_
= true;
217 if (!cardinality_specified_
) {
218 // The cardinality was inferred - no need to check the action
223 // The cardinality was explicitly specified.
224 const int action_count
= static_cast<int>(untyped_actions_
.size());
225 const int upper_bound
= cardinality().ConservativeUpperBound();
226 const int lower_bound
= cardinality().ConservativeLowerBound();
227 bool too_many
; // True if there are too many actions, or false
228 // if there are too few.
229 if (action_count
> upper_bound
||
230 (action_count
== upper_bound
&& repeated_action_specified_
)) {
232 } else if (0 < action_count
&& action_count
< lower_bound
&&
233 !repeated_action_specified_
) {
239 ::std::stringstream ss
;
240 DescribeLocationTo(&ss
);
241 ss
<< "Too " << (too_many
? "many" : "few")
242 << " actions specified in " << source_text() << "...\n"
243 << "Expected to be ";
244 cardinality().DescribeTo(&ss
);
245 ss
<< ", but has " << (too_many
? "" : "only ")
246 << action_count
<< " WillOnce()"
247 << (action_count
== 1 ? "" : "s");
248 if (repeated_action_specified_
) {
249 ss
<< " and a WillRepeatedly()";
252 Log(kWarning
, ss
.str(), -1); // -1 means "don't print stack trace".
256 // Implements the .Times() clause.
257 void ExpectationBase::UntypedTimes(const Cardinality
& a_cardinality
) {
258 if (last_clause_
== kTimes
) {
259 ExpectSpecProperty(false,
260 ".Times() cannot appear "
261 "more than once in an EXPECT_CALL().");
263 ExpectSpecProperty(last_clause_
< kTimes
,
264 ".Times() cannot appear after "
265 ".InSequence(), .WillOnce(), .WillRepeatedly(), "
266 "or .RetiresOnSaturation().");
268 last_clause_
= kTimes
;
270 SpecifyCardinality(a_cardinality
);
273 // Points to the implicit sequence introduced by a living InSequence
274 // object (if any) in the current thread or NULL.
275 GTEST_API_ ThreadLocal
<Sequence
*> g_gmock_implicit_sequence
;
277 // Reports an uninteresting call (whose description is in msg) in the
278 // manner specified by 'reaction'.
279 void ReportUninterestingCall(CallReaction reaction
, const std::string
& msg
) {
280 // Include a stack trace only if --gmock_verbose=info is specified.
281 const int stack_frames_to_skip
=
282 GMOCK_FLAG(verbose
) == kInfoVerbosity
? 3 : -1;
285 Log(kInfo
, msg
, stack_frames_to_skip
);
290 "\nNOTE: You can safely ignore the above warning unless this "
291 "call should not happen. Do not suppress it by blindly adding "
292 "an EXPECT_CALL() if you don't mean to enforce the call. "
294 "https://github.com/google/googletest/blob/master/googlemock/"
296 "knowing-when-to-expect for details.\n",
297 stack_frames_to_skip
);
300 Expect(false, nullptr, -1, msg
);
304 UntypedFunctionMockerBase::UntypedFunctionMockerBase()
305 : mock_obj_(nullptr), name_("") {}
307 UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
309 // Sets the mock object this mock method belongs to, and registers
310 // this information in the global mock registry. Will be called
311 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
313 void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj
)
314 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
316 MutexLock
l(&g_gmock_mutex
);
317 mock_obj_
= mock_obj
;
319 Mock::Register(mock_obj
, this);
322 // Sets the mock object this mock method belongs to, and sets the name
323 // of the mock function. Will be called upon each invocation of this
325 void UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj
,
327 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
328 // We protect name_ under g_gmock_mutex in case this mock function
329 // is called from two threads concurrently.
330 MutexLock
l(&g_gmock_mutex
);
331 mock_obj_
= mock_obj
;
335 // Returns the name of the function being mocked. Must be called
336 // after RegisterOwner() or SetOwnerAndName() has been called.
337 const void* UntypedFunctionMockerBase::MockObject() const
338 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
339 const void* mock_obj
;
341 // We protect mock_obj_ under g_gmock_mutex in case this mock
342 // function is called from two threads concurrently.
343 MutexLock
l(&g_gmock_mutex
);
344 Assert(mock_obj_
!= nullptr, __FILE__
, __LINE__
,
345 "MockObject() must not be called before RegisterOwner() or "
346 "SetOwnerAndName() has been called.");
347 mock_obj
= mock_obj_
;
352 // Returns the name of this mock method. Must be called after
353 // SetOwnerAndName() has been called.
354 const char* UntypedFunctionMockerBase::Name() const
355 GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
358 // We protect name_ under g_gmock_mutex in case this mock
359 // function is called from two threads concurrently.
360 MutexLock
l(&g_gmock_mutex
);
361 Assert(name_
!= nullptr, __FILE__
, __LINE__
,
362 "Name() must not be called before SetOwnerAndName() has "
369 // Calculates the result of invoking this mock function with the given
370 // arguments, prints it, and returns it. The caller is responsible
371 // for deleting the result.
372 UntypedActionResultHolderBase
* UntypedFunctionMockerBase::UntypedInvokeWith(
373 void* const untyped_args
) GTEST_LOCK_EXCLUDED_(g_gmock_mutex
) {
374 // See the definition of untyped_expectations_ for why access to it
375 // is unprotected here.
376 if (untyped_expectations_
.size() == 0) {
377 // No expectation is set on this mock method - we have an
378 // uninteresting call.
380 // We must get Google Mock's reaction on uninteresting calls
381 // made on this mock object BEFORE performing the action,
382 // because the action may DELETE the mock object and make the
383 // following expression meaningless.
384 const CallReaction reaction
=
385 Mock::GetReactionOnUninterestingCalls(MockObject());
387 // True if and only if we need to print this call's arguments and return
388 // value. This definition must be kept in sync with
389 // the behavior of ReportUninterestingCall().
390 const bool need_to_report_uninteresting_call
=
391 // If the user allows this uninteresting call, we print it
392 // only when they want informational messages.
393 reaction
== kAllow
? LogIsVisible(kInfo
) :
394 // If the user wants this to be a warning, we print
395 // it only when they want to see warnings.
397 ? LogIsVisible(kWarning
)
399 // Otherwise, the user wants this to be an error, and we
400 // should always print detailed information in the error.
403 if (!need_to_report_uninteresting_call
) {
404 // Perform the action without printing the call information.
405 return this->UntypedPerformDefaultAction(
406 untyped_args
, "Function call: " + std::string(Name()));
409 // Warns about the uninteresting call.
410 ::std::stringstream ss
;
411 this->UntypedDescribeUninterestingCall(untyped_args
, &ss
);
413 // Calculates the function result.
414 UntypedActionResultHolderBase
* const result
=
415 this->UntypedPerformDefaultAction(untyped_args
, ss
.str());
417 // Prints the function result.
418 if (result
!= nullptr) result
->PrintAsActionResult(&ss
);
420 ReportUninterestingCall(reaction
, ss
.str());
424 bool is_excessive
= false;
425 ::std::stringstream ss
;
426 ::std::stringstream why
;
427 ::std::stringstream loc
;
428 const void* untyped_action
= nullptr;
430 // The UntypedFindMatchingExpectation() function acquires and
431 // releases g_gmock_mutex.
432 const ExpectationBase
* const untyped_expectation
=
433 this->UntypedFindMatchingExpectation(
434 untyped_args
, &untyped_action
, &is_excessive
,
436 const bool found
= untyped_expectation
!= nullptr;
438 // True if and only if we need to print the call's arguments
440 // This definition must be kept in sync with the uses of Expect()
441 // and Log() in this function.
442 const bool need_to_report_call
=
443 !found
|| is_excessive
|| LogIsVisible(kInfo
);
444 if (!need_to_report_call
) {
445 // Perform the action without printing the call information.
446 return untyped_action
== nullptr
447 ? this->UntypedPerformDefaultAction(untyped_args
, "")
448 : this->UntypedPerformAction(untyped_action
, untyped_args
);
451 ss
<< " Function call: " << Name();
452 this->UntypedPrintArgs(untyped_args
, &ss
);
454 // In case the action deletes a piece of the expectation, we
455 // generate the message beforehand.
456 if (found
&& !is_excessive
) {
457 untyped_expectation
->DescribeLocationTo(&loc
);
460 UntypedActionResultHolderBase
* const result
=
461 untyped_action
== nullptr
462 ? this->UntypedPerformDefaultAction(untyped_args
, ss
.str())
463 : this->UntypedPerformAction(untyped_action
, untyped_args
);
464 if (result
!= nullptr) result
->PrintAsActionResult(&ss
);
465 ss
<< "\n" << why
.str();
468 // No expectation matches this call - reports a failure.
469 Expect(false, nullptr, -1, ss
.str());
470 } else if (is_excessive
) {
471 // We had an upper-bound violation and the failure message is in ss.
472 Expect(false, untyped_expectation
->file(),
473 untyped_expectation
->line(), ss
.str());
475 // We had an expected call and the matching expectation is
477 Log(kInfo
, loc
.str() + ss
.str(), 2);
483 // Returns an Expectation object that references and co-owns exp,
484 // which must be an expectation on this mock function.
485 Expectation
UntypedFunctionMockerBase::GetHandleOf(ExpectationBase
* exp
) {
486 // See the definition of untyped_expectations_ for why access to it
487 // is unprotected here.
488 for (UntypedExpectations::const_iterator it
=
489 untyped_expectations_
.begin();
490 it
!= untyped_expectations_
.end(); ++it
) {
491 if (it
->get() == exp
) {
492 return Expectation(*it
);
496 Assert(false, __FILE__
, __LINE__
, "Cannot find expectation.");
497 return Expectation();
498 // The above statement is just to make the code compile, and will
499 // never be executed.
502 // Verifies that all expectations on this mock function have been
503 // satisfied. Reports one or more Google Test non-fatal failures
504 // and returns false if not.
505 bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
506 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex
) {
507 g_gmock_mutex
.AssertHeld();
508 bool expectations_met
= true;
509 for (UntypedExpectations::const_iterator it
=
510 untyped_expectations_
.begin();
511 it
!= untyped_expectations_
.end(); ++it
) {
512 ExpectationBase
* const untyped_expectation
= it
->get();
513 if (untyped_expectation
->IsOverSaturated()) {
514 // There was an upper-bound violation. Since the error was
515 // already reported when it occurred, there is no need to do
517 expectations_met
= false;
518 } else if (!untyped_expectation
->IsSatisfied()) {
519 expectations_met
= false;
520 ::std::stringstream ss
;
521 ss
<< "Actual function call count doesn't match "
522 << untyped_expectation
->source_text() << "...\n";
523 // No need to show the source file location of the expectation
524 // in the description, as the Expect() call that follows already
526 untyped_expectation
->MaybeDescribeExtraMatcherTo(&ss
);
527 untyped_expectation
->DescribeCallCountTo(&ss
);
528 Expect(false, untyped_expectation
->file(),
529 untyped_expectation
->line(), ss
.str());
533 // Deleting our expectations may trigger other mock objects to be deleted, for
534 // example if an action contains a reference counted smart pointer to that
535 // mock object, and that is the last reference. So if we delete our
536 // expectations within the context of the global mutex we may deadlock when
537 // this method is called again. Instead, make a copy of the set of
538 // expectations to delete, clear our set within the mutex, and then clear the
539 // copied set outside of it.
540 UntypedExpectations expectations_to_delete
;
541 untyped_expectations_
.swap(expectations_to_delete
);
543 g_gmock_mutex
.Unlock();
544 expectations_to_delete
.clear();
545 g_gmock_mutex
.Lock();
547 return expectations_met
;
550 CallReaction
intToCallReaction(int mock_behavior
) {
551 if (mock_behavior
>= kAllow
&& mock_behavior
<= kFail
) {
552 return static_cast<internal::CallReaction
>(mock_behavior
);
557 } // namespace internal
563 typedef std::set
<internal::UntypedFunctionMockerBase
*> FunctionMockers
;
565 // The current state of a mock object. Such information is needed for
566 // detecting leaked mock objects and explicitly verifying a mock's
568 struct MockObjectState
{
570 : first_used_file(nullptr), first_used_line(-1), leakable(false) {}
572 // Where in the source file an ON_CALL or EXPECT_CALL is first
573 // invoked on this mock object.
574 const char* first_used_file
;
576 ::std::string first_used_test_suite
;
577 ::std::string first_used_test
;
578 bool leakable
; // true if and only if it's OK to leak the object.
579 FunctionMockers function_mockers
; // All registered methods of the object.
582 // A global registry holding the state of all mock objects that are
583 // alive. A mock object is added to this registry the first time
584 // Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it. It
585 // is removed from the registry in the mock object's destructor.
586 class MockObjectRegistry
{
588 // Maps a mock object (identified by its address) to its state.
589 typedef std::map
<const void*, MockObjectState
> StateMap
;
591 // This destructor will be called when a program exits, after all
592 // tests in it have been run. By then, there should be no mock
593 // object alive. Therefore we report any living object as test
594 // failure, unless the user explicitly asked us to ignore it.
595 ~MockObjectRegistry() {
596 if (!GMOCK_FLAG(catch_leaked_mocks
))
599 int leaked_count
= 0;
600 for (StateMap::const_iterator it
= states_
.begin(); it
!= states_
.end();
602 if (it
->second
.leakable
) // The user said it's fine to leak this object.
605 // FIXME: Print the type of the leaked object.
606 // This can help the user identify the leaked object.
608 const MockObjectState
& state
= it
->second
;
609 std::cout
<< internal::FormatFileLocation(state
.first_used_file
,
610 state
.first_used_line
);
611 std::cout
<< " ERROR: this mock object";
612 if (state
.first_used_test
!= "") {
613 std::cout
<< " (used in test " << state
.first_used_test_suite
<< "."
614 << state
.first_used_test
<< ")";
616 std::cout
<< " should be deleted but never is. Its address is @"
620 if (leaked_count
> 0) {
621 std::cout
<< "\nERROR: " << leaked_count
<< " leaked mock "
622 << (leaked_count
== 1 ? "object" : "objects")
623 << " found at program exit. Expectations on a mock object is "
624 "verified when the object is destructed. Leaking a mock "
625 "means that its expectations aren't verified, which is "
626 "usually a test bug. If you really intend to leak a mock, "
627 "you can suppress this error using "
628 "testing::Mock::AllowLeak(mock_object), or you may use a "
629 "fake or stub instead of a mock.\n";
632 // RUN_ALL_TESTS() has already returned when this destructor is
633 // called. Therefore we cannot use the normal Google Test
634 // failure reporting mechanism.
635 _exit(1); // We cannot call exit() as it is not reentrant and
636 // may already have been called.
640 StateMap
& states() { return states_
; }
646 // Protected by g_gmock_mutex.
647 MockObjectRegistry g_mock_object_registry
;
649 // Maps a mock object to the reaction Google Mock should have when an
650 // uninteresting method is called. Protected by g_gmock_mutex.
651 std::map
<const void*, internal::CallReaction
> g_uninteresting_call_reaction
;
653 // Sets the reaction Google Mock should have when an uninteresting
654 // method of the given mock object is called.
655 void SetReactionOnUninterestingCalls(const void* mock_obj
,
656 internal::CallReaction reaction
)
657 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
658 internal::MutexLock
l(&internal::g_gmock_mutex
);
659 g_uninteresting_call_reaction
[mock_obj
] = reaction
;
664 // Tells Google Mock to allow uninteresting calls on the given mock
666 void Mock::AllowUninterestingCalls(const void* mock_obj
)
667 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
668 SetReactionOnUninterestingCalls(mock_obj
, internal::kAllow
);
671 // Tells Google Mock to warn the user about uninteresting calls on the
672 // given mock object.
673 void Mock::WarnUninterestingCalls(const void* mock_obj
)
674 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
675 SetReactionOnUninterestingCalls(mock_obj
, internal::kWarn
);
678 // Tells Google Mock to fail uninteresting calls on the given mock
680 void Mock::FailUninterestingCalls(const void* mock_obj
)
681 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
682 SetReactionOnUninterestingCalls(mock_obj
, internal::kFail
);
685 // Tells Google Mock the given mock object is being destroyed and its
686 // entry in the call-reaction table should be removed.
687 void Mock::UnregisterCallReaction(const void* mock_obj
)
688 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
689 internal::MutexLock
l(&internal::g_gmock_mutex
);
690 g_uninteresting_call_reaction
.erase(mock_obj
);
693 // Returns the reaction Google Mock will have on uninteresting calls
694 // made on the given mock object.
695 internal::CallReaction
Mock::GetReactionOnUninterestingCalls(
696 const void* mock_obj
)
697 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
698 internal::MutexLock
l(&internal::g_gmock_mutex
);
699 return (g_uninteresting_call_reaction
.count(mock_obj
) == 0) ?
700 internal::intToCallReaction(GMOCK_FLAG(default_mock_behavior
)) :
701 g_uninteresting_call_reaction
[mock_obj
];
704 // Tells Google Mock to ignore mock_obj when checking for leaked mock
706 void Mock::AllowLeak(const void* mock_obj
)
707 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
708 internal::MutexLock
l(&internal::g_gmock_mutex
);
709 g_mock_object_registry
.states()[mock_obj
].leakable
= true;
712 // Verifies and clears all expectations on the given mock object. If
713 // the expectations aren't satisfied, generates one or more Google
714 // Test non-fatal failures and returns false.
715 bool Mock::VerifyAndClearExpectations(void* mock_obj
)
716 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
717 internal::MutexLock
l(&internal::g_gmock_mutex
);
718 return VerifyAndClearExpectationsLocked(mock_obj
);
721 // Verifies all expectations on the given mock object and clears its
722 // default actions and expectations. Returns true if and only if the
723 // verification was successful.
724 bool Mock::VerifyAndClear(void* mock_obj
)
725 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
726 internal::MutexLock
l(&internal::g_gmock_mutex
);
727 ClearDefaultActionsLocked(mock_obj
);
728 return VerifyAndClearExpectationsLocked(mock_obj
);
731 // Verifies and clears all expectations on the given mock object. If
732 // the expectations aren't satisfied, generates one or more Google
733 // Test non-fatal failures and returns false.
734 bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj
)
735 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
) {
736 internal::g_gmock_mutex
.AssertHeld();
737 if (g_mock_object_registry
.states().count(mock_obj
) == 0) {
738 // No EXPECT_CALL() was set on the given mock object.
742 // Verifies and clears the expectations on each mock method in the
743 // given mock object.
744 bool expectations_met
= true;
745 FunctionMockers
& mockers
=
746 g_mock_object_registry
.states()[mock_obj
].function_mockers
;
747 for (FunctionMockers::const_iterator it
= mockers
.begin();
748 it
!= mockers
.end(); ++it
) {
749 if (!(*it
)->VerifyAndClearExpectationsLocked()) {
750 expectations_met
= false;
754 // We don't clear the content of mockers, as they may still be
755 // needed by ClearDefaultActionsLocked().
756 return expectations_met
;
759 bool Mock::IsNaggy(void* mock_obj
)
760 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
761 return Mock::GetReactionOnUninterestingCalls(mock_obj
) == internal::kWarn
;
763 bool Mock::IsNice(void* mock_obj
)
764 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
765 return Mock::GetReactionOnUninterestingCalls(mock_obj
) == internal::kAllow
;
767 bool Mock::IsStrict(void* mock_obj
)
768 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
769 return Mock::GetReactionOnUninterestingCalls(mock_obj
) == internal::kFail
;
772 // Registers a mock object and a mock method it owns.
773 void Mock::Register(const void* mock_obj
,
774 internal::UntypedFunctionMockerBase
* mocker
)
775 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
776 internal::MutexLock
l(&internal::g_gmock_mutex
);
777 g_mock_object_registry
.states()[mock_obj
].function_mockers
.insert(mocker
);
780 // Tells Google Mock where in the source code mock_obj is used in an
781 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
782 // information helps the user identify which object it is.
783 void Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj
,
784 const char* file
, int line
)
785 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex
) {
786 internal::MutexLock
l(&internal::g_gmock_mutex
);
787 MockObjectState
& state
= g_mock_object_registry
.states()[mock_obj
];
788 if (state
.first_used_file
== nullptr) {
789 state
.first_used_file
= file
;
790 state
.first_used_line
= line
;
791 const TestInfo
* const test_info
=
792 UnitTest::GetInstance()->current_test_info();
793 if (test_info
!= nullptr) {
794 state
.first_used_test_suite
= test_info
->test_suite_name();
795 state
.first_used_test
= test_info
->name();
800 // Unregisters a mock method; removes the owning mock object from the
801 // registry when the last mock method associated with it has been
802 // unregistered. This is called only in the destructor of
803 // FunctionMockerBase.
804 void Mock::UnregisterLocked(internal::UntypedFunctionMockerBase
* mocker
)
805 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
) {
806 internal::g_gmock_mutex
.AssertHeld();
807 for (MockObjectRegistry::StateMap::iterator it
=
808 g_mock_object_registry
.states().begin();
809 it
!= g_mock_object_registry
.states().end(); ++it
) {
810 FunctionMockers
& mockers
= it
->second
.function_mockers
;
811 if (mockers
.erase(mocker
) > 0) {
812 // mocker was in mockers and has been just removed.
813 if (mockers
.empty()) {
814 g_mock_object_registry
.states().erase(it
);
821 // Clears all ON_CALL()s set on the given mock object.
822 void Mock::ClearDefaultActionsLocked(void* mock_obj
)
823 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex
) {
824 internal::g_gmock_mutex
.AssertHeld();
826 if (g_mock_object_registry
.states().count(mock_obj
) == 0) {
827 // No ON_CALL() was set on the given mock object.
831 // Clears the default actions for each mock method in the given mock
833 FunctionMockers
& mockers
=
834 g_mock_object_registry
.states()[mock_obj
].function_mockers
;
835 for (FunctionMockers::const_iterator it
= mockers
.begin();
836 it
!= mockers
.end(); ++it
) {
837 (*it
)->ClearDefaultActionsLocked();
840 // We don't clear the content of mockers, as they may still be
841 // needed by VerifyAndClearExpectationsLocked().
844 Expectation::Expectation() {}
846 Expectation::Expectation(
847 const std::shared_ptr
<internal::ExpectationBase
>& an_expectation_base
)
848 : expectation_base_(an_expectation_base
) {}
850 Expectation::~Expectation() {}
852 // Adds an expectation to a sequence.
853 void Sequence::AddExpectation(const Expectation
& expectation
) const {
854 if (*last_expectation_
!= expectation
) {
855 if (last_expectation_
->expectation_base() != nullptr) {
856 expectation
.expectation_base()->immediate_prerequisites_
857 += *last_expectation_
;
859 *last_expectation_
= expectation
;
863 // Creates the implicit sequence if there isn't one.
864 InSequence::InSequence() {
865 if (internal::g_gmock_implicit_sequence
.get() == nullptr) {
866 internal::g_gmock_implicit_sequence
.set(new Sequence
);
867 sequence_created_
= true;
869 sequence_created_
= false;
873 // Deletes the implicit sequence if it was created by the constructor
875 InSequence::~InSequence() {
876 if (sequence_created_
) {
877 delete internal::g_gmock_implicit_sequence
.get();
878 internal::g_gmock_implicit_sequence
.set(nullptr);
882 } // namespace testing
886 # pragma warning(pop)