blob: 4c2dca98bafc1ea77bd8e0aafffce2342e0f90be [file] [log] [blame]
shiqiane35fdd92008-12-10 05:08:54 +00001// 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// Author: wan@google.com (Zhanyong Wan)
31
32// Google Mock - a framework for writing C++ mock classes.
33//
34// This file implements the ON_CALL() and EXPECT_CALL() macros.
35//
36// A user can use the ON_CALL() macro to specify the default action of
37// a mock method. The syntax is:
38//
39// ON_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000040// .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +000041// .WillByDefault(action);
42//
zhanyong.wanbf550852009-06-09 06:09:53 +000043// where the .With() clause is optional.
shiqiane35fdd92008-12-10 05:08:54 +000044//
45// A user can use the EXPECT_CALL() macro to specify an expectation on
46// a mock method. The syntax is:
47//
48// EXPECT_CALL(mock_object, Method(argument-matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +000049// .With(multi-argument-matchers)
shiqiane35fdd92008-12-10 05:08:54 +000050// .Times(cardinality)
51// .InSequence(sequences)
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000052// .After(expectations)
shiqiane35fdd92008-12-10 05:08:54 +000053// .WillOnce(action)
54// .WillRepeatedly(action)
55// .RetiresOnSaturation();
56//
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000057// where all clauses are optional, and .InSequence()/.After()/
58// .WillOnce() can appear any number of times.
shiqiane35fdd92008-12-10 05:08:54 +000059
60#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
61#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
62
63#include <map>
64#include <set>
65#include <sstream>
66#include <string>
67#include <vector>
68
zhanyong.wanedd4ab42013-02-28 22:58:51 +000069#if GTEST_HAS_EXCEPTIONS
70# include <stdexcept> // NOLINT
71#endif
72
zhanyong.wan53e08c42010-09-14 05:38:21 +000073#include "gmock/gmock-actions.h"
74#include "gmock/gmock-cardinalities.h"
75#include "gmock/gmock-matchers.h"
76#include "gmock/internal/gmock-internal-utils.h"
77#include "gmock/internal/gmock-port.h"
78#include "gtest/gtest.h"
shiqiane35fdd92008-12-10 05:08:54 +000079
80namespace testing {
81
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000082// An abstract handle of an expectation.
83class Expectation;
84
85// A set of expectation handles.
86class ExpectationSet;
87
shiqiane35fdd92008-12-10 05:08:54 +000088// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION
89// and MUST NOT BE USED IN USER CODE!!!
90namespace internal {
91
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000092// Implements a mock function.
93template <typename F> class FunctionMocker;
shiqiane35fdd92008-12-10 05:08:54 +000094
95// Base class for expectations.
96class ExpectationBase;
97
zhanyong.wan41b9b0b2009-07-01 19:04:51 +000098// Implements an expectation.
99template <typename F> class TypedExpectation;
100
shiqiane35fdd92008-12-10 05:08:54 +0000101// Helper class for testing the Expectation class template.
102class ExpectationTester;
103
104// Base class for function mockers.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000105template <typename F> class FunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000106
shiqiane35fdd92008-12-10 05:08:54 +0000107// Protects the mock object registry (in class Mock), all function
108// mockers, and all expectations.
109//
110// The reason we don't use more fine-grained protection is: when a
111// mock function Foo() is called, it needs to consult its expectations
112// to see which one should be picked. If another thread is allowed to
113// call a mock function (either Foo() or a different one) at the same
114// time, it could affect the "retired" attributes of Foo()'s
115// expectations when InSequence() is used, and thus affect which
116// expectation gets picked. Therefore, we sequence all mock function
117// calls to ensure the integrity of the mock objects' states.
vladlosev587c1b32011-05-20 00:42:22 +0000118GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000119
zhanyong.waned6c9272011-02-23 19:39:27 +0000120// Untyped base class for ActionResultHolder<R>.
121class UntypedActionResultHolderBase;
122
shiqiane35fdd92008-12-10 05:08:54 +0000123// Abstract base class of FunctionMockerBase. This is the
124// type-agnostic part of the function mocker interface. Its pure
125// virtual methods are implemented by FunctionMockerBase.
vladlosev587c1b32011-05-20 00:42:22 +0000126class GTEST_API_ UntypedFunctionMockerBase {
shiqiane35fdd92008-12-10 05:08:54 +0000127 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000128 UntypedFunctionMockerBase();
129 virtual ~UntypedFunctionMockerBase();
shiqiane35fdd92008-12-10 05:08:54 +0000130
131 // Verifies that all expectations on this mock function have been
132 // satisfied. Reports one or more Google Test non-fatal failures
133 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000134 bool VerifyAndClearExpectationsLocked()
135 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000136
137 // Clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000138 virtual void ClearDefaultActionsLocked()
139 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000140
141 // In all of the following Untyped* functions, it's the caller's
142 // responsibility to guarantee the correctness of the arguments'
143 // types.
144
145 // Performs the default action with the given arguments and returns
146 // the action's result. The call description string will be used in
147 // the error message to describe the call in the case the default
148 // action fails.
149 // L = *
150 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
151 const void* untyped_args,
152 const string& call_description) const = 0;
153
154 // Performs the given action with the given arguments and returns
155 // the action's result.
156 // L = *
157 virtual UntypedActionResultHolderBase* UntypedPerformAction(
158 const void* untyped_action,
159 const 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.
vladlosev4d60a592011-10-24 21:16:22 +0000164 virtual void UntypedDescribeUninterestingCall(
165 const void* untyped_args,
166 ::std::ostream* os) const
167 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000168
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.
zhanyong.waned6c9272011-02-23 19:39:27 +0000175 virtual const ExpectationBase* UntypedFindMatchingExpectation(
176 const void* untyped_args,
177 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +0000178 ::std::ostream* what, ::std::ostream* why)
179 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;
zhanyong.waned6c9272011-02-23 19:39:27 +0000180
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 // TODO(wan@google.com): rename to SetAndRegisterOwner().
vladlosev4d60a592011-10-24 21:16:22 +0000190 void RegisterOwner(const void* mock_obj)
191 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000192
193 // Sets the mock object this mock method belongs to, and sets the
194 // name of the mock function. Will be called upon each invocation
195 // of this mock function.
vladlosev4d60a592011-10-24 21:16:22 +0000196 void SetOwnerAndName(const void* mock_obj, const char* name)
197 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000198
199 // Returns the mock object this mock method belongs to. Must be
200 // called after RegisterOwner() or SetOwnerAndName() has been
201 // called.
vladlosev4d60a592011-10-24 21:16:22 +0000202 const void* MockObject() const
203 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000204
205 // Returns the name of this mock method. Must be called after
206 // SetOwnerAndName() has been called.
vladlosev4d60a592011-10-24 21:16:22 +0000207 const char* Name() const
208 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000209
210 // Returns the result of invoking this mock function with the given
211 // arguments. This function can be safely called from multiple
212 // threads concurrently. The caller is responsible for deleting the
213 // result.
zhanyong.waned6c9272011-02-23 19:39:27 +0000214 const UntypedActionResultHolderBase* UntypedInvokeWith(
vladlosev4d60a592011-10-24 21:16:22 +0000215 const void* untyped_args)
216 GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000217
218 protected:
219 typedef std::vector<const void*> UntypedOnCallSpecs;
220
221 typedef std::vector<internal::linked_ptr<ExpectationBase> >
222 UntypedExpectations;
223
224 // Returns an Expectation object that references and co-owns exp,
225 // which must be an expectation on this mock function.
226 Expectation GetHandleOf(ExpectationBase* exp);
227
228 // Address of the mock object this mock method belongs to. Only
229 // valid after this mock method has been called or
230 // ON_CALL/EXPECT_CALL has been invoked on it.
231 const void* mock_obj_; // Protected by g_gmock_mutex.
232
233 // Name of the function being mocked. Only valid after this mock
234 // method has been called.
235 const char* name_; // Protected by g_gmock_mutex.
236
237 // All default action specs for this function mocker.
238 UntypedOnCallSpecs untyped_on_call_specs_;
239
240 // All expectations for this function mocker.
241 UntypedExpectations untyped_expectations_;
shiqiane35fdd92008-12-10 05:08:54 +0000242}; // class UntypedFunctionMockerBase
243
zhanyong.waned6c9272011-02-23 19:39:27 +0000244// Untyped base class for OnCallSpec<F>.
245class UntypedOnCallSpecBase {
shiqiane35fdd92008-12-10 05:08:54 +0000246 public:
zhanyong.waned6c9272011-02-23 19:39:27 +0000247 // The arguments are the location of the ON_CALL() statement.
248 UntypedOnCallSpecBase(const char* a_file, int a_line)
249 : file_(a_file), line_(a_line), last_clause_(kNone) {}
shiqiane35fdd92008-12-10 05:08:54 +0000250
251 // Where in the source file was the default action spec defined?
252 const char* file() const { return file_; }
253 int line() const { return line_; }
254
zhanyong.waned6c9272011-02-23 19:39:27 +0000255 protected:
256 // Gives each clause in the ON_CALL() statement a name.
257 enum Clause {
258 // Do not change the order of the enum members! The run-time
259 // syntax checking relies on it.
260 kNone,
261 kWith,
vladlosevab29bb62011-04-08 01:32:32 +0000262 kWillByDefault
zhanyong.waned6c9272011-02-23 19:39:27 +0000263 };
264
265 // Asserts that the ON_CALL() statement has a certain property.
266 void AssertSpecProperty(bool property, const string& failure_message) const {
267 Assert(property, file_, line_, failure_message);
268 }
269
270 // Expects that the ON_CALL() statement has a certain property.
271 void ExpectSpecProperty(bool property, const string& failure_message) const {
272 Expect(property, file_, line_, failure_message);
273 }
274
275 const char* file_;
276 int line_;
277
278 // The last clause in the ON_CALL() statement as seen so far.
279 // Initially kNone and changes as the statement is parsed.
280 Clause last_clause_;
281}; // class UntypedOnCallSpecBase
282
283// This template class implements an ON_CALL spec.
284template <typename F>
285class OnCallSpec : public UntypedOnCallSpecBase {
286 public:
287 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
288 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
289
290 // Constructs an OnCallSpec object from the information inside
291 // the parenthesis of an ON_CALL() statement.
292 OnCallSpec(const char* a_file, int a_line,
293 const ArgumentMatcherTuple& matchers)
294 : UntypedOnCallSpecBase(a_file, a_line),
295 matchers_(matchers),
296 // By default, extra_matcher_ should match anything. However,
297 // we cannot initialize it with _ as that triggers a compiler
298 // bug in Symbian's C++ compiler (cannot decide between two
299 // overloaded constructors of Matcher<const ArgumentTuple&>).
300 extra_matcher_(A<const ArgumentTuple&>()) {
301 }
302
zhanyong.wanbf550852009-06-09 06:09:53 +0000303 // Implements the .With() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000304 OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {
shiqiane35fdd92008-12-10 05:08:54 +0000305 // Makes sure this is called at most once.
zhanyong.wanbf550852009-06-09 06:09:53 +0000306 ExpectSpecProperty(last_clause_ < kWith,
307 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000308 "more than once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000309 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000310
311 extra_matcher_ = m;
312 return *this;
313 }
314
315 // Implements the .WillByDefault() clause.
zhanyong.waned6c9272011-02-23 19:39:27 +0000316 OnCallSpec& WillByDefault(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000317 ExpectSpecProperty(last_clause_ < kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000318 ".WillByDefault() must appear "
319 "exactly once in an ON_CALL().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000320 last_clause_ = kWillByDefault;
shiqiane35fdd92008-12-10 05:08:54 +0000321
322 ExpectSpecProperty(!action.IsDoDefault(),
323 "DoDefault() cannot be used in ON_CALL().");
324 action_ = action;
325 return *this;
326 }
327
328 // Returns true iff the given arguments match the matchers.
329 bool Matches(const ArgumentTuple& args) const {
330 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
331 }
332
333 // Returns the action specified by the user.
334 const Action<F>& GetAction() const {
zhanyong.wanbf550852009-06-09 06:09:53 +0000335 AssertSpecProperty(last_clause_ == kWillByDefault,
shiqiane35fdd92008-12-10 05:08:54 +0000336 ".WillByDefault() must appear exactly "
337 "once in an ON_CALL().");
338 return action_;
339 }
zhanyong.wan32de5f52009-12-23 00:13:23 +0000340
shiqiane35fdd92008-12-10 05:08:54 +0000341 private:
shiqiane35fdd92008-12-10 05:08:54 +0000342 // The information in statement
343 //
344 // ON_CALL(mock_object, Method(matchers))
zhanyong.wanbf550852009-06-09 06:09:53 +0000345 // .With(multi-argument-matcher)
shiqiane35fdd92008-12-10 05:08:54 +0000346 // .WillByDefault(action);
347 //
348 // is recorded in the data members like this:
349 //
350 // source file that contains the statement => file_
351 // line number of the statement => line_
352 // matchers => matchers_
353 // multi-argument-matcher => extra_matcher_
354 // action => action_
shiqiane35fdd92008-12-10 05:08:54 +0000355 ArgumentMatcherTuple matchers_;
356 Matcher<const ArgumentTuple&> extra_matcher_;
357 Action<F> action_;
zhanyong.waned6c9272011-02-23 19:39:27 +0000358}; // class OnCallSpec
shiqiane35fdd92008-12-10 05:08:54 +0000359
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000360// Possible reactions on uninteresting calls.
shiqiane35fdd92008-12-10 05:08:54 +0000361enum CallReaction {
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000362 kAllow,
363 kWarn,
364 kFail
shiqiane35fdd92008-12-10 05:08:54 +0000365};
366
367} // namespace internal
368
369// Utilities for manipulating mock objects.
vladlosev587c1b32011-05-20 00:42:22 +0000370class GTEST_API_ Mock {
shiqiane35fdd92008-12-10 05:08:54 +0000371 public:
372 // The following public methods can be called concurrently.
373
zhanyong.wandf35a762009-04-22 22:25:31 +0000374 // Tells Google Mock to ignore mock_obj when checking for leaked
375 // mock objects.
vladlosev4d60a592011-10-24 21:16:22 +0000376 static void AllowLeak(const void* mock_obj)
377 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000378
shiqiane35fdd92008-12-10 05:08:54 +0000379 // Verifies and clears all expectations on the given mock object.
380 // If the expectations aren't satisfied, generates one or more
381 // Google Test non-fatal failures and returns false.
vladlosev4d60a592011-10-24 21:16:22 +0000382 static bool VerifyAndClearExpectations(void* mock_obj)
383 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000384
385 // Verifies all expectations on the given mock object and clears its
386 // default actions and expectations. Returns true iff the
387 // verification was successful.
vladlosev4d60a592011-10-24 21:16:22 +0000388 static bool VerifyAndClear(void* mock_obj)
389 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
jgm79a367e2012-04-10 16:02:11 +0000390
shiqiane35fdd92008-12-10 05:08:54 +0000391 private:
zhanyong.waned6c9272011-02-23 19:39:27 +0000392 friend class internal::UntypedFunctionMockerBase;
393
shiqiane35fdd92008-12-10 05:08:54 +0000394 // Needed for a function mocker to register itself (so that we know
395 // how to clear a mock object).
396 template <typename F>
397 friend class internal::FunctionMockerBase;
398
shiqiane35fdd92008-12-10 05:08:54 +0000399 template <typename M>
400 friend class NiceMock;
401
402 template <typename M>
zhanyong.wan844fa942013-03-01 01:54:22 +0000403 friend class NaggyMock;
404
405 template <typename M>
shiqiane35fdd92008-12-10 05:08:54 +0000406 friend class StrictMock;
407
408 // Tells Google Mock to allow uninteresting calls on the given mock
409 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000410 static void AllowUninterestingCalls(const void* mock_obj)
411 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000412
413 // Tells Google Mock to warn the user about uninteresting calls on
414 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000415 static void WarnUninterestingCalls(const void* mock_obj)
416 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000417
418 // Tells Google Mock to fail uninteresting calls on the given mock
419 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000420 static void FailUninterestingCalls(const void* mock_obj)
421 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000422
423 // Tells Google Mock the given mock object is being destroyed and
424 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000425 static void UnregisterCallReaction(const void* mock_obj)
426 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000427
428 // Returns the reaction Google Mock will have on uninteresting calls
429 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000430 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000431 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000432 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000433
434 // Verifies that all expectations on the given mock object have been
435 // satisfied. Reports one or more Google Test non-fatal failures
436 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000437 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
438 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000439
440 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000441 static void ClearDefaultActionsLocked(void* mock_obj)
442 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000443
444 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000445 static void Register(
446 const void* mock_obj,
447 internal::UntypedFunctionMockerBase* mocker)
448 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000449
zhanyong.wandf35a762009-04-22 22:25:31 +0000450 // Tells Google Mock where in the source code mock_obj is used in an
451 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
452 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000453 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000454 const void* mock_obj, const char* file, int line)
455 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000456
shiqiane35fdd92008-12-10 05:08:54 +0000457 // Unregisters a mock method; removes the owning mock object from
458 // the registry when the last mock method associated with it has
459 // been unregistered. This is called only in the destructor of
460 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000461 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
462 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000463}; // class Mock
464
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000465// An abstract handle of an expectation. Useful in the .After()
466// clause of EXPECT_CALL() for setting the (partial) order of
467// expectations. The syntax:
468//
469// Expectation e1 = EXPECT_CALL(...)...;
470// EXPECT_CALL(...).After(e1)...;
471//
472// sets two expectations where the latter can only be matched after
473// the former has been satisfied.
474//
475// Notes:
476// - This class is copyable and has value semantics.
477// - Constness is shallow: a const Expectation object itself cannot
478// be modified, but the mutable methods of the ExpectationBase
479// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000480// - The constructors and destructor are defined out-of-line because
481// the Symbian WINSCW compiler wants to otherwise instantiate them
482// when it sees this class definition, at which point it doesn't have
483// ExpectationBase available yet, leading to incorrect destruction
484// in the linked_ptr (or compilation errors if using a checking
485// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000486class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000487 public:
488 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000489 Expectation();
490
491 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000492
493 // This single-argument ctor must not be explicit, in order to support the
494 // Expectation e = EXPECT_CALL(...);
495 // syntax.
496 //
497 // A TypedExpectation object stores its pre-requisites as
498 // Expectation objects, and needs to call the non-const Retire()
499 // method on the ExpectationBase objects they reference. Therefore
500 // Expectation must receive a *non-const* reference to the
501 // ExpectationBase object.
502 Expectation(internal::ExpectationBase& exp); // NOLINT
503
504 // The compiler-generated copy ctor and operator= work exactly as
505 // intended, so we don't need to define our own.
506
507 // Returns true iff rhs references the same expectation as this object does.
508 bool operator==(const Expectation& rhs) const {
509 return expectation_base_ == rhs.expectation_base_;
510 }
511
512 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
513
514 private:
515 friend class ExpectationSet;
516 friend class Sequence;
517 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000518 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000519
520 template <typename F>
521 friend class ::testing::internal::FunctionMockerBase;
522
523 template <typename F>
524 friend class ::testing::internal::TypedExpectation;
525
526 // This comparator is needed for putting Expectation objects into a set.
527 class Less {
528 public:
529 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
530 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
531 }
532 };
533
534 typedef ::std::set<Expectation, Less> Set;
535
536 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000537 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000538
539 // Returns the expectation this object references.
540 const internal::linked_ptr<internal::ExpectationBase>&
541 expectation_base() const {
542 return expectation_base_;
543 }
544
545 // A linked_ptr that co-owns the expectation this handle references.
546 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
547};
548
549// A set of expectation handles. Useful in the .After() clause of
550// EXPECT_CALL() for setting the (partial) order of expectations. The
551// syntax:
552//
553// ExpectationSet es;
554// es += EXPECT_CALL(...)...;
555// es += EXPECT_CALL(...)...;
556// EXPECT_CALL(...).After(es)...;
557//
558// sets three expectations where the last one can only be matched
559// after the first two have both been satisfied.
560//
561// This class is copyable and has value semantics.
562class ExpectationSet {
563 public:
564 // A bidirectional iterator that can read a const element in the set.
565 typedef Expectation::Set::const_iterator const_iterator;
566
567 // An object stored in the set. This is an alias of Expectation.
568 typedef Expectation::Set::value_type value_type;
569
570 // Constructs an empty set.
571 ExpectationSet() {}
572
573 // This single-argument ctor must not be explicit, in order to support the
574 // ExpectationSet es = EXPECT_CALL(...);
575 // syntax.
576 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
577 *this += Expectation(exp);
578 }
579
580 // This single-argument ctor implements implicit conversion from
581 // Expectation and thus must not be explicit. This allows either an
582 // Expectation or an ExpectationSet to be used in .After().
583 ExpectationSet(const Expectation& e) { // NOLINT
584 *this += e;
585 }
586
587 // The compiler-generator ctor and operator= works exactly as
588 // intended, so we don't need to define our own.
589
590 // Returns true iff rhs contains the same set of Expectation objects
591 // as this does.
592 bool operator==(const ExpectationSet& rhs) const {
593 return expectations_ == rhs.expectations_;
594 }
595
596 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
597
598 // Implements the syntax
599 // expectation_set += EXPECT_CALL(...);
600 ExpectationSet& operator+=(const Expectation& e) {
601 expectations_.insert(e);
602 return *this;
603 }
604
605 int size() const { return static_cast<int>(expectations_.size()); }
606
607 const_iterator begin() const { return expectations_.begin(); }
608 const_iterator end() const { return expectations_.end(); }
609
610 private:
611 Expectation::Set expectations_;
612};
613
614
shiqiane35fdd92008-12-10 05:08:54 +0000615// Sequence objects are used by a user to specify the relative order
616// in which the expectations should match. They are copyable (we rely
617// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000618class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000619 public:
620 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000621 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000622
623 // Adds an expectation to this sequence. The caller must ensure
624 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000625 void AddExpectation(const Expectation& expectation) const;
626
shiqiane35fdd92008-12-10 05:08:54 +0000627 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000628 // The last expectation in this sequence. We use a linked_ptr here
629 // because Sequence objects are copyable and we want the copies to
630 // be aliases. The linked_ptr allows the copies to co-own and share
631 // the same Expectation object.
632 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000633}; // class Sequence
634
635// An object of this type causes all EXPECT_CALL() statements
636// encountered in its scope to be put in an anonymous sequence. The
637// work is done in the constructor and destructor. You should only
638// create an InSequence object on the stack.
639//
640// The sole purpose for this class is to support easy definition of
641// sequential expectations, e.g.
642//
643// {
644// InSequence dummy; // The name of the object doesn't matter.
645//
646// // The following expectations must match in the order they appear.
647// EXPECT_CALL(a, Bar())...;
648// EXPECT_CALL(a, Baz())...;
649// ...
650// EXPECT_CALL(b, Xyz())...;
651// }
652//
653// You can create InSequence objects in multiple threads, as long as
654// they are used to affect different mock objects. The idea is that
655// each thread can create and set up its own mocks as if it's the only
656// thread. However, for clarity of your tests we recommend you to set
657// up mocks in the main thread unless you have a good reason not to do
658// so.
vladlosev587c1b32011-05-20 00:42:22 +0000659class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000660 public:
661 InSequence();
662 ~InSequence();
663 private:
664 bool sequence_created_;
665
666 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000667} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000668
669namespace internal {
670
671// Points to the implicit sequence introduced by a living InSequence
672// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000673GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000674
675// Base class for implementing expectations.
676//
677// There are two reasons for having a type-agnostic base class for
678// Expectation:
679//
680// 1. We need to store collections of expectations of different
681// types (e.g. all pre-requisites of a particular expectation, all
682// expectations in a sequence). Therefore these expectation objects
683// must share a common base class.
684//
685// 2. We can avoid binary code bloat by moving methods not depending
686// on the template argument of Expectation to the base class.
687//
688// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000689class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000690 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000691 // source_text is the EXPECT_CALL(...) source that created this Expectation.
692 ExpectationBase(const char* file, int line, const string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000693
694 virtual ~ExpectationBase();
695
696 // Where in the source file was the expectation spec defined?
697 const char* file() const { return file_; }
698 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000699 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000700 // Returns the cardinality specified in the expectation spec.
701 const Cardinality& cardinality() const { return cardinality_; }
702
703 // Describes the source file location of this expectation.
704 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000705 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000706 }
707
708 // Describes how many times a function call matching this
709 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000710 void DescribeCallCountTo(::std::ostream* os) const
711 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000712
713 // If this mock method has an extra matcher (i.e. .With(matcher)),
714 // describes it to the ostream.
715 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000716
shiqiane35fdd92008-12-10 05:08:54 +0000717 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000718 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000719 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000720
721 enum Clause {
722 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000723 kNone,
724 kWith,
725 kTimes,
726 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000727 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000728 kWillOnce,
729 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000730 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000731 };
732
zhanyong.waned6c9272011-02-23 19:39:27 +0000733 typedef std::vector<const void*> UntypedActions;
734
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000735 // Returns an Expectation object that references and co-owns this
736 // expectation.
737 virtual Expectation GetHandle() = 0;
738
shiqiane35fdd92008-12-10 05:08:54 +0000739 // Asserts that the EXPECT_CALL() statement has the given property.
740 void AssertSpecProperty(bool property, const string& failure_message) const {
741 Assert(property, file_, line_, failure_message);
742 }
743
744 // Expects that the EXPECT_CALL() statement has the given property.
745 void ExpectSpecProperty(bool property, const string& failure_message) const {
746 Expect(property, file_, line_, failure_message);
747 }
748
749 // Explicitly specifies the cardinality of this expectation. Used
750 // by the subclasses to implement the .Times() clause.
751 void SpecifyCardinality(const Cardinality& cardinality);
752
753 // Returns true iff the user specified the cardinality explicitly
754 // using a .Times().
755 bool cardinality_specified() const { return cardinality_specified_; }
756
757 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000758 void set_cardinality(const Cardinality& a_cardinality) {
759 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000760 }
761
762 // The following group of methods should only be called after the
763 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
764 // the current thread.
765
766 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000767 void RetireAllPreRequisites()
768 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000769
770 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000771 bool is_retired() const
772 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000773 g_gmock_mutex.AssertHeld();
774 return retired_;
775 }
776
777 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000778 void Retire()
779 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000780 g_gmock_mutex.AssertHeld();
781 retired_ = true;
782 }
783
784 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000785 bool IsSatisfied() const
786 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000787 g_gmock_mutex.AssertHeld();
788 return cardinality().IsSatisfiedByCallCount(call_count_);
789 }
790
791 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000792 bool IsSaturated() const
793 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000794 g_gmock_mutex.AssertHeld();
795 return cardinality().IsSaturatedByCallCount(call_count_);
796 }
797
798 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000799 bool IsOverSaturated() const
800 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000801 g_gmock_mutex.AssertHeld();
802 return cardinality().IsOverSaturatedByCallCount(call_count_);
803 }
804
805 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000806 bool AllPrerequisitesAreSatisfied() const
807 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000808
809 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000810 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
811 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000812
813 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000814 int call_count() const
815 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000816 g_gmock_mutex.AssertHeld();
817 return call_count_;
818 }
819
820 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000821 void IncrementCallCount()
822 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000823 g_gmock_mutex.AssertHeld();
824 call_count_++;
825 }
826
zhanyong.waned6c9272011-02-23 19:39:27 +0000827 // Checks the action count (i.e. the number of WillOnce() and
828 // WillRepeatedly() clauses) against the cardinality if this hasn't
829 // been done before. Prints a warning if there are too many or too
830 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000831 void CheckActionCountIfNotDone() const
832 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000833
shiqiane35fdd92008-12-10 05:08:54 +0000834 friend class ::testing::Sequence;
835 friend class ::testing::internal::ExpectationTester;
836
837 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000838 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000839
zhanyong.waned6c9272011-02-23 19:39:27 +0000840 // Implements the .Times() clause.
841 void UntypedTimes(const Cardinality& a_cardinality);
842
shiqiane35fdd92008-12-10 05:08:54 +0000843 // This group of fields are part of the spec and won't change after
844 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000845 const char* file_; // The file that contains the expectation.
846 int line_; // The line number of the expectation.
847 const string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000848 // True iff the cardinality is specified explicitly.
849 bool cardinality_specified_;
850 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000851 // The immediate pre-requisites (i.e. expectations that must be
852 // satisfied before this expectation can be matched) of this
853 // expectation. We use linked_ptr in the set because we want an
854 // Expectation object to be co-owned by its FunctionMocker and its
855 // successors. This allows multiple mock objects to be deleted at
856 // different times.
857 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000858
859 // This group of fields are the current state of the expectation,
860 // and can change as the mock function is called.
861 int call_count_; // How many times this expectation has been invoked.
862 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000863 UntypedActions untyped_actions_;
864 bool extra_matcher_specified_;
865 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
866 bool retires_on_saturation_;
867 Clause last_clause_;
868 mutable bool action_count_checked_; // Under mutex_.
869 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000870
871 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000872}; // class ExpectationBase
873
874// Impements an expectation for the given function type.
875template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000876class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000877 public:
878 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
879 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
880 typedef typename Function<F>::Result Result;
881
vladlosev6c54a5e2009-10-21 06:15:34 +0000882 TypedExpectation(FunctionMockerBase<F>* owner,
zhanyong.wan32de5f52009-12-23 00:13:23 +0000883 const char* a_file, int a_line, const string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000884 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000885 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000886 owner_(owner),
887 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000888 // By default, extra_matcher_ should match anything. However,
889 // we cannot initialize it with _ as that triggers a compiler
890 // bug in Symbian's C++ compiler (cannot decide between two
891 // overloaded constructors of Matcher<const ArgumentTuple&>).
892 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000893 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000894
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000895 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000896 // Check the validity of the action count if it hasn't been done
897 // yet (for example, if the expectation was never used).
898 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000899 for (UntypedActions::const_iterator it = untyped_actions_.begin();
900 it != untyped_actions_.end(); ++it) {
901 delete static_cast<const Action<F>*>(*it);
902 }
shiqiane35fdd92008-12-10 05:08:54 +0000903 }
904
zhanyong.wanbf550852009-06-09 06:09:53 +0000905 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000906 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000907 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000908 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000909 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000910 "more than once in an EXPECT_CALL().");
911 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000912 ExpectSpecProperty(last_clause_ < kWith,
913 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000914 "clause in an EXPECT_CALL().");
915 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000916 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000917
918 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000919 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000920 return *this;
921 }
922
923 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000924 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000925 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000926 return *this;
927 }
928
929 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000930 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000931 return Times(Exactly(n));
932 }
933
934 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000935 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000936 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000937 ".InSequence() cannot appear after .After(),"
938 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000939 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000940 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000941
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000942 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000943 return *this;
944 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000945 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000946 return InSequence(s1).InSequence(s2);
947 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000948 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
949 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000950 return InSequence(s1, s2).InSequence(s3);
951 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000952 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
953 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000954 return InSequence(s1, s2, s3).InSequence(s4);
955 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000956 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
957 const Sequence& s3, const Sequence& s4,
958 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000959 return InSequence(s1, s2, s3, s4).InSequence(s5);
960 }
961
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000962 // Implements that .After() clause.
963 TypedExpectation& After(const ExpectationSet& s) {
964 ExpectSpecProperty(last_clause_ <= kAfter,
965 ".After() cannot appear after .WillOnce(),"
966 " .WillRepeatedly(), or "
967 ".RetiresOnSaturation().");
968 last_clause_ = kAfter;
969
970 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
971 immediate_prerequisites_ += *it;
972 }
973 return *this;
974 }
975 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
976 return After(s1).After(s2);
977 }
978 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
979 const ExpectationSet& s3) {
980 return After(s1, s2).After(s3);
981 }
982 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
983 const ExpectationSet& s3, const ExpectationSet& s4) {
984 return After(s1, s2, s3).After(s4);
985 }
986 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
987 const ExpectationSet& s3, const ExpectationSet& s4,
988 const ExpectationSet& s5) {
989 return After(s1, s2, s3, s4).After(s5);
990 }
991
shiqiane35fdd92008-12-10 05:08:54 +0000992 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000993 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000994 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000995 ".WillOnce() cannot appear after "
996 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000997 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +0000998
zhanyong.waned6c9272011-02-23 19:39:27 +0000999 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +00001000 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001001 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001002 }
1003 return *this;
1004 }
1005
1006 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001007 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001008 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001009 ExpectSpecProperty(false,
1010 ".WillRepeatedly() cannot appear "
1011 "more than once in an EXPECT_CALL().");
1012 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001013 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001014 ".WillRepeatedly() cannot appear "
1015 "after .RetiresOnSaturation().");
1016 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001017 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001018 repeated_action_specified_ = true;
1019
1020 repeated_action_ = action;
1021 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001022 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001023 }
1024
1025 // Now that no more action clauses can be specified, we check
1026 // whether their count makes sense.
1027 CheckActionCountIfNotDone();
1028 return *this;
1029 }
1030
1031 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001032 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001033 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001034 ".RetiresOnSaturation() cannot appear "
1035 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001036 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001037 retires_on_saturation_ = true;
1038
1039 // Now that no more action clauses can be specified, we check
1040 // whether their count makes sense.
1041 CheckActionCountIfNotDone();
1042 return *this;
1043 }
1044
1045 // Returns the matchers for the arguments as specified inside the
1046 // EXPECT_CALL() macro.
1047 const ArgumentMatcherTuple& matchers() const {
1048 return matchers_;
1049 }
1050
zhanyong.wanbf550852009-06-09 06:09:53 +00001051 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001052 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1053 return extra_matcher_;
1054 }
1055
shiqiane35fdd92008-12-10 05:08:54 +00001056 // Returns the action specified by the .WillRepeatedly() clause.
1057 const Action<F>& repeated_action() const { return repeated_action_; }
1058
zhanyong.waned6c9272011-02-23 19:39:27 +00001059 // If this mock method has an extra matcher (i.e. .With(matcher)),
1060 // describes it to the ostream.
1061 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001062 if (extra_matcher_specified_) {
1063 *os << " Expected args: ";
1064 extra_matcher_.DescribeTo(os);
1065 *os << "\n";
1066 }
1067 }
1068
shiqiane35fdd92008-12-10 05:08:54 +00001069 private:
1070 template <typename Function>
1071 friend class FunctionMockerBase;
1072
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001073 // Returns an Expectation object that references and co-owns this
1074 // expectation.
1075 virtual Expectation GetHandle() {
1076 return owner_->GetHandleOf(this);
1077 }
1078
shiqiane35fdd92008-12-10 05:08:54 +00001079 // The following methods will be called only after the EXPECT_CALL()
1080 // statement finishes and when the current thread holds
1081 // g_gmock_mutex.
1082
1083 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001084 bool Matches(const ArgumentTuple& args) const
1085 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001086 g_gmock_mutex.AssertHeld();
1087 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1088 }
1089
1090 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001091 bool ShouldHandleArguments(const ArgumentTuple& args) const
1092 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001093 g_gmock_mutex.AssertHeld();
1094
1095 // In case the action count wasn't checked when the expectation
1096 // was defined (e.g. if this expectation has no WillRepeatedly()
1097 // or RetiresOnSaturation() clause), we check it when the
1098 // expectation is used for the first time.
1099 CheckActionCountIfNotDone();
1100 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1101 }
1102
1103 // Describes the result of matching the arguments against this
1104 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001105 void ExplainMatchResultTo(
1106 const ArgumentTuple& args,
1107 ::std::ostream* os) const
1108 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001109 g_gmock_mutex.AssertHeld();
1110
1111 if (is_retired()) {
1112 *os << " Expected: the expectation is active\n"
1113 << " Actual: it is retired\n";
1114 } else if (!Matches(args)) {
1115 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001116 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001117 }
zhanyong.wan82113312010-01-08 21:55:40 +00001118 StringMatchResultListener listener;
1119 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001120 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001121 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001122 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001123
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001124 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001125 *os << "\n";
1126 }
1127 } else if (!AllPrerequisitesAreSatisfied()) {
1128 *os << " Expected: all pre-requisites are satisfied\n"
1129 << " Actual: the following immediate pre-requisites "
1130 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001131 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001132 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1133 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001134 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001135 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001136 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001137 *os << "pre-requisite #" << i++ << "\n";
1138 }
1139 *os << " (end of pre-requisites)\n";
1140 } else {
1141 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001142 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001143 // is called only when the mock function call does NOT match the
1144 // expectation.
1145 *os << "The call matches the expectation.\n";
1146 }
1147 }
1148
1149 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001150 const Action<F>& GetCurrentAction(
1151 const FunctionMockerBase<F>* mocker,
1152 const ArgumentTuple& args) const
1153 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001154 g_gmock_mutex.AssertHeld();
1155 const int count = call_count();
1156 Assert(count >= 1, __FILE__, __LINE__,
1157 "call_count() is <= 0 when GetCurrentAction() is "
1158 "called - this should never happen.");
1159
zhanyong.waned6c9272011-02-23 19:39:27 +00001160 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001161 if (action_count > 0 && !repeated_action_specified_ &&
1162 count > action_count) {
1163 // If there is at least one WillOnce() and no WillRepeatedly(),
1164 // we warn the user when the WillOnce() clauses ran out.
1165 ::std::stringstream ss;
1166 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001167 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001168 << "Called " << count << " times, but only "
1169 << action_count << " WillOnce()"
1170 << (action_count == 1 ? " is" : "s are") << " specified - ";
1171 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001172 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001173 }
1174
zhanyong.waned6c9272011-02-23 19:39:27 +00001175 return count <= action_count ?
1176 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1177 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001178 }
1179
1180 // Given the arguments of a mock function call, if the call will
1181 // over-saturate this expectation, returns the default action;
1182 // otherwise, returns the next action in this expectation. Also
1183 // describes *what* happened to 'what', and explains *why* Google
1184 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001185 // IncrementCallCount(). A return value of NULL means the default
1186 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001187 const Action<F>* GetActionForArguments(
1188 const FunctionMockerBase<F>* mocker,
1189 const ArgumentTuple& args,
1190 ::std::ostream* what,
1191 ::std::ostream* why)
1192 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001193 g_gmock_mutex.AssertHeld();
1194 if (IsSaturated()) {
1195 // We have an excessive call.
1196 IncrementCallCount();
1197 *what << "Mock function called more times than expected - ";
1198 mocker->DescribeDefaultActionTo(args, what);
1199 DescribeCallCountTo(why);
1200
zhanyong.waned6c9272011-02-23 19:39:27 +00001201 // TODO(wan@google.com): allow the user to control whether
1202 // unexpected calls should fail immediately or continue using a
1203 // flag --gmock_unexpected_calls_are_fatal.
1204 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001205 }
1206
1207 IncrementCallCount();
1208 RetireAllPreRequisites();
1209
zhanyong.waned6c9272011-02-23 19:39:27 +00001210 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001211 Retire();
1212 }
1213
1214 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001215 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001216 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001217 }
1218
1219 // All the fields below won't change once the EXPECT_CALL()
1220 // statement finishes.
1221 FunctionMockerBase<F>* const owner_;
1222 ArgumentMatcherTuple matchers_;
1223 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001224 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001225
1226 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001227}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001228
1229// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1230// specifying the default behavior of, or expectation on, a mock
1231// function.
1232
1233// Note: class MockSpec really belongs to the ::testing namespace.
1234// However if we define it in ::testing, MSVC will complain when
1235// classes in ::testing::internal declare it as a friend class
1236// template. To workaround this compiler bug, we define MockSpec in
1237// ::testing::internal and import it into ::testing.
1238
zhanyong.waned6c9272011-02-23 19:39:27 +00001239// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001240GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1241 const char* file, int line,
1242 const string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001243
shiqiane35fdd92008-12-10 05:08:54 +00001244template <typename F>
1245class MockSpec {
1246 public:
1247 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1248 typedef typename internal::Function<F>::ArgumentMatcherTuple
1249 ArgumentMatcherTuple;
1250
1251 // Constructs a MockSpec object, given the function mocker object
1252 // that the spec is associated with.
1253 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1254 : function_mocker_(function_mocker) {}
1255
1256 // Adds a new default action spec to the function mocker and returns
1257 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001258 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001259 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001260 LogWithLocation(internal::kInfo, file, line,
shiqiane35fdd92008-12-10 05:08:54 +00001261 string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001262 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001263 }
1264
1265 // Adds a new expectation spec to the function mocker and returns
1266 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001267 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001268 const char* file, int line, const char* obj, const char* call) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001269 const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001270 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001271 return function_mocker_->AddNewExpectation(
1272 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001273 }
1274
1275 private:
1276 template <typename Function>
1277 friend class internal::FunctionMocker;
1278
1279 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1280 matchers_ = matchers;
1281 }
1282
shiqiane35fdd92008-12-10 05:08:54 +00001283 // The function mocker that owns this spec.
1284 internal::FunctionMockerBase<F>* const function_mocker_;
1285 // The argument matchers specified in the spec.
1286 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001287
1288 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001289}; // class MockSpec
1290
1291// MSVC warns about using 'this' in base member initializer list, so
1292// we need to temporarily disable the warning. We have to do it for
1293// the entire class to suppress the warning, even though it's about
1294// the constructor only.
1295
1296#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001297# pragma warning(push) // Saves the current warning state.
1298# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001299#endif // _MSV_VER
1300
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001301// C++ treats the void type specially. For example, you cannot define
1302// a void-typed variable or pass a void value to a function.
1303// ActionResultHolder<T> holds a value of type T, where T must be a
1304// copyable type or void (T doesn't need to be default-constructable).
1305// It hides the syntactic difference between void and other types, and
1306// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001307// non-void-returning mock functions.
1308
1309// Untyped base class for ActionResultHolder<T>.
1310class UntypedActionResultHolderBase {
1311 public:
1312 virtual ~UntypedActionResultHolderBase() {}
1313
1314 // Prints the held value as an action's result to os.
1315 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1316};
1317
1318// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001319template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001320class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001321 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00001322 explicit ActionResultHolder(T a_value) : value_(a_value) {}
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001323
1324 // The compiler-generated copy constructor and assignment operator
1325 // are exactly what we need, so we don't need to define them.
1326
zhanyong.waned6c9272011-02-23 19:39:27 +00001327 // Returns the held value and deletes this object.
1328 T GetValueAndDelete() const {
1329 T retval(value_);
1330 delete this;
1331 return retval;
1332 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001333
1334 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001335 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001336 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001337 // T may be a reference type, so we don't use UniversalPrint().
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001338 UniversalPrinter<T>::Print(value_, os);
1339 }
1340
1341 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001342 // result in a new-ed ActionResultHolder.
1343 template <typename F>
1344 static ActionResultHolder* PerformDefaultAction(
1345 const FunctionMockerBase<F>* func_mocker,
1346 const typename Function<F>::ArgumentTuple& args,
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001347 const string& call_description) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001348 return new ActionResultHolder(
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001349 func_mocker->PerformDefaultAction(args, call_description));
1350 }
1351
zhanyong.waned6c9272011-02-23 19:39:27 +00001352 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001353 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001354 template <typename F>
1355 static ActionResultHolder*
1356 PerformAction(const Action<F>& action,
1357 const typename Function<F>::ArgumentTuple& args) {
1358 return new ActionResultHolder(action.Perform(args));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001359 }
1360
1361 private:
1362 T value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001363
1364 // T could be a reference type, so = isn't supported.
1365 GTEST_DISALLOW_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001366};
1367
1368// Specialization for T = void.
1369template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001370class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001371 public:
zhanyong.waned6c9272011-02-23 19:39:27 +00001372 void GetValueAndDelete() const { delete this; }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001373
zhanyong.waned6c9272011-02-23 19:39:27 +00001374 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1375
1376 // Performs the given mock function's default action and returns NULL;
1377 template <typename F>
1378 static ActionResultHolder* PerformDefaultAction(
1379 const FunctionMockerBase<F>* func_mocker,
1380 const typename Function<F>::ArgumentTuple& args,
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001381 const string& call_description) {
1382 func_mocker->PerformDefaultAction(args, call_description);
zhanyong.waned6c9272011-02-23 19:39:27 +00001383 return NULL;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001384 }
1385
zhanyong.waned6c9272011-02-23 19:39:27 +00001386 // Performs the given action and returns NULL.
1387 template <typename F>
1388 static ActionResultHolder* PerformAction(
1389 const Action<F>& action,
1390 const typename Function<F>::ArgumentTuple& args) {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001391 action.Perform(args);
zhanyong.waned6c9272011-02-23 19:39:27 +00001392 return NULL;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001393 }
1394};
1395
shiqiane35fdd92008-12-10 05:08:54 +00001396// The base of the function mocker class for the given function type.
1397// We put the methods in this class instead of its child to avoid code
1398// bloat.
1399template <typename F>
1400class FunctionMockerBase : public UntypedFunctionMockerBase {
1401 public:
1402 typedef typename Function<F>::Result Result;
1403 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1404 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1405
zhanyong.waned6c9272011-02-23 19:39:27 +00001406 FunctionMockerBase() : current_spec_(this) {}
shiqiane35fdd92008-12-10 05:08:54 +00001407
1408 // The destructor verifies that all expectations on this mock
1409 // function have been satisfied. If not, it will report Google Test
1410 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001411 virtual ~FunctionMockerBase()
1412 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001413 MutexLock l(&g_gmock_mutex);
1414 VerifyAndClearExpectationsLocked();
1415 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001416 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001417 }
1418
1419 // Returns the ON_CALL spec that matches this mock function with the
1420 // given arguments; returns NULL if no matching ON_CALL is found.
1421 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001422 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001423 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001424 for (UntypedOnCallSpecs::const_reverse_iterator it
1425 = untyped_on_call_specs_.rbegin();
1426 it != untyped_on_call_specs_.rend(); ++it) {
1427 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1428 if (spec->Matches(args))
1429 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001430 }
1431
1432 return NULL;
1433 }
1434
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001435 // Performs the default action of this mock function on the given
1436 // arguments and returns the result. Asserts (or throws if
1437 // exceptions are enabled) with a helpful call descrption if there
1438 // is no valid return value. This method doesn't depend on the
1439 // mutable state of this object, and thus can be called concurrently
1440 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001441 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001442 Result PerformDefaultAction(const ArgumentTuple& args,
1443 const string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001444 const OnCallSpec<F>* const spec =
1445 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001446 if (spec != NULL) {
1447 return spec->GetAction().Perform(args);
1448 }
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001449 const string message = call_description +
1450 "\n The mock function has no default action "
1451 "set, and its return type has no default value set.";
1452#if GTEST_HAS_EXCEPTIONS
1453 if (!DefaultValue<Result>::Exists()) {
1454 throw std::runtime_error(message);
1455 }
1456#else
1457 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1458#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001459 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001460 }
1461
zhanyong.waned6c9272011-02-23 19:39:27 +00001462 // Performs the default action with the given arguments and returns
1463 // the action's result. The call description string will be used in
1464 // the error message to describe the call in the case the default
1465 // action fails. The caller is responsible for deleting the result.
1466 // L = *
1467 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1468 const void* untyped_args, // must point to an ArgumentTuple
1469 const string& call_description) const {
1470 const ArgumentTuple& args =
1471 *static_cast<const ArgumentTuple*>(untyped_args);
1472 return ResultHolder::PerformDefaultAction(this, args, call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001473 }
1474
zhanyong.waned6c9272011-02-23 19:39:27 +00001475 // Performs the given action with the given arguments and returns
1476 // the action's result. The caller is responsible for deleting the
1477 // result.
1478 // L = *
1479 virtual UntypedActionResultHolderBase* UntypedPerformAction(
1480 const void* untyped_action, const void* untyped_args) const {
1481 // Make a copy of the action before performing it, in case the
1482 // action deletes the mock object (and thus deletes itself).
1483 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1484 const ArgumentTuple& args =
1485 *static_cast<const ArgumentTuple*>(untyped_args);
1486 return ResultHolder::PerformAction(action, args);
1487 }
shiqiane35fdd92008-12-10 05:08:54 +00001488
zhanyong.waned6c9272011-02-23 19:39:27 +00001489 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1490 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001491 virtual void ClearDefaultActionsLocked()
1492 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001493 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001494
1495 // Deleting our default actions may trigger other mock objects to be
1496 // deleted, for example if an action contains a reference counted smart
1497 // pointer to that mock object, and that is the last reference. So if we
1498 // delete our actions within the context of the global mutex we may deadlock
1499 // when this method is called again. Instead, make a copy of the set of
1500 // actions to delete, clear our set within the mutex, and then delete the
1501 // actions outside of the mutex.
1502 UntypedOnCallSpecs specs_to_delete;
1503 untyped_on_call_specs_.swap(specs_to_delete);
1504
1505 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001506 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001507 specs_to_delete.begin();
1508 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001509 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001510 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001511
1512 // Lock the mutex again, since the caller expects it to be locked when we
1513 // return.
1514 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001515 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001516
shiqiane35fdd92008-12-10 05:08:54 +00001517 protected:
1518 template <typename Function>
1519 friend class MockSpec;
1520
zhanyong.waned6c9272011-02-23 19:39:27 +00001521 typedef ActionResultHolder<Result> ResultHolder;
1522
shiqiane35fdd92008-12-10 05:08:54 +00001523 // Returns the result of invoking this mock function with the given
1524 // arguments. This function can be safely called from multiple
1525 // threads concurrently.
vladlosev4d60a592011-10-24 21:16:22 +00001526 Result InvokeWith(const ArgumentTuple& args)
1527 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001528 return static_cast<const ResultHolder*>(
1529 this->UntypedInvokeWith(&args))->GetValueAndDelete();
1530 }
shiqiane35fdd92008-12-10 05:08:54 +00001531
1532 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001533 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001534 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001535 const ArgumentMatcherTuple& m)
1536 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001537 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001538 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1539 untyped_on_call_specs_.push_back(on_call_spec);
1540 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001541 }
1542
1543 // Adds and returns an expectation spec for this mock function.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001544 TypedExpectation<F>& AddNewExpectation(
vladlosev6c54a5e2009-10-21 06:15:34 +00001545 const char* file,
1546 int line,
1547 const string& source_text,
vladlosev4d60a592011-10-24 21:16:22 +00001548 const ArgumentMatcherTuple& m)
1549 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001550 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001551 TypedExpectation<F>* const expectation =
1552 new TypedExpectation<F>(this, file, line, source_text, m);
1553 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
1554 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001555
1556 // Adds this expectation into the implicit sequence if there is one.
1557 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1558 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001559 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001560 }
1561
1562 return *expectation;
1563 }
1564
1565 // The current spec (either default action spec or expectation spec)
1566 // being described on this function mocker.
1567 MockSpec<F>& current_spec() { return current_spec_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001568
shiqiane35fdd92008-12-10 05:08:54 +00001569 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001570 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001571
zhanyong.waned6c9272011-02-23 19:39:27 +00001572 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001573
1574 // Describes what default action will be performed for the given
1575 // arguments.
1576 // L = *
1577 void DescribeDefaultActionTo(const ArgumentTuple& args,
1578 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001579 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001580
1581 if (spec == NULL) {
1582 *os << (internal::type_equals<Result, void>::value ?
1583 "returning directly.\n" :
1584 "returning default value.\n");
1585 } else {
1586 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001587 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001588 }
1589 }
1590
1591 // Writes a message that the call is uninteresting (i.e. neither
1592 // explicitly expected nor explicitly unexpected) to the given
1593 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001594 virtual void UntypedDescribeUninterestingCall(
1595 const void* untyped_args,
1596 ::std::ostream* os) const
1597 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001598 const ArgumentTuple& args =
1599 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001600 *os << "Uninteresting mock function call - ";
1601 DescribeDefaultActionTo(args, os);
1602 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001603 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001604 }
1605
zhanyong.waned6c9272011-02-23 19:39:27 +00001606 // Returns the expectation that matches the given function arguments
1607 // (or NULL is there's no match); when a match is found,
1608 // untyped_action is set to point to the action that should be
1609 // performed (or NULL if the action is "do default"), and
1610 // is_excessive is modified to indicate whether the call exceeds the
1611 // expected number.
1612 //
shiqiane35fdd92008-12-10 05:08:54 +00001613 // Critical section: We must find the matching expectation and the
1614 // corresponding action that needs to be taken in an ATOMIC
1615 // transaction. Otherwise another thread may call this mock
1616 // method in the middle and mess up the state.
1617 //
1618 // However, performing the action has to be left out of the critical
1619 // section. The reason is that we have no control on what the
1620 // action does (it can invoke an arbitrary user function or even a
1621 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001622 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1623 const void* untyped_args,
1624 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001625 ::std::ostream* what, ::std::ostream* why)
1626 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001627 const ArgumentTuple& args =
1628 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001629 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001630 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1631 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001632 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001633 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001634 }
1635
1636 // This line must be done before calling GetActionForArguments(),
1637 // which will increment the call count for *exp and thus affect
1638 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001639 *is_excessive = exp->IsSaturated();
1640 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1641 if (action != NULL && action->IsDoDefault())
1642 action = NULL; // Normalize "do default" to NULL.
1643 *untyped_action = action;
1644 return exp;
1645 }
1646
1647 // Prints the given function arguments to the ostream.
1648 virtual void UntypedPrintArgs(const void* untyped_args,
1649 ::std::ostream* os) const {
1650 const ArgumentTuple& args =
1651 *static_cast<const ArgumentTuple*>(untyped_args);
1652 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001653 }
1654
1655 // Returns the expectation that matches the arguments, or NULL if no
1656 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001657 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001658 const ArgumentTuple& args) const
1659 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001660 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001661 for (typename UntypedExpectations::const_reverse_iterator it =
1662 untyped_expectations_.rbegin();
1663 it != untyped_expectations_.rend(); ++it) {
1664 TypedExpectation<F>* const exp =
1665 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001666 if (exp->ShouldHandleArguments(args)) {
1667 return exp;
1668 }
1669 }
1670 return NULL;
1671 }
1672
1673 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001674 void FormatUnexpectedCallMessageLocked(
1675 const ArgumentTuple& args,
1676 ::std::ostream* os,
1677 ::std::ostream* why) const
1678 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001679 g_gmock_mutex.AssertHeld();
1680 *os << "\nUnexpected mock function call - ";
1681 DescribeDefaultActionTo(args, os);
1682 PrintTriedExpectationsLocked(args, why);
1683 }
1684
1685 // Prints a list of expectations that have been tried against the
1686 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001687 void PrintTriedExpectationsLocked(
1688 const ArgumentTuple& args,
1689 ::std::ostream* why) const
1690 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001691 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001692 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001693 *why << "Google Mock tried the following " << count << " "
1694 << (count == 1 ? "expectation, but it didn't match" :
1695 "expectations, but none matched")
1696 << ":\n";
1697 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001698 TypedExpectation<F>* const expectation =
1699 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001700 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001701 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001702 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001703 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001704 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001705 *why << expectation->source_text() << "...\n";
1706 expectation->ExplainMatchResultTo(args, why);
1707 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001708 }
1709 }
1710
shiqiane35fdd92008-12-10 05:08:54 +00001711 // The current spec (either default action spec or expectation spec)
1712 // being described on this function mocker.
1713 MockSpec<F> current_spec_;
1714
zhanyong.wan16cf4732009-05-14 20:55:30 +00001715 // There is no generally useful and implementable semantics of
1716 // copying a mock object, so copying a mock is usually a user error.
1717 // Thus we disallow copying function mockers. If the user really
1718 // wants to copy a mock object, he should implement his own copy
1719 // operation, for example:
1720 //
1721 // class MockFoo : public Foo {
1722 // public:
1723 // // Defines a copy constructor explicitly.
1724 // MockFoo(const MockFoo& src) {}
1725 // ...
1726 // };
1727 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001728}; // class FunctionMockerBase
1729
1730#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001731# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001732#endif // _MSV_VER
1733
1734// Implements methods of FunctionMockerBase.
1735
1736// Verifies that all expectations on this mock function have been
1737// satisfied. Reports one or more Google Test non-fatal failures and
1738// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001739
1740// Reports an uninteresting call (whose description is in msg) in the
1741// manner specified by 'reaction'.
1742void ReportUninterestingCall(CallReaction reaction, const string& msg);
1743
shiqiane35fdd92008-12-10 05:08:54 +00001744} // namespace internal
1745
1746// The style guide prohibits "using" statements in a namespace scope
1747// inside a header file. However, the MockSpec class template is
1748// meant to be defined in the ::testing namespace. The following line
1749// is just a trick for working around a bug in MSVC 8.0, which cannot
1750// handle it if we define MockSpec in ::testing.
1751using internal::MockSpec;
1752
1753// Const(x) is a convenient function for obtaining a const reference
1754// to x. This is useful for setting expectations on an overloaded
1755// const mock method, e.g.
1756//
1757// class MockFoo : public FooInterface {
1758// public:
1759// MOCK_METHOD0(Bar, int());
1760// MOCK_CONST_METHOD0(Bar, int&());
1761// };
1762//
1763// MockFoo foo;
1764// // Expects a call to non-const MockFoo::Bar().
1765// EXPECT_CALL(foo, Bar());
1766// // Expects a call to const MockFoo::Bar().
1767// EXPECT_CALL(Const(foo), Bar());
1768template <typename T>
1769inline const T& Const(const T& x) { return x; }
1770
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001771// Constructs an Expectation object that references and co-owns exp.
1772inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1773 : expectation_base_(exp.GetHandle().expectation_base()) {}
1774
shiqiane35fdd92008-12-10 05:08:54 +00001775} // namespace testing
1776
1777// A separate macro is required to avoid compile errors when the name
1778// of the method used in call is a result of macro expansion.
1779// See CompilesWithMethodNameExpandedFromMacro tests in
1780// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001781#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001782 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1783 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001784#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001785
zhanyong.wane0d051e2009-02-19 00:33:37 +00001786#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001787 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001788#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001789
1790#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_