1// Copyright 2007, Google Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
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
13// distribution.
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.
17//
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.
29
30
31// Google Mock - a framework for writing C++ mock classes.
32//
33// This file implements the ON_CALL() and EXPECT_CALL() macros.
34//
35// A user can use the ON_CALL() macro to specify the default action of
36// a mock method. The syntax is:
37//
38// ON_CALL(mock_object, Method(argument-matchers))
39// .With(multi-argument-matcher)
40// .WillByDefault(action);
41//
42// where the .With() clause is optional.
43//
44// A user can use the EXPECT_CALL() macro to specify an expectation on
45// a mock method. The syntax is:
46//
47// EXPECT_CALL(mock_object, Method(argument-matchers))
48// .With(multi-argument-matchers)
49// .Times(cardinality)
50// .InSequence(sequences)
51// .After(expectations)
52// .WillOnce(action)
53// .WillRepeatedly(action)
54// .RetiresOnSaturation();
55//
56// where all clauses are optional, and .InSequence()/.After()/
57// .WillOnce() can appear any number of times.
58
59// GOOGLETEST_CM0002 DO NOT DELETE
60
61#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
63
64#include <map>
65#include <memory>
66#include <set>
67#include <sstream>
68#include <string>
69#include <utility>
70#include <vector>
71#include "gmock/gmock-actions.h"
72#include "gmock/gmock-cardinalities.h"
73#include "gmock/gmock-matchers.h"
74#include "gmock/internal/gmock-internal-utils.h"
75#include "gmock/internal/gmock-port.h"
76#include "gtest/gtest.h"
77
78#if GTEST_HAS_EXCEPTIONS
79# include <stdexcept> // NOLINT
80#endif
81
82GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
83/* class A needs to have dll-interface to be used by clients of class B */)
84
85namespace testing {
86
87// An abstract handle of an expectation.
88class Expectation;
89
90// A set of expectation handles.
91class ExpectationSet;
92
93// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
94// and MUST NOT BE USED IN USER CODE!!!
95namespace internal {
96
97// Implements a mock function.
98template <typename F> class FunctionMocker;
99
100// Base class for expectations.
101class ExpectationBase;
102
103// Implements an expectation.
104template <typename F> class TypedExpectation;
105
106// Helper class for testing the Expectation class template.
107class ExpectationTester;
108
109// Protects the mock object registry (in class Mock), all function
110// mockers, and all expectations.
111//
112// The reason we don't use more fine-grained protection is: when a
113// mock function Foo() is called, it needs to consult its expectations
114// to see which one should be picked. If another thread is allowed to
115// call a mock function (either Foo() or a different one) at the same
116// time, it could affect the "retired" attributes of Foo()'s
117// expectations when InSequence() is used, and thus affect which
118// expectation gets picked. Therefore, we sequence all mock function
119// calls to ensure the integrity of the mock objects' states.
120GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
121
122// Untyped base class for ActionResultHolder<R>.
123class UntypedActionResultHolderBase;
124
125// Abstract base class of FunctionMocker. This is the
126// type-agnostic part of the function mocker interface. Its pure
127// virtual methods are implemented by FunctionMocker.
128class GTEST_API_ UntypedFunctionMockerBase {
129 public:
130 UntypedFunctionMockerBase();
131 virtual ~UntypedFunctionMockerBase();
132
133 // Verifies that all expectations on this mock function have been
134 // satisfied. Reports one or more Google Test non-fatal failures
135 // and returns false if not.
136 bool VerifyAndClearExpectationsLocked()
137 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
138
139 // Clears the ON_CALL()s set on this mock function.
140 virtual void ClearDefaultActionsLocked()
141 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
142
143 // In all of the following Untyped* functions, it's the caller's
144 // responsibility to guarantee the correctness of the arguments'
145 // types.
146
147 // Performs the default action with the given arguments and returns
148 // the action's result. The call description string will be used in
149 // the error message to describe the call in the case the default
150 // action fails.
151 // L = *
152 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
153 void* untyped_args, const std::string& call_description) const = 0;
154
155 // Performs the given action with the given arguments and returns
156 // the action's result.
157 // L = *
158 virtual UntypedActionResultHolderBase* UntypedPerformAction(
159 const void* untyped_action, void* untyped_args) const = 0;
160
161 // Writes a message that the call is uninteresting (i.e. neither
162 // explicitly expected nor explicitly unexpected) to the given
163 // ostream.
164 virtual void UntypedDescribeUninterestingCall(
165 const void* untyped_args,
166 ::std::ostream* os) const
167 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
168
169 // Returns the expectation that matches the given function arguments
170 // (or NULL is there's no match); when a match is found,
171 // untyped_action is set to point to the action that should be
172 // performed (or NULL if the action is "do default"), and
173 // is_excessive is modified to indicate whether the call exceeds the
174 // expected number.
175 virtual const ExpectationBase* UntypedFindMatchingExpectation(
176 const void* untyped_args,
177 const void** untyped_action, bool* is_excessive,
178 ::std::ostream* what, ::std::ostream* why)
179 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
180
181 // Prints the given function arguments to the ostream.
182 virtual void UntypedPrintArgs(const void* untyped_args,
183 ::std::ostream* os) const = 0;
184
185 // Sets the mock object this mock method belongs to, and registers
186 // this information in the global mock registry. Will be called
187 // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock
188 // method.
189 void RegisterOwner(const void* mock_obj)
190 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
191
192 // Sets the mock object this mock method belongs to, and sets the
193 // name of the mock function. Will be called upon each invocation
194 // of this mock function.
195 void SetOwnerAndName(const void* mock_obj, const char* name)
196 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
197
198 // Returns the mock object this mock method belongs to. Must be
199 // called after RegisterOwner() or SetOwnerAndName() has been
200 // called.
201 const void* MockObject() const
202 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
203
204 // Returns the name of this mock method. Must be called after
205 // SetOwnerAndName() has been called.
206 const char* Name() const
207 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
208
209 // Returns the result of invoking this mock function with the given
210 // arguments. This function can be safely called from multiple
211 // threads concurrently. The caller is responsible for deleting the
212 // result.
213 UntypedActionResultHolderBase* UntypedInvokeWith(void* untyped_args)
214 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
215
216 protected:
217 typedef std::vector<const void*> UntypedOnCallSpecs;
218
219 using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;
220
221 // Returns an Expectation object that references and co-owns exp,
222 // which must be an expectation on this mock function.
223 Expectation GetHandleOf(ExpectationBase* exp);
224
225 // Address of the mock object this mock method belongs to. Only
226 // valid after this mock method has been called or
227 // ON_CALL/EXPECT_CALL has been invoked on it.
228 const void* mock_obj_; // Protected by g_gmock_mutex.
229
230 // Name of the function being mocked. Only valid after this mock
231 // method has been called.
232 const char* name_; // Protected by g_gmock_mutex.
233
234 // All default action specs for this function mocker.
235 UntypedOnCallSpecs untyped_on_call_specs_;
236
237 // All expectations for this function mocker.
238 //
239 // It's undefined behavior to interleave expectations (EXPECT_CALLs
240 // or ON_CALLs) and mock function calls. Also, the order of
241 // expectations is important. Therefore it's a logic race condition
242 // to read/write untyped_expectations_ concurrently. In order for
243 // tools like tsan to catch concurrent read/write accesses to
244 // untyped_expectations, we deliberately leave accesses to it
245 // unprotected.
246 UntypedExpectations untyped_expectations_;
247}; // class UntypedFunctionMockerBase
248
249// Untyped base class for OnCallSpec<F>.
250class UntypedOnCallSpecBase {
251 public:
252 // The arguments are the location of the ON_CALL() statement.
253 UntypedOnCallSpecBase(const char* a_file, int a_line)
254 : file_(a_file), line_(a_line), last_clause_(kNone) {}
255
256 // Where in the source file was the default action spec defined?
257 const char* file() const { return file_; }
258 int line() const { return line_; }
259
260 protected:
261 // Gives each clause in the ON_CALL() statement a name.
262 enum Clause {
263 // Do not change the order of the enum members! The run-time
264 // syntax checking relies on it.
265 kNone,
266 kWith,
267 kWillByDefault
268 };
269
270 // Asserts that the ON_CALL() statement has a certain property.
271 void AssertSpecProperty(bool property,
272 const std::string& failure_message) const {
273 Assert(property, file_, line_, failure_message);
274 }
275
276 // Expects that the ON_CALL() statement has a certain property.
277 void ExpectSpecProperty(bool property,
278 const std::string& failure_message) const {
279 Expect(property, file_, line_, failure_message);
280 }
281
282 const char* file_;
283 int line_;
284
285 // The last clause in the ON_CALL() statement as seen so far.
286 // Initially kNone and changes as the statement is parsed.
287 Clause last_clause_;
288}; // class UntypedOnCallSpecBase
289
290// This template class implements an ON_CALL spec.
291template <typename F>
292class OnCallSpec : public UntypedOnCallSpecBase {
293 public:
294 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
295 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
296
297 // Constructs an OnCallSpec object from the information inside
298 // the parenthesis of an ON_CALL() statement.
299 OnCallSpec(const char* a_file, int a_line,
300 const ArgumentMatcherTuple& matchers)
301 : UntypedOnCallSpecBase(a_file, a_line),
302 matchers_(matchers),
303 // By default, extra_matcher_ should match anything. However,
304 // we cannot initialize it with _ as that causes ambiguity between
305 // Matcher's copy and move constructor for some argument types.
306 extra_matcher_(A<const ArgumentTuple&>()) {}
307
308 // Implements the .With() clause.
309 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
310 // Makes sure this is called at most once.
311 ExpectSpecProperty(last_clause_ < kWith,
312 ".With() cannot appear "
313 "more than once in an ON_CALL().");
314 last_clause_ = kWith;
315
316 extra_matcher_ = m;
317 return *this;
318 }
319
320 // Implements the .WillByDefault() clause.
321 OnCallSpec& WillByDefault(const Action<F>& action) {
322 ExpectSpecProperty(last_clause_ < kWillByDefault,
323 ".WillByDefault() must appear "
324 "exactly once in an ON_CALL().");
325 last_clause_ = kWillByDefault;
326
327 ExpectSpecProperty(!action.IsDoDefault(),
328 "DoDefault() cannot be used in ON_CALL().");
329 action_ = action;
330 return *this;
331 }
332
333 // Returns true iff the given arguments match the matchers.
334 bool Matches(const ArgumentTuple& args) const {
335 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
336 }
337
338 // Returns the action specified by the user.
339 const Action<F>& GetAction() const {
340 AssertSpecProperty(last_clause_ == kWillByDefault,
341 ".WillByDefault() must appear exactly "
342 "once in an ON_CALL().");
343 return action_;
344 }
345
346 private:
347 // The information in statement
348 //
349 // ON_CALL(mock_object, Method(matchers))
350 // .With(multi-argument-matcher)
351 // .WillByDefault(action);
352 //
353 // is recorded in the data members like this:
354 //
355 // source file that contains the statement => file_
356 // line number of the statement => line_
357 // matchers => matchers_
358 // multi-argument-matcher => extra_matcher_
359 // action => action_
360 ArgumentMatcherTuple matchers_;
361 Matcher<const ArgumentTuple&> extra_matcher_;
362 Action<F> action_;
363}; // class OnCallSpec
364
365// Possible reactions on uninteresting calls.
366enum CallReaction {
367 kAllow,
368 kWarn,
369 kFail,
370};
371
372} // namespace internal
373
374// Utilities for manipulating mock objects.
375class GTEST_API_ Mock {
376 public:
377 // The following public methods can be called concurrently.
378
379 // Tells Google Mock to ignore mock_obj when checking for leaked
380 // mock objects.
381 static void AllowLeak(const void* mock_obj)
382 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
383
384 // Verifies and clears all expectations on the given mock object.
385 // If the expectations aren't satisfied, generates one or more
386 // Google Test non-fatal failures and returns false.
387 static bool VerifyAndClearExpectations(void* mock_obj)
388 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
389
390 // Verifies all expectations on the given mock object and clears its
391 // default actions and expectations. Returns true iff the
392 // verification was successful.
393 static bool VerifyAndClear(void* mock_obj)
394 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
395
396 // Returns whether the mock was created as a naggy mock (default)
397 static bool IsNaggy(void* mock_obj)
398 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
399 // Returns whether the mock was created as a nice mock
400 static bool IsNice(void* mock_obj)
401 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
402 // Returns whether the mock was created as a strict mock
403 static bool IsStrict(void* mock_obj)
404 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
405
406 private:
407 friend class internal::UntypedFunctionMockerBase;
408
409 // Needed for a function mocker to register itself (so that we know
410 // how to clear a mock object).
411 template <typename F>
412 friend class internal::FunctionMocker;
413
414 template <typename M>
415 friend class NiceMock;
416
417 template <typename M>
418 friend class NaggyMock;
419
420 template <typename M>
421 friend class StrictMock;
422
423 // Tells Google Mock to allow uninteresting calls on the given mock
424 // object.
425 static void AllowUninterestingCalls(const void* mock_obj)
426 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
427
428 // Tells Google Mock to warn the user about uninteresting calls on
429 // the given mock object.
430 static void WarnUninterestingCalls(const void* mock_obj)
431 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
432
433 // Tells Google Mock to fail uninteresting calls on the given mock
434 // object.
435 static void FailUninterestingCalls(const void* mock_obj)
436 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
437
438 // Tells Google Mock the given mock object is being destroyed and
439 // its entry in the call-reaction table should be removed.
440 static void UnregisterCallReaction(const void* mock_obj)
441 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
442
443 // Returns the reaction Google Mock will have on uninteresting calls
444 // made on the given mock object.
445 static internal::CallReaction GetReactionOnUninterestingCalls(
446 const void* mock_obj)
447 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
448
449 // Verifies that all expectations on the given mock object have been
450 // satisfied. Reports one or more Google Test non-fatal failures
451 // and returns false if not.
452 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
453 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
454
455 // Clears all ON_CALL()s set on the given mock object.
456 static void ClearDefaultActionsLocked(void* mock_obj)
457 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
458
459 // Registers a mock object and a mock method it owns.
460 static void Register(
461 const void* mock_obj,
462 internal::UntypedFunctionMockerBase* mocker)
463 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
464
465 // Tells Google Mock where in the source code mock_obj is used in an
466 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
467 // information helps the user identify which object it is.
468 static void RegisterUseByOnCallOrExpectCall(
469 const void* mock_obj, const char* file, int line)
470 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
471
472 // Unregisters a mock method; removes the owning mock object from
473 // the registry when the last mock method associated with it has
474 // been unregistered. This is called only in the destructor of
475 // FunctionMocker.
476 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
477 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
478}; // class Mock
479
480// An abstract handle of an expectation. Useful in the .After()
481// clause of EXPECT_CALL() for setting the (partial) order of
482// expectations. The syntax:
483//
484// Expectation e1 = EXPECT_CALL(...)...;
485// EXPECT_CALL(...).After(e1)...;
486//
487// sets two expectations where the latter can only be matched after
488// the former has been satisfied.
489//
490// Notes:
491// - This class is copyable and has value semantics.
492// - Constness is shallow: a const Expectation object itself cannot
493// be modified, but the mutable methods of the ExpectationBase
494// object it references can be called via expectation_base().
495
496class GTEST_API_ Expectation {
497 public:
498 // Constructs a null object that doesn't reference any expectation.
499 Expectation();
500
501 ~Expectation();
502
503 // This single-argument ctor must not be explicit, in order to support the
504 // Expectation e = EXPECT_CALL(...);
505 // syntax.
506 //
507 // A TypedExpectation object stores its pre-requisites as
508 // Expectation objects, and needs to call the non-const Retire()
509 // method on the ExpectationBase objects they reference. Therefore
510 // Expectation must receive a *non-const* reference to the
511 // ExpectationBase object.
512 Expectation(internal::ExpectationBase& exp); // NOLINT
513
514 // The compiler-generated copy ctor and operator= work exactly as
515 // intended, so we don't need to define our own.
516
517 // Returns true iff rhs references the same expectation as this object does.
518 bool operator==(const Expectation& rhs) const {
519 return expectation_base_ == rhs.expectation_base_;
520 }
521
522 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
523
524 private:
525 friend class ExpectationSet;
526 friend class Sequence;
527 friend class ::testing::internal::ExpectationBase;
528 friend class ::testing::internal::UntypedFunctionMockerBase;
529
530 template <typename F>
531 friend class ::testing::internal::FunctionMocker;
532
533 template <typename F>
534 friend class ::testing::internal::TypedExpectation;
535
536 // This comparator is needed for putting Expectation objects into a set.
537 class Less {
538 public:
539 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
540 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
541 }
542 };
543
544 typedef ::std::set<Expectation, Less> Set;
545
546 Expectation(
547 const std::shared_ptr<internal::ExpectationBase>& expectation_base);
548
549 // Returns the expectation this object references.
550 const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {
551 return expectation_base_;
552 }
553
554 // A shared_ptr that co-owns the expectation this handle references.
555 std::shared_ptr<internal::ExpectationBase> expectation_base_;
556};
557
558// A set of expectation handles. Useful in the .After() clause of
559// EXPECT_CALL() for setting the (partial) order of expectations. The
560// syntax:
561//
562// ExpectationSet es;
563// es += EXPECT_CALL(...)...;
564// es += EXPECT_CALL(...)...;
565// EXPECT_CALL(...).After(es)...;
566//
567// sets three expectations where the last one can only be matched
568// after the first two have both been satisfied.
569//
570// This class is copyable and has value semantics.
571class ExpectationSet {
572 public:
573 // A bidirectional iterator that can read a const element in the set.
574 typedef Expectation::Set::const_iterator const_iterator;
575
576 // An object stored in the set. This is an alias of Expectation.
577 typedef Expectation::Set::value_type value_type;
578
579 // Constructs an empty set.
580 ExpectationSet() {}
581
582 // This single-argument ctor must not be explicit, in order to support the
583 // ExpectationSet es = EXPECT_CALL(...);
584 // syntax.
585 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
586 *this += Expectation(exp);
587 }
588
589 // This single-argument ctor implements implicit conversion from
590 // Expectation and thus must not be explicit. This allows either an
591 // Expectation or an ExpectationSet to be used in .After().
592 ExpectationSet(const Expectation& e) { // NOLINT
593 *this += e;
594 }
595
596 // The compiler-generator ctor and operator= works exactly as
597 // intended, so we don't need to define our own.
598
599 // Returns true iff rhs contains the same set of Expectation objects
600 // as this does.
601 bool operator==(const ExpectationSet& rhs) const {
602 return expectations_ == rhs.expectations_;
603 }
604
605 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
606
607 // Implements the syntax
608 // expectation_set += EXPECT_CALL(...);
609 ExpectationSet& operator+=(const Expectation& e) {
610 expectations_.insert(e);
611 return *this;
612 }
613
614 int size() const { return static_cast<int>(expectations_.size()); }
615
616 const_iterator begin() const { return expectations_.begin(); }
617 const_iterator end() const { return expectations_.end(); }
618
619 private:
620 Expectation::Set expectations_;
621};
622
623
624// Sequence objects are used by a user to specify the relative order
625// in which the expectations should match. They are copyable (we rely
626// on the compiler-defined copy constructor and assignment operator).
627class GTEST_API_ Sequence {
628 public:
629 // Constructs an empty sequence.
630 Sequence() : last_expectation_(new Expectation) {}
631
632 // Adds an expectation to this sequence. The caller must ensure
633 // that no other thread is accessing this Sequence object.
634 void AddExpectation(const Expectation& expectation) const;
635
636 private:
637 // The last expectation in this sequence.
638 std::shared_ptr<Expectation> last_expectation_;
639}; // class Sequence
640
641// An object of this type causes all EXPECT_CALL() statements
642// encountered in its scope to be put in an anonymous sequence. The
643// work is done in the constructor and destructor. You should only
644// create an InSequence object on the stack.
645//
646// The sole purpose for this class is to support easy definition of
647// sequential expectations, e.g.
648//
649// {
650// InSequence dummy; // The name of the object doesn't matter.
651//
652// // The following expectations must match in the order they appear.
653// EXPECT_CALL(a, Bar())...;
654// EXPECT_CALL(a, Baz())...;
655// ...
656// EXPECT_CALL(b, Xyz())...;
657// }
658//
659// You can create InSequence objects in multiple threads, as long as
660// they are used to affect different mock objects. The idea is that
661// each thread can create and set up its own mocks as if it's the only
662// thread. However, for clarity of your tests we recommend you to set
663// up mocks in the main thread unless you have a good reason not to do
664// so.
665class GTEST_API_ InSequence {
666 public:
667 InSequence();
668 ~InSequence();
669 private:
670 bool sequence_created_;
671
672 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
673} GTEST_ATTRIBUTE_UNUSED_;
674
675namespace internal {
676
677// Points to the implicit sequence introduced by a living InSequence
678// object (if any) in the current thread or NULL.
679GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
680
681// Base class for implementing expectations.
682//
683// There are two reasons for having a type-agnostic base class for
684// Expectation:
685//
686// 1. We need to store collections of expectations of different
687// types (e.g. all pre-requisites of a particular expectation, all
688// expectations in a sequence). Therefore these expectation objects
689// must share a common base class.
690//
691// 2. We can avoid binary code bloat by moving methods not depending
692// on the template argument of Expectation to the base class.
693//
694// This class is internal and mustn't be used by user code directly.
695class GTEST_API_ ExpectationBase {
696 public:
697 // source_text is the EXPECT_CALL(...) source that created this Expectation.
698 ExpectationBase(const char* file, int line, const std::string& source_text);
699
700 virtual ~ExpectationBase();
701
702 // Where in the source file was the expectation spec defined?
703 const char* file() const { return file_; }
704 int line() const { return line_; }
705 const char* source_text() const { return source_text_.c_str(); }
706 // Returns the cardinality specified in the expectation spec.
707 const Cardinality& cardinality() const { return cardinality_; }
708
709 // Describes the source file location of this expectation.
710 void DescribeLocationTo(::std::ostream* os) const {
711 *os << FormatFileLocation(file(), line()) << " ";
712 }
713
714 // Describes how many times a function call matching this
715 // expectation has occurred.
716 void DescribeCallCountTo(::std::ostream* os) const
717 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
718
719 // If this mock method has an extra matcher (i.e. .With(matcher)),
720 // describes it to the ostream.
721 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
722
723 protected:
724 friend class ::testing::Expectation;
725 friend class UntypedFunctionMockerBase;
726
727 enum Clause {
728 // Don't change the order of the enum members!
729 kNone,
730 kWith,
731 kTimes,
732 kInSequence,
733 kAfter,
734 kWillOnce,
735 kWillRepeatedly,
736 kRetiresOnSaturation
737 };
738
739 typedef std::vector<const void*> UntypedActions;
740
741 // Returns an Expectation object that references and co-owns this
742 // expectation.
743 virtual Expectation GetHandle() = 0;
744
745 // Asserts that the EXPECT_CALL() statement has the given property.
746 void AssertSpecProperty(bool property,
747 const std::string& failure_message) const {
748 Assert(property, file_, line_, failure_message);
749 }
750
751 // Expects that the EXPECT_CALL() statement has the given property.
752 void ExpectSpecProperty(bool property,
753 const std::string& failure_message) const {
754 Expect(property, file_, line_, failure_message);
755 }
756
757 // Explicitly specifies the cardinality of this expectation. Used
758 // by the subclasses to implement the .Times() clause.
759 void SpecifyCardinality(const Cardinality& cardinality);
760
761 // Returns true iff the user specified the cardinality explicitly
762 // using a .Times().
763 bool cardinality_specified() const { return cardinality_specified_; }
764
765 // Sets the cardinality of this expectation spec.
766 void set_cardinality(const Cardinality& a_cardinality) {
767 cardinality_ = a_cardinality;
768 }
769
770 // The following group of methods should only be called after the
771 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
772 // the current thread.
773
774 // Retires all pre-requisites of this expectation.
775 void RetireAllPreRequisites()
776 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
777
778 // Returns true iff this expectation is retired.
779 bool is_retired() const
780 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
781 g_gmock_mutex.AssertHeld();
782 return retired_;
783 }
784
785 // Retires this expectation.
786 void Retire()
787 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
788 g_gmock_mutex.AssertHeld();
789 retired_ = true;
790 }
791
792 // Returns true iff this expectation is satisfied.
793 bool IsSatisfied() const
794 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
795 g_gmock_mutex.AssertHeld();
796 return cardinality().IsSatisfiedByCallCount(call_count_);
797 }
798
799 // Returns true iff this expectation is saturated.
800 bool IsSaturated() const
801 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
802 g_gmock_mutex.AssertHeld();
803 return cardinality().IsSaturatedByCallCount(call_count_);
804 }
805
806 // Returns true iff this expectation is over-saturated.
807 bool IsOverSaturated() const
808 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
809 g_gmock_mutex.AssertHeld();
810 return cardinality().IsOverSaturatedByCallCount(call_count_);
811 }
812
813 // Returns true iff all pre-requisites of this expectation are satisfied.
814 bool AllPrerequisitesAreSatisfied() const
815 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
816
817 // Adds unsatisfied pre-requisites of this expectation to 'result'.
818 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
819 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
820
821 // Returns the number this expectation has been invoked.
822 int call_count() const
823 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
824 g_gmock_mutex.AssertHeld();
825 return call_count_;
826 }
827
828 // Increments the number this expectation has been invoked.
829 void IncrementCallCount()
830 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
831 g_gmock_mutex.AssertHeld();
832 call_count_++;
833 }
834
835 // Checks the action count (i.e. the number of WillOnce() and
836 // WillRepeatedly() clauses) against the cardinality if this hasn't
837 // been done before. Prints a warning if there are too many or too
838 // few actions.
839 void CheckActionCountIfNotDone() const
840 GTEST_LOCK_EXCLUDED_(mutex_);
841
842 friend class ::testing::Sequence;
843 friend class ::testing::internal::ExpectationTester;
844
845 template <typename Function>
846 friend class TypedExpectation;
847
848 // Implements the .Times() clause.
849 void UntypedTimes(const Cardinality& a_cardinality);
850
851 // This group of fields are part of the spec and won't change after
852 // an EXPECT_CALL() statement finishes.
853 const char* file_; // The file that contains the expectation.
854 int line_; // The line number of the expectation.
855 const std::string source_text_; // The EXPECT_CALL(...) source text.
856 // True iff the cardinality is specified explicitly.
857 bool cardinality_specified_;
858 Cardinality cardinality_; // The cardinality of the expectation.
859 // The immediate pre-requisites (i.e. expectations that must be
860 // satisfied before this expectation can be matched) of this
861 // expectation. We use std::shared_ptr in the set because we want an
862 // Expectation object to be co-owned by its FunctionMocker and its
863 // successors. This allows multiple mock objects to be deleted at
864 // different times.
865 ExpectationSet immediate_prerequisites_;
866
867 // This group of fields are the current state of the expectation,
868 // and can change as the mock function is called.
869 int call_count_; // How many times this expectation has been invoked.
870 bool retired_; // True iff this expectation has retired.
871 UntypedActions untyped_actions_;
872 bool extra_matcher_specified_;
873 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
874 bool retires_on_saturation_;
875 Clause last_clause_;
876 mutable bool action_count_checked_; // Under mutex_.
877 mutable Mutex mutex_; // Protects action_count_checked_.
878
879 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
880}; // class ExpectationBase
881
882// Impements an expectation for the given function type.
883template <typename F>
884class TypedExpectation : public ExpectationBase {
885 public:
886 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
887 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
888 typedef typename Function<F>::Result Result;
889
890 TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,
891 const std::string& a_source_text,
892 const ArgumentMatcherTuple& m)
893 : ExpectationBase(a_file, a_line, a_source_text),
894 owner_(owner),
895 matchers_(m),
896 // By default, extra_matcher_ should match anything. However,
897 // we cannot initialize it with _ as that causes ambiguity between
898 // Matcher's copy and move constructor for some argument types.
899 extra_matcher_(A<const ArgumentTuple&>()),
900 repeated_action_(DoDefault()) {}
901
902 ~TypedExpectation() override {
903 // Check the validity of the action count if it hasn't been done
904 // yet (for example, if the expectation was never used).
905 CheckActionCountIfNotDone();
906 for (UntypedActions::const_iterator it = untyped_actions_.begin();
907 it != untyped_actions_.end(); ++it) {
908 delete static_cast<const Action<F>*>(*it);
909 }
910 }
911
912 // Implements the .With() clause.
913 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
914 if (last_clause_ == kWith) {
915 ExpectSpecProperty(false,
916 ".With() cannot appear "
917 "more than once in an EXPECT_CALL().");
918 } else {
919 ExpectSpecProperty(last_clause_ < kWith,
920 ".With() must be the first "
921 "clause in an EXPECT_CALL().");
922 }
923 last_clause_ = kWith;
924
925 extra_matcher_ = m;
926 extra_matcher_specified_ = true;
927 return *this;
928 }
929
930 // Implements the .Times() clause.
931 TypedExpectation& Times(const Cardinality& a_cardinality) {
932 ExpectationBase::UntypedTimes(a_cardinality);
933 return *this;
934 }
935
936 // Implements the .Times() clause.
937 TypedExpectation& Times(int n) {
938 return Times(Exactly(n));
939 }
940
941 // Implements the .InSequence() clause.
942 TypedExpectation& InSequence(const Sequence& s) {
943 ExpectSpecProperty(last_clause_ <= kInSequence,
944 ".InSequence() cannot appear after .After(),"
945 " .WillOnce(), .WillRepeatedly(), or "
946 ".RetiresOnSaturation().");
947 last_clause_ = kInSequence;
948
949 s.AddExpectation(GetHandle());
950 return *this;
951 }
952 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
953 return InSequence(s1).InSequence(s2);
954 }
955 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
956 const Sequence& s3) {
957 return InSequence(s1, s2).InSequence(s3);
958 }
959 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
960 const Sequence& s3, const Sequence& s4) {
961 return InSequence(s1, s2, s3).InSequence(s4);
962 }
963 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
964 const Sequence& s3, const Sequence& s4,
965 const Sequence& s5) {
966 return InSequence(s1, s2, s3, s4).InSequence(s5);
967 }
968
969 // Implements that .After() clause.
970 TypedExpectation& After(const ExpectationSet& s) {
971 ExpectSpecProperty(last_clause_ <= kAfter,
972 ".After() cannot appear after .WillOnce(),"
973 " .WillRepeatedly(), or "
974 ".RetiresOnSaturation().");
975 last_clause_ = kAfter;
976
977 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
978 immediate_prerequisites_ += *it;
979 }
980 return *this;
981 }
982 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
983 return After(s1).After(s2);
984 }
985 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
986 const ExpectationSet& s3) {
987 return After(s1, s2).After(s3);
988 }
989 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
990 const ExpectationSet& s3, const ExpectationSet& s4) {
991 return After(s1, s2, s3).After(s4);
992 }
993 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
994 const ExpectationSet& s3, const ExpectationSet& s4,
995 const ExpectationSet& s5) {
996 return After(s1, s2, s3, s4).After(s5);
997 }
998
999 // Implements the .WillOnce() clause.
1000 TypedExpectation& WillOnce(const Action<F>& action) {
1001 ExpectSpecProperty(last_clause_ <= kWillOnce,
1002 ".WillOnce() cannot appear after "
1003 ".WillRepeatedly() or .RetiresOnSaturation().");
1004 last_clause_ = kWillOnce;
1005
1006 untyped_actions_.push_back(new Action<F>(action));
1007 if (!cardinality_specified()) {
1008 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
1009 }
1010 return *this;
1011 }
1012
1013 // Implements the .WillRepeatedly() clause.
1014 TypedExpectation& WillRepeatedly(const Action<F>& action) {
1015 if (last_clause_ == kWillRepeatedly) {
1016 ExpectSpecProperty(false,
1017 ".WillRepeatedly() cannot appear "
1018 "more than once in an EXPECT_CALL().");
1019 } else {
1020 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
1021 ".WillRepeatedly() cannot appear "
1022 "after .RetiresOnSaturation().");
1023 }
1024 last_clause_ = kWillRepeatedly;
1025 repeated_action_specified_ = true;
1026
1027 repeated_action_ = action;
1028 if (!cardinality_specified()) {
1029 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
1030 }
1031
1032 // Now that no more action clauses can be specified, we check
1033 // whether their count makes sense.
1034 CheckActionCountIfNotDone();
1035 return *this;
1036 }
1037
1038 // Implements the .RetiresOnSaturation() clause.
1039 TypedExpectation& RetiresOnSaturation() {
1040 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
1041 ".RetiresOnSaturation() cannot appear "
1042 "more than once.");
1043 last_clause_ = kRetiresOnSaturation;
1044 retires_on_saturation_ = true;
1045
1046 // Now that no more action clauses can be specified, we check
1047 // whether their count makes sense.
1048 CheckActionCountIfNotDone();
1049 return *this;
1050 }
1051
1052 // Returns the matchers for the arguments as specified inside the
1053 // EXPECT_CALL() macro.
1054 const ArgumentMatcherTuple& matchers() const {
1055 return matchers_;
1056 }
1057
1058 // Returns the matcher specified by the .With() clause.
1059 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1060 return extra_matcher_;
1061 }
1062
1063 // Returns the action specified by the .WillRepeatedly() clause.
1064 const Action<F>& repeated_action() const { return repeated_action_; }
1065
1066 // If this mock method has an extra matcher (i.e. .With(matcher)),
1067 // describes it to the ostream.
1068 void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {
1069 if (extra_matcher_specified_) {
1070 *os << " Expected args: ";
1071 extra_matcher_.DescribeTo(os);
1072 *os << "\n";
1073 }
1074 }
1075
1076 private:
1077 template <typename Function>
1078 friend class FunctionMocker;
1079
1080 // Returns an Expectation object that references and co-owns this
1081 // expectation.
1082 Expectation GetHandle() override { return owner_->GetHandleOf(this); }
1083
1084 // The following methods will be called only after the EXPECT_CALL()
1085 // statement finishes and when the current thread holds
1086 // g_gmock_mutex.
1087
1088 // Returns true iff this expectation matches the given arguments.
1089 bool Matches(const ArgumentTuple& args) const
1090 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1091 g_gmock_mutex.AssertHeld();
1092 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1093 }
1094
1095 // Returns true iff this expectation should handle the given arguments.
1096 bool ShouldHandleArguments(const ArgumentTuple& args) const
1097 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1098 g_gmock_mutex.AssertHeld();
1099
1100 // In case the action count wasn't checked when the expectation
1101 // was defined (e.g. if this expectation has no WillRepeatedly()
1102 // or RetiresOnSaturation() clause), we check it when the
1103 // expectation is used for the first time.
1104 CheckActionCountIfNotDone();
1105 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1106 }
1107
1108 // Describes the result of matching the arguments against this
1109 // expectation to the given ostream.
1110 void ExplainMatchResultTo(
1111 const ArgumentTuple& args,
1112 ::std::ostream* os) const
1113 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1114 g_gmock_mutex.AssertHeld();
1115
1116 if (is_retired()) {
1117 *os << " Expected: the expectation is active\n"
1118 << " Actual: it is retired\n";
1119 } else if (!Matches(args)) {
1120 if (!TupleMatches(matchers_, args)) {
1121 ExplainMatchFailureTupleTo(matchers_, args, os);
1122 }
1123 StringMatchResultListener listener;
1124 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
1125 *os << " Expected args: ";
1126 extra_matcher_.DescribeTo(os);
1127 *os << "\n Actual: don't match";
1128
1129 internal::PrintIfNotEmpty(listener.str(), os);
1130 *os << "\n";
1131 }
1132 } else if (!AllPrerequisitesAreSatisfied()) {
1133 *os << " Expected: all pre-requisites are satisfied\n"
1134 << " Actual: the following immediate pre-requisites "
1135 << "are not satisfied:\n";
1136 ExpectationSet unsatisfied_prereqs;
1137 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1138 int i = 0;
1139 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
1140 it != unsatisfied_prereqs.end(); ++it) {
1141 it->expectation_base()->DescribeLocationTo(os);
1142 *os << "pre-requisite #" << i++ << "\n";
1143 }
1144 *os << " (end of pre-requisites)\n";
1145 } else {
1146 // This line is here just for completeness' sake. It will never
1147 // be executed as currently the ExplainMatchResultTo() function
1148 // is called only when the mock function call does NOT match the
1149 // expectation.
1150 *os << "The call matches the expectation.\n";
1151 }
1152 }
1153
1154 // Returns the action that should be taken for the current invocation.
1155 const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,
1156 const ArgumentTuple& args) const
1157 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1158 g_gmock_mutex.AssertHeld();
1159 const int count = call_count();
1160 Assert(count >= 1, __FILE__, __LINE__,
1161 "call_count() is <= 0 when GetCurrentAction() is "
1162 "called - this should never happen.");
1163
1164 const int action_count = static_cast<int>(untyped_actions_.size());
1165 if (action_count > 0 && !repeated_action_specified_ &&
1166 count > action_count) {
1167 // If there is at least one WillOnce() and no WillRepeatedly(),
1168 // we warn the user when the WillOnce() clauses ran out.
1169 ::std::stringstream ss;
1170 DescribeLocationTo(&ss);
1171 ss << "Actions ran out in " << source_text() << "...\n"
1172 << "Called " << count << " times, but only "
1173 << action_count << " WillOnce()"
1174 << (action_count == 1 ? " is" : "s are") << " specified - ";
1175 mocker->DescribeDefaultActionTo(args, &ss);
1176 Log(kWarning, ss.str(), 1);
1177 }
1178
1179 return count <= action_count
1180 ? *static_cast<const Action<F>*>(
1181 untyped_actions_[static_cast<size_t>(count - 1)])
1182 : repeated_action();
1183 }
1184
1185 // Given the arguments of a mock function call, if the call will
1186 // over-saturate this expectation, returns the default action;
1187 // otherwise, returns the next action in this expectation. Also
1188 // describes *what* happened to 'what', and explains *why* Google
1189 // Mock does it to 'why'. This method is not const as it calls
1190 // IncrementCallCount(). A return value of NULL means the default
1191 // action.
1192 const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,
1193 const ArgumentTuple& args,
1194 ::std::ostream* what,
1195 ::std::ostream* why)
1196 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1197 g_gmock_mutex.AssertHeld();
1198 if (IsSaturated()) {
1199 // We have an excessive call.
1200 IncrementCallCount();
1201 *what << "Mock function called more times than expected - ";
1202 mocker->DescribeDefaultActionTo(args, what);
1203 DescribeCallCountTo(why);
1204
1205 return nullptr;
1206 }
1207
1208 IncrementCallCount();
1209 RetireAllPreRequisites();
1210
1211 if (retires_on_saturation_ && IsSaturated()) {
1212 Retire();
1213 }
1214
1215 // Must be done after IncrementCount()!
1216 *what << "Mock function call matches " << source_text() <<"...\n";
1217 return &(GetCurrentAction(mocker, args));
1218 }
1219
1220 // All the fields below won't change once the EXPECT_CALL()
1221 // statement finishes.
1222 FunctionMocker<F>* const owner_;
1223 ArgumentMatcherTuple matchers_;
1224 Matcher<const ArgumentTuple&> extra_matcher_;
1225 Action<F> repeated_action_;
1226
1227 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
1228}; // class TypedExpectation
1229
1230// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1231// specifying the default behavior of, or expectation on, a mock
1232// function.
1233
1234// Note: class MockSpec really belongs to the ::testing namespace.
1235// However if we define it in ::testing, MSVC will complain when
1236// classes in ::testing::internal declare it as a friend class
1237// template. To workaround this compiler bug, we define MockSpec in
1238// ::testing::internal and import it into ::testing.
1239
1240// Logs a message including file and line number information.
1241GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1242 const char* file, int line,
1243 const std::string& message);
1244
1245template <typename F>
1246class MockSpec {
1247 public:
1248 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1249 typedef typename internal::Function<F>::ArgumentMatcherTuple
1250 ArgumentMatcherTuple;
1251
1252 // Constructs a MockSpec object, given the function mocker object
1253 // that the spec is associated with.
1254 MockSpec(internal::FunctionMocker<F>* function_mocker,
1255 const ArgumentMatcherTuple& matchers)
1256 : function_mocker_(function_mocker), matchers_(matchers) {}
1257
1258 // Adds a new default action spec to the function mocker and returns
1259 // the newly created spec.
1260 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
1261 const char* file, int line, const char* obj, const char* call) {
1262 LogWithLocation(internal::kInfo, file, line,
1263 std::string("ON_CALL(") + obj + ", " + call + ") invoked");
1264 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
1265 }
1266
1267 // Adds a new expectation spec to the function mocker and returns
1268 // the newly created spec.
1269 internal::TypedExpectation<F>& InternalExpectedAt(
1270 const char* file, int line, const char* obj, const char* call) {
1271 const std::string source_text(std::string("EXPECT_CALL(") + obj + ", " +
1272 call + ")");
1273 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
1274 return function_mocker_->AddNewExpectation(
1275 file, line, source_text, matchers_);
1276 }
1277
1278 // This operator overload is used to swallow the superfluous parameter list
1279 // introduced by the ON/EXPECT_CALL macros. See the macro comments for more
1280 // explanation.
1281 MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {
1282 return *this;
1283 }
1284
1285 private:
1286 template <typename Function>
1287 friend class internal::FunctionMocker;
1288
1289 // The function mocker that owns this spec.
1290 internal::FunctionMocker<F>* const function_mocker_;
1291 // The argument matchers specified in the spec.
1292 ArgumentMatcherTuple matchers_;
1293
1294 GTEST_DISALLOW_ASSIGN_(MockSpec);
1295}; // class MockSpec
1296
1297// Wrapper type for generically holding an ordinary value or lvalue reference.
1298// If T is not a reference type, it must be copyable or movable.
1299// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless
1300// T is a move-only value type (which means that it will always be copyable
1301// if the current platform does not support move semantics).
1302//
1303// The primary template defines handling for values, but function header
1304// comments describe the contract for the whole template (including
1305// specializations).
1306template <typename T>
1307class ReferenceOrValueWrapper {
1308 public:
1309 // Constructs a wrapper from the given value/reference.
1310 explicit ReferenceOrValueWrapper(T value)
1311 : value_(std::move(value)) {
1312 }
1313
1314 // Unwraps and returns the underlying value/reference, exactly as
1315 // originally passed. The behavior of calling this more than once on
1316 // the same object is unspecified.
1317 T Unwrap() { return std::move(value_); }
1318
1319 // Provides nondestructive access to the underlying value/reference.
1320 // Always returns a const reference (more precisely,
1321 // const RemoveReference<T>&). The behavior of calling this after
1322 // calling Unwrap on the same object is unspecified.
1323 const T& Peek() const {
1324 return value_;
1325 }
1326
1327 private:
1328 T value_;
1329};
1330
1331// Specialization for lvalue reference types. See primary template
1332// for documentation.
1333template <typename T>
1334class ReferenceOrValueWrapper<T&> {
1335 public:
1336 // Workaround for debatable pass-by-reference lint warning (c-library-team
1337 // policy precludes NOLINT in this context)
1338 typedef T& reference;
1339 explicit ReferenceOrValueWrapper(reference ref)
1340 : value_ptr_(&ref) {}
1341 T& Unwrap() { return *value_ptr_; }
1342 const T& Peek() const { return *value_ptr_; }
1343
1344 private:
1345 T* value_ptr_;
1346};
1347
1348// MSVC warns about using 'this' in base member initializer list, so
1349// we need to temporarily disable the warning. We have to do it for
1350// the entire class to suppress the warning, even though it's about
1351// the constructor only.
1352GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355)
1353
1354// C++ treats the void type specially. For example, you cannot define
1355// a void-typed variable or pass a void value to a function.
1356// ActionResultHolder<T> holds a value of type T, where T must be a
1357// copyable type or void (T doesn't need to be default-constructable).
1358// It hides the syntactic difference between void and other types, and
1359// is used to unify the code for invoking both void-returning and
1360// non-void-returning mock functions.
1361
1362// Untyped base class for ActionResultHolder<T>.
1363class UntypedActionResultHolderBase {
1364 public:
1365 virtual ~UntypedActionResultHolderBase() {}
1366
1367 // Prints the held value as an action's result to os.
1368 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1369};
1370
1371// This generic definition is used when T is not void.
1372template <typename T>
1373class ActionResultHolder : public UntypedActionResultHolderBase {
1374 public:
1375 // Returns the held value. Must not be called more than once.
1376 T Unwrap() {
1377 return result_.Unwrap();
1378 }
1379
1380 // Prints the held value as an action's result to os.
1381 void PrintAsActionResult(::std::ostream* os) const override {
1382 *os << "\n Returns: ";
1383 // T may be a reference type, so we don't use UniversalPrint().
1384 UniversalPrinter<T>::Print(result_.Peek(), os);
1385 }
1386
1387 // Performs the given mock function's default action and returns the
1388 // result in a new-ed ActionResultHolder.
1389 template <typename F>
1390 static ActionResultHolder* PerformDefaultAction(
1391 const FunctionMocker<F>* func_mocker,
1392 typename Function<F>::ArgumentTuple&& args,
1393 const std::string& call_description) {
1394 return new ActionResultHolder(Wrapper(func_mocker->PerformDefaultAction(
1395 std::move(args), call_description)));
1396 }
1397
1398 // Performs the given action and returns the result in a new-ed
1399 // ActionResultHolder.
1400 template <typename F>
1401 static ActionResultHolder* PerformAction(
1402 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
1403 return new ActionResultHolder(
1404 Wrapper(action.Perform(std::move(args))));
1405 }
1406
1407 private:
1408 typedef ReferenceOrValueWrapper<T> Wrapper;
1409
1410 explicit ActionResultHolder(Wrapper result)
1411 : result_(std::move(result)) {
1412 }
1413
1414 Wrapper result_;
1415
1416 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1417};
1418
1419// Specialization for T = void.
1420template <>
1421class ActionResultHolder<void> : public UntypedActionResultHolderBase {
1422 public:
1423 void Unwrap() { }
1424
1425 void PrintAsActionResult(::std::ostream* /* os */) const override {}
1426
1427 // Performs the given mock function's default action and returns ownership
1428 // of an empty ActionResultHolder*.
1429 template <typename F>
1430 static ActionResultHolder* PerformDefaultAction(
1431 const FunctionMocker<F>* func_mocker,
1432 typename Function<F>::ArgumentTuple&& args,
1433 const std::string& call_description) {
1434 func_mocker->PerformDefaultAction(std::move(args), call_description);
1435 return new ActionResultHolder;
1436 }
1437
1438 // Performs the given action and returns ownership of an empty
1439 // ActionResultHolder*.
1440 template <typename F>
1441 static ActionResultHolder* PerformAction(
1442 const Action<F>& action, typename Function<F>::ArgumentTuple&& args) {
1443 action.Perform(std::move(args));
1444 return new ActionResultHolder;
1445 }
1446
1447 private:
1448 ActionResultHolder() {}
1449 GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder);
1450};
1451
1452template <typename F>
1453class FunctionMocker;
1454
1455template <typename R, typename... Args>
1456class FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {
1457 using F = R(Args...);
1458
1459 public:
1460 using Result = R;
1461 using ArgumentTuple = std::tuple<Args...>;
1462 using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;
1463
1464 FunctionMocker() {}
1465
1466 // There is no generally useful and implementable semantics of
1467 // copying a mock object, so copying a mock is usually a user error.
1468 // Thus we disallow copying function mockers. If the user really
1469 // wants to copy a mock object, they should implement their own copy
1470 // operation, for example:
1471 //
1472 // class MockFoo : public Foo {
1473 // public:
1474 // // Defines a copy constructor explicitly.
1475 // MockFoo(const MockFoo& src) {}
1476 // ...
1477 // };
1478 FunctionMocker(const FunctionMocker&) = delete;
1479 FunctionMocker& operator=(const FunctionMocker&) = delete;
1480
1481 // The destructor verifies that all expectations on this mock
1482 // function have been satisfied. If not, it will report Google Test
1483 // non-fatal failures for the violations.
1484 ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1485 MutexLock l(&g_gmock_mutex);
1486 VerifyAndClearExpectationsLocked();
1487 Mock::UnregisterLocked(this);
1488 ClearDefaultActionsLocked();
1489 }
1490
1491 // Returns the ON_CALL spec that matches this mock function with the
1492 // given arguments; returns NULL if no matching ON_CALL is found.
1493 // L = *
1494 const OnCallSpec<F>* FindOnCallSpec(
1495 const ArgumentTuple& args) const {
1496 for (UntypedOnCallSpecs::const_reverse_iterator it
1497 = untyped_on_call_specs_.rbegin();
1498 it != untyped_on_call_specs_.rend(); ++it) {
1499 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1500 if (spec->Matches(args))
1501 return spec;
1502 }
1503
1504 return nullptr;
1505 }
1506
1507 // Performs the default action of this mock function on the given
1508 // arguments and returns the result. Asserts (or throws if
1509 // exceptions are enabled) with a helpful call descrption if there
1510 // is no valid return value. This method doesn't depend on the
1511 // mutable state of this object, and thus can be called concurrently
1512 // without locking.
1513 // L = *
1514 Result PerformDefaultAction(ArgumentTuple&& args,
1515 const std::string& call_description) const {
1516 const OnCallSpec<F>* const spec =
1517 this->FindOnCallSpec(args);
1518 if (spec != nullptr) {
1519 return spec->GetAction().Perform(std::move(args));
1520 }
1521 const std::string message =
1522 call_description +
1523 "\n The mock function has no default action "
1524 "set, and its return type has no default value set.";
1525#if GTEST_HAS_EXCEPTIONS
1526 if (!DefaultValue<Result>::Exists()) {
1527 throw std::runtime_error(message);
1528 }
1529#else
1530 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1531#endif
1532 return DefaultValue<Result>::Get();
1533 }
1534
1535 // Performs the default action with the given arguments and returns
1536 // the action's result. The call description string will be used in
1537 // the error message to describe the call in the case the default
1538 // action fails. The caller is responsible for deleting the result.
1539 // L = *
1540 UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1541 void* untyped_args, // must point to an ArgumentTuple
1542 const std::string& call_description) const override {
1543 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1544 return ResultHolder::PerformDefaultAction(this, std::move(*args),
1545 call_description);
1546 }
1547
1548 // Performs the given action with the given arguments and returns
1549 // the action's result. The caller is responsible for deleting the
1550 // result.
1551 // L = *
1552 UntypedActionResultHolderBase* UntypedPerformAction(
1553 const void* untyped_action, void* untyped_args) const override {
1554 // Make a copy of the action before performing it, in case the
1555 // action deletes the mock object (and thus deletes itself).
1556 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1557 ArgumentTuple* args = static_cast<ArgumentTuple*>(untyped_args);
1558 return ResultHolder::PerformAction(action, std::move(*args));
1559 }
1560
1561 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1562 // clears the ON_CALL()s set on this mock function.
1563 void ClearDefaultActionsLocked() override
1564 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1565 g_gmock_mutex.AssertHeld();
1566
1567 // Deleting our default actions may trigger other mock objects to be
1568 // deleted, for example if an action contains a reference counted smart
1569 // pointer to that mock object, and that is the last reference. So if we
1570 // delete our actions within the context of the global mutex we may deadlock
1571 // when this method is called again. Instead, make a copy of the set of
1572 // actions to delete, clear our set within the mutex, and then delete the
1573 // actions outside of the mutex.
1574 UntypedOnCallSpecs specs_to_delete;
1575 untyped_on_call_specs_.swap(specs_to_delete);
1576
1577 g_gmock_mutex.Unlock();
1578 for (UntypedOnCallSpecs::const_iterator it =
1579 specs_to_delete.begin();
1580 it != specs_to_delete.end(); ++it) {
1581 delete static_cast<const OnCallSpec<F>*>(*it);
1582 }
1583
1584 // Lock the mutex again, since the caller expects it to be locked when we
1585 // return.
1586 g_gmock_mutex.Lock();
1587 }
1588
1589 // Returns the result of invoking this mock function with the given
1590 // arguments. This function can be safely called from multiple
1591 // threads concurrently.
1592 Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1593 ArgumentTuple tuple(std::forward<Args>(args)...);
1594 std::unique_ptr<ResultHolder> holder(DownCast_<ResultHolder*>(
1595 this->UntypedInvokeWith(static_cast<void*>(&tuple))));
1596 return holder->Unwrap();
1597 }
1598
1599 MockSpec<F> With(Matcher<Args>... m) {
1600 return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));
1601 }
1602
1603 protected:
1604 template <typename Function>
1605 friend class MockSpec;
1606
1607 typedef ActionResultHolder<Result> ResultHolder;
1608
1609 // Adds and returns a default action spec for this mock function.
1610 OnCallSpec<F>& AddNewOnCallSpec(
1611 const char* file, int line,
1612 const ArgumentMatcherTuple& m)
1613 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1614 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1615 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1616 untyped_on_call_specs_.push_back(on_call_spec);
1617 return *on_call_spec;
1618 }
1619
1620 // Adds and returns an expectation spec for this mock function.
1621 TypedExpectation<F>& AddNewExpectation(const char* file, int line,
1622 const std::string& source_text,
1623 const ArgumentMatcherTuple& m)
1624 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1625 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
1626 TypedExpectation<F>* const expectation =
1627 new TypedExpectation<F>(this, file, line, source_text, m);
1628 const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);
1629 // See the definition of untyped_expectations_ for why access to
1630 // it is unprotected here.
1631 untyped_expectations_.push_back(untyped_expectation);
1632
1633 // Adds this expectation into the implicit sequence if there is one.
1634 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1635 if (implicit_sequence != nullptr) {
1636 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
1637 }
1638
1639 return *expectation;
1640 }
1641
1642 private:
1643 template <typename Func> friend class TypedExpectation;
1644
1645 // Some utilities needed for implementing UntypedInvokeWith().
1646
1647 // Describes what default action will be performed for the given
1648 // arguments.
1649 // L = *
1650 void DescribeDefaultActionTo(const ArgumentTuple& args,
1651 ::std::ostream* os) const {
1652 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
1653
1654 if (spec == nullptr) {
1655 *os << (internal::type_equals<Result, void>::value ?
1656 "returning directly.\n" :
1657 "returning default value.\n");
1658 } else {
1659 *os << "taking default action specified at:\n"
1660 << FormatFileLocation(spec->file(), spec->line()) << "\n";
1661 }
1662 }
1663
1664 // Writes a message that the call is uninteresting (i.e. neither
1665 // explicitly expected nor explicitly unexpected) to the given
1666 // ostream.
1667 void UntypedDescribeUninterestingCall(const void* untyped_args,
1668 ::std::ostream* os) const override
1669 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1670 const ArgumentTuple& args =
1671 *static_cast<const ArgumentTuple*>(untyped_args);
1672 *os << "Uninteresting mock function call - ";
1673 DescribeDefaultActionTo(args, os);
1674 *os << " Function call: " << Name();
1675 UniversalPrint(args, os);
1676 }
1677
1678 // Returns the expectation that matches the given function arguments
1679 // (or NULL is there's no match); when a match is found,
1680 // untyped_action is set to point to the action that should be
1681 // performed (or NULL if the action is "do default"), and
1682 // is_excessive is modified to indicate whether the call exceeds the
1683 // expected number.
1684 //
1685 // Critical section: We must find the matching expectation and the
1686 // corresponding action that needs to be taken in an ATOMIC
1687 // transaction. Otherwise another thread may call this mock
1688 // method in the middle and mess up the state.
1689 //
1690 // However, performing the action has to be left out of the critical
1691 // section. The reason is that we have no control on what the
1692 // action does (it can invoke an arbitrary user function or even a
1693 // mock function) and excessive locking could cause a dead lock.
1694 const ExpectationBase* UntypedFindMatchingExpectation(
1695 const void* untyped_args, const void** untyped_action, bool* is_excessive,
1696 ::std::ostream* what, ::std::ostream* why) override
1697 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
1698 const ArgumentTuple& args =
1699 *static_cast<const ArgumentTuple*>(untyped_args);
1700 MutexLock l(&g_gmock_mutex);
1701 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1702 if (exp == nullptr) { // A match wasn't found.
1703 this->FormatUnexpectedCallMessageLocked(args, what, why);
1704 return nullptr;
1705 }
1706
1707 // This line must be done before calling GetActionForArguments(),
1708 // which will increment the call count for *exp and thus affect
1709 // its saturation status.
1710 *is_excessive = exp->IsSaturated();
1711 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1712 if (action != nullptr && action->IsDoDefault())
1713 action = nullptr; // Normalize "do default" to NULL.
1714 *untyped_action = action;
1715 return exp;
1716 }
1717
1718 // Prints the given function arguments to the ostream.
1719 void UntypedPrintArgs(const void* untyped_args,
1720 ::std::ostream* os) const override {
1721 const ArgumentTuple& args =
1722 *static_cast<const ArgumentTuple*>(untyped_args);
1723 UniversalPrint(args, os);
1724 }
1725
1726 // Returns the expectation that matches the arguments, or NULL if no
1727 // expectation matches them.
1728 TypedExpectation<F>* FindMatchingExpectationLocked(
1729 const ArgumentTuple& args) const
1730 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1731 g_gmock_mutex.AssertHeld();
1732 // See the definition of untyped_expectations_ for why access to
1733 // it is unprotected here.
1734 for (typename UntypedExpectations::const_reverse_iterator it =
1735 untyped_expectations_.rbegin();
1736 it != untyped_expectations_.rend(); ++it) {
1737 TypedExpectation<F>* const exp =
1738 static_cast<TypedExpectation<F>*>(it->get());
1739 if (exp->ShouldHandleArguments(args)) {
1740 return exp;
1741 }
1742 }
1743 return nullptr;
1744 }
1745
1746 // Returns a message that the arguments don't match any expectation.
1747 void FormatUnexpectedCallMessageLocked(
1748 const ArgumentTuple& args,
1749 ::std::ostream* os,
1750 ::std::ostream* why) const
1751 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1752 g_gmock_mutex.AssertHeld();
1753 *os << "\nUnexpected mock function call - ";
1754 DescribeDefaultActionTo(args, os);
1755 PrintTriedExpectationsLocked(args, why);
1756 }
1757
1758 // Prints a list of expectations that have been tried against the
1759 // current mock function call.
1760 void PrintTriedExpectationsLocked(
1761 const ArgumentTuple& args,
1762 ::std::ostream* why) const
1763 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
1764 g_gmock_mutex.AssertHeld();
1765 const size_t count = untyped_expectations_.size();
1766 *why << "Google Mock tried the following " << count << " "
1767 << (count == 1 ? "expectation, but it didn't match" :
1768 "expectations, but none matched")
1769 << ":\n";
1770 for (size_t i = 0; i < count; i++) {
1771 TypedExpectation<F>* const expectation =
1772 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
1773 *why << "\n";
1774 expectation->DescribeLocationTo(why);
1775 if (count > 1) {
1776 *why << "tried expectation #" << i << ": ";
1777 }
1778 *why << expectation->source_text() << "...\n";
1779 expectation->ExplainMatchResultTo(args, why);
1780 expectation->DescribeCallCountTo(why);
1781 }
1782 }
1783}; // class FunctionMocker
1784
1785GTEST_DISABLE_MSC_WARNINGS_POP_() // 4355
1786
1787// Reports an uninteresting call (whose description is in msg) in the
1788// manner specified by 'reaction'.
1789void ReportUninterestingCall(CallReaction reaction, const std::string& msg);
1790
1791} // namespace internal
1792
1793// A MockFunction<F> class has one mock method whose type is F. It is
1794// useful when you just want your test code to emit some messages and
1795// have Google Mock verify the right messages are sent (and perhaps at
1796// the right times). For example, if you are exercising code:
1797//
1798// Foo(1);
1799// Foo(2);
1800// Foo(3);
1801//
1802// and want to verify that Foo(1) and Foo(3) both invoke
1803// mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write:
1804//
1805// TEST(FooTest, InvokesBarCorrectly) {
1806// MyMock mock;
1807// MockFunction<void(string check_point_name)> check;
1808// {
1809// InSequence s;
1810//
1811// EXPECT_CALL(mock, Bar("a"));
1812// EXPECT_CALL(check, Call("1"));
1813// EXPECT_CALL(check, Call("2"));
1814// EXPECT_CALL(mock, Bar("a"));
1815// }
1816// Foo(1);
1817// check.Call("1");
1818// Foo(2);
1819// check.Call("2");
1820// Foo(3);
1821// }
1822//
1823// The expectation spec says that the first Bar("a") must happen
1824// before check point "1", the second Bar("a") must happen after check
1825// point "2", and nothing should happen between the two check
1826// points. The explicit check points make it easy to tell which
1827// Bar("a") is called by which call to Foo().
1828//
1829// MockFunction<F> can also be used to exercise code that accepts
1830// std::function<F> callbacks. To do so, use AsStdFunction() method
1831// to create std::function proxy forwarding to original object's Call.
1832// Example:
1833//
1834// TEST(FooTest, RunsCallbackWithBarArgument) {
1835// MockFunction<int(string)> callback;
1836// EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1));
1837// Foo(callback.AsStdFunction());
1838// }
1839template <typename F>
1840class MockFunction;
1841
1842template <typename R, typename... Args>
1843class MockFunction<R(Args...)> {
1844 public:
1845 MockFunction() {}
1846 MockFunction(const MockFunction&) = delete;
1847 MockFunction& operator=(const MockFunction&) = delete;
1848
1849 std::function<R(Args...)> AsStdFunction() {
1850 return [this](Args... args) -> R {
1851 return this->Call(std::forward<Args>(args)...);
1852 };
1853 }
1854
1855 // Implementation detail: the expansion of the MOCK_METHOD macro.
1856 R Call(Args... args) {
1857 mock_.SetOwnerAndName(this, "Call");
1858 return mock_.Invoke(std::forward<Args>(args)...);
1859 }
1860
1861 internal::MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {
1862 mock_.RegisterOwner(this);
1863 return mock_.With(std::move(m)...);
1864 }
1865
1866 internal::MockSpec<R(Args...)> gmock_Call(const internal::WithoutMatchers&,
1867 R (*)(Args...)) {
1868 return this->gmock_Call(::testing::A<Args>()...);
1869 }
1870
1871 private:
1872 mutable internal::FunctionMocker<R(Args...)> mock_;
1873};
1874
1875// The style guide prohibits "using" statements in a namespace scope
1876// inside a header file. However, the MockSpec class template is
1877// meant to be defined in the ::testing namespace. The following line
1878// is just a trick for working around a bug in MSVC 8.0, which cannot
1879// handle it if we define MockSpec in ::testing.
1880using internal::MockSpec;
1881
1882// Const(x) is a convenient function for obtaining a const reference
1883// to x. This is useful for setting expectations on an overloaded
1884// const mock method, e.g.
1885//
1886// class MockFoo : public FooInterface {
1887// public:
1888// MOCK_METHOD0(Bar, int());
1889// MOCK_CONST_METHOD0(Bar, int&());
1890// };
1891//
1892// MockFoo foo;
1893// // Expects a call to non-const MockFoo::Bar().
1894// EXPECT_CALL(foo, Bar());
1895// // Expects a call to const MockFoo::Bar().
1896// EXPECT_CALL(Const(foo), Bar());
1897template <typename T>
1898inline const T& Const(const T& x) { return x; }
1899
1900// Constructs an Expectation object that references and co-owns exp.
1901inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1902 : expectation_base_(exp.GetHandle().expectation_base()) {}
1903
1904} // namespace testing
1905
1906GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
1907
1908// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is
1909// required to avoid compile errors when the name of the method used in call is
1910// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro
1911// tests in internal/gmock-spec-builders_test.cc for more details.
1912//
1913// This macro supports statements both with and without parameter matchers. If
1914// the parameter list is omitted, gMock will accept any parameters, which allows
1915// tests to be written that don't need to encode the number of method
1916// parameter. This technique may only be used for non-overloaded methods.
1917//
1918// // These are the same:
1919// ON_CALL(mock, NoArgsMethod()).WillByDefault(...);
1920// ON_CALL(mock, NoArgsMethod).WillByDefault(...);
1921//
1922// // As are these:
1923// ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);
1924// ON_CALL(mock, TwoArgsMethod).WillByDefault(...);
1925//
1926// // Can also specify args if you want, of course:
1927// ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);
1928//
1929// // Overloads work as long as you specify parameters:
1930// ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);
1931// ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);
1932//
1933// // Oops! Which overload did you want?
1934// ON_CALL(mock, OverloadedMethod).WillByDefault(...);
1935// => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous
1936//
1937// How this works: The mock class uses two overloads of the gmock_Method
1938// expectation setter method plus an operator() overload on the MockSpec object.
1939// In the matcher list form, the macro expands to:
1940//
1941// // This statement:
1942// ON_CALL(mock, TwoArgsMethod(_, 45))...
1943//
1944// // ...expands to:
1945// mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...
1946// |-------------v---------------||------------v-------------|
1947// invokes first overload swallowed by operator()
1948//
1949// // ...which is essentially:
1950// mock.gmock_TwoArgsMethod(_, 45)...
1951//
1952// Whereas the form without a matcher list:
1953//
1954// // This statement:
1955// ON_CALL(mock, TwoArgsMethod)...
1956//
1957// // ...expands to:
1958// mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...
1959// |-----------------------v--------------------------|
1960// invokes second overload
1961//
1962// // ...which is essentially:
1963// mock.gmock_TwoArgsMethod(_, _)...
1964//
1965// The WithoutMatchers() argument is used to disambiguate overloads and to
1966// block the caller from accidentally invoking the second overload directly. The
1967// second argument is an internal type derived from the method signature. The
1968// failure to disambiguate two overloads of this method in the ON_CALL statement
1969// is how we block callers from setting expectations on overloaded methods.
1970#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call) \
1971 ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
1972 nullptr) \
1973 .Setter(__FILE__, __LINE__, #mock_expr, #call)
1974
1975#define ON_CALL(obj, call) \
1976 GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)
1977
1978#define EXPECT_CALL(obj, call) \
1979 GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
1980
1981#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
1982