blob: 59f1d71e3850c779a2a13edf051e68b9636ecd02 [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>
403 friend class StrictMock;
404
405 // Tells Google Mock to allow uninteresting calls on the given mock
406 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000407 static void AllowUninterestingCalls(const void* mock_obj)
408 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000409
410 // Tells Google Mock to warn the user about uninteresting calls on
411 // the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000412 static void WarnUninterestingCalls(const void* mock_obj)
413 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000414
415 // Tells Google Mock to fail uninteresting calls on the given mock
416 // object.
vladlosev4d60a592011-10-24 21:16:22 +0000417 static void FailUninterestingCalls(const void* mock_obj)
418 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000419
420 // Tells Google Mock the given mock object is being destroyed and
421 // its entry in the call-reaction table should be removed.
vladlosev4d60a592011-10-24 21:16:22 +0000422 static void UnregisterCallReaction(const void* mock_obj)
423 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000424
425 // Returns the reaction Google Mock will have on uninteresting calls
426 // made on the given mock object.
shiqiane35fdd92008-12-10 05:08:54 +0000427 static internal::CallReaction GetReactionOnUninterestingCalls(
zhanyong.wan2fd619e2012-05-31 20:40:56 +0000428 const void* mock_obj)
vladlosev4d60a592011-10-24 21:16:22 +0000429 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000430
431 // Verifies that all expectations on the given mock object have been
432 // satisfied. Reports one or more Google Test non-fatal failures
433 // and returns false if not.
vladlosev4d60a592011-10-24 21:16:22 +0000434 static bool VerifyAndClearExpectationsLocked(void* mock_obj)
435 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000436
437 // Clears all ON_CALL()s set on the given mock object.
vladlosev4d60a592011-10-24 21:16:22 +0000438 static void ClearDefaultActionsLocked(void* mock_obj)
439 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000440
441 // Registers a mock object and a mock method it owns.
vladlosev4d60a592011-10-24 21:16:22 +0000442 static void Register(
443 const void* mock_obj,
444 internal::UntypedFunctionMockerBase* mocker)
445 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000446
zhanyong.wandf35a762009-04-22 22:25:31 +0000447 // Tells Google Mock where in the source code mock_obj is used in an
448 // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this
449 // information helps the user identify which object it is.
zhanyong.wandf35a762009-04-22 22:25:31 +0000450 static void RegisterUseByOnCallOrExpectCall(
vladlosev4d60a592011-10-24 21:16:22 +0000451 const void* mock_obj, const char* file, int line)
452 GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
zhanyong.wandf35a762009-04-22 22:25:31 +0000453
shiqiane35fdd92008-12-10 05:08:54 +0000454 // Unregisters a mock method; removes the owning mock object from
455 // the registry when the last mock method associated with it has
456 // been unregistered. This is called only in the destructor of
457 // FunctionMockerBase.
vladlosev4d60a592011-10-24 21:16:22 +0000458 static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)
459 GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000460}; // class Mock
461
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000462// An abstract handle of an expectation. Useful in the .After()
463// clause of EXPECT_CALL() for setting the (partial) order of
464// expectations. The syntax:
465//
466// Expectation e1 = EXPECT_CALL(...)...;
467// EXPECT_CALL(...).After(e1)...;
468//
469// sets two expectations where the latter can only be matched after
470// the former has been satisfied.
471//
472// Notes:
473// - This class is copyable and has value semantics.
474// - Constness is shallow: a const Expectation object itself cannot
475// be modified, but the mutable methods of the ExpectationBase
476// object it references can be called via expectation_base().
zhanyong.wan7c95d832009-10-01 21:56:16 +0000477// - The constructors and destructor are defined out-of-line because
478// the Symbian WINSCW compiler wants to otherwise instantiate them
479// when it sees this class definition, at which point it doesn't have
480// ExpectationBase available yet, leading to incorrect destruction
481// in the linked_ptr (or compilation errors if using a checking
482// linked_ptr).
vladlosev587c1b32011-05-20 00:42:22 +0000483class GTEST_API_ Expectation {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000484 public:
485 // Constructs a null object that doesn't reference any expectation.
zhanyong.wan7c95d832009-10-01 21:56:16 +0000486 Expectation();
487
488 ~Expectation();
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000489
490 // This single-argument ctor must not be explicit, in order to support the
491 // Expectation e = EXPECT_CALL(...);
492 // syntax.
493 //
494 // A TypedExpectation object stores its pre-requisites as
495 // Expectation objects, and needs to call the non-const Retire()
496 // method on the ExpectationBase objects they reference. Therefore
497 // Expectation must receive a *non-const* reference to the
498 // ExpectationBase object.
499 Expectation(internal::ExpectationBase& exp); // NOLINT
500
501 // The compiler-generated copy ctor and operator= work exactly as
502 // intended, so we don't need to define our own.
503
504 // Returns true iff rhs references the same expectation as this object does.
505 bool operator==(const Expectation& rhs) const {
506 return expectation_base_ == rhs.expectation_base_;
507 }
508
509 bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }
510
511 private:
512 friend class ExpectationSet;
513 friend class Sequence;
514 friend class ::testing::internal::ExpectationBase;
zhanyong.waned6c9272011-02-23 19:39:27 +0000515 friend class ::testing::internal::UntypedFunctionMockerBase;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000516
517 template <typename F>
518 friend class ::testing::internal::FunctionMockerBase;
519
520 template <typename F>
521 friend class ::testing::internal::TypedExpectation;
522
523 // This comparator is needed for putting Expectation objects into a set.
524 class Less {
525 public:
526 bool operator()(const Expectation& lhs, const Expectation& rhs) const {
527 return lhs.expectation_base_.get() < rhs.expectation_base_.get();
528 }
529 };
530
531 typedef ::std::set<Expectation, Less> Set;
532
533 Expectation(
zhanyong.wan7c95d832009-10-01 21:56:16 +0000534 const internal::linked_ptr<internal::ExpectationBase>& expectation_base);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000535
536 // Returns the expectation this object references.
537 const internal::linked_ptr<internal::ExpectationBase>&
538 expectation_base() const {
539 return expectation_base_;
540 }
541
542 // A linked_ptr that co-owns the expectation this handle references.
543 internal::linked_ptr<internal::ExpectationBase> expectation_base_;
544};
545
546// A set of expectation handles. Useful in the .After() clause of
547// EXPECT_CALL() for setting the (partial) order of expectations. The
548// syntax:
549//
550// ExpectationSet es;
551// es += EXPECT_CALL(...)...;
552// es += EXPECT_CALL(...)...;
553// EXPECT_CALL(...).After(es)...;
554//
555// sets three expectations where the last one can only be matched
556// after the first two have both been satisfied.
557//
558// This class is copyable and has value semantics.
559class ExpectationSet {
560 public:
561 // A bidirectional iterator that can read a const element in the set.
562 typedef Expectation::Set::const_iterator const_iterator;
563
564 // An object stored in the set. This is an alias of Expectation.
565 typedef Expectation::Set::value_type value_type;
566
567 // Constructs an empty set.
568 ExpectationSet() {}
569
570 // This single-argument ctor must not be explicit, in order to support the
571 // ExpectationSet es = EXPECT_CALL(...);
572 // syntax.
573 ExpectationSet(internal::ExpectationBase& exp) { // NOLINT
574 *this += Expectation(exp);
575 }
576
577 // This single-argument ctor implements implicit conversion from
578 // Expectation and thus must not be explicit. This allows either an
579 // Expectation or an ExpectationSet to be used in .After().
580 ExpectationSet(const Expectation& e) { // NOLINT
581 *this += e;
582 }
583
584 // The compiler-generator ctor and operator= works exactly as
585 // intended, so we don't need to define our own.
586
587 // Returns true iff rhs contains the same set of Expectation objects
588 // as this does.
589 bool operator==(const ExpectationSet& rhs) const {
590 return expectations_ == rhs.expectations_;
591 }
592
593 bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }
594
595 // Implements the syntax
596 // expectation_set += EXPECT_CALL(...);
597 ExpectationSet& operator+=(const Expectation& e) {
598 expectations_.insert(e);
599 return *this;
600 }
601
602 int size() const { return static_cast<int>(expectations_.size()); }
603
604 const_iterator begin() const { return expectations_.begin(); }
605 const_iterator end() const { return expectations_.end(); }
606
607 private:
608 Expectation::Set expectations_;
609};
610
611
shiqiane35fdd92008-12-10 05:08:54 +0000612// Sequence objects are used by a user to specify the relative order
613// in which the expectations should match. They are copyable (we rely
614// on the compiler-defined copy constructor and assignment operator).
vladlosev587c1b32011-05-20 00:42:22 +0000615class GTEST_API_ Sequence {
shiqiane35fdd92008-12-10 05:08:54 +0000616 public:
617 // Constructs an empty sequence.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000618 Sequence() : last_expectation_(new Expectation) {}
shiqiane35fdd92008-12-10 05:08:54 +0000619
620 // Adds an expectation to this sequence. The caller must ensure
621 // that no other thread is accessing this Sequence object.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000622 void AddExpectation(const Expectation& expectation) const;
623
shiqiane35fdd92008-12-10 05:08:54 +0000624 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000625 // The last expectation in this sequence. We use a linked_ptr here
626 // because Sequence objects are copyable and we want the copies to
627 // be aliases. The linked_ptr allows the copies to co-own and share
628 // the same Expectation object.
629 internal::linked_ptr<Expectation> last_expectation_;
shiqiane35fdd92008-12-10 05:08:54 +0000630}; // class Sequence
631
632// An object of this type causes all EXPECT_CALL() statements
633// encountered in its scope to be put in an anonymous sequence. The
634// work is done in the constructor and destructor. You should only
635// create an InSequence object on the stack.
636//
637// The sole purpose for this class is to support easy definition of
638// sequential expectations, e.g.
639//
640// {
641// InSequence dummy; // The name of the object doesn't matter.
642//
643// // The following expectations must match in the order they appear.
644// EXPECT_CALL(a, Bar())...;
645// EXPECT_CALL(a, Baz())...;
646// ...
647// EXPECT_CALL(b, Xyz())...;
648// }
649//
650// You can create InSequence objects in multiple threads, as long as
651// they are used to affect different mock objects. The idea is that
652// each thread can create and set up its own mocks as if it's the only
653// thread. However, for clarity of your tests we recommend you to set
654// up mocks in the main thread unless you have a good reason not to do
655// so.
vladlosev587c1b32011-05-20 00:42:22 +0000656class GTEST_API_ InSequence {
shiqiane35fdd92008-12-10 05:08:54 +0000657 public:
658 InSequence();
659 ~InSequence();
660 private:
661 bool sequence_created_;
662
663 GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT
zhanyong.wanccedc1c2010-08-09 22:46:12 +0000664} GTEST_ATTRIBUTE_UNUSED_;
shiqiane35fdd92008-12-10 05:08:54 +0000665
666namespace internal {
667
668// Points to the implicit sequence introduced by a living InSequence
669// object (if any) in the current thread or NULL.
vladlosev587c1b32011-05-20 00:42:22 +0000670GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;
shiqiane35fdd92008-12-10 05:08:54 +0000671
672// Base class for implementing expectations.
673//
674// There are two reasons for having a type-agnostic base class for
675// Expectation:
676//
677// 1. We need to store collections of expectations of different
678// types (e.g. all pre-requisites of a particular expectation, all
679// expectations in a sequence). Therefore these expectation objects
680// must share a common base class.
681//
682// 2. We can avoid binary code bloat by moving methods not depending
683// on the template argument of Expectation to the base class.
684//
685// This class is internal and mustn't be used by user code directly.
vladlosev587c1b32011-05-20 00:42:22 +0000686class GTEST_API_ ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000687 public:
vladlosev6c54a5e2009-10-21 06:15:34 +0000688 // source_text is the EXPECT_CALL(...) source that created this Expectation.
689 ExpectationBase(const char* file, int line, const string& source_text);
shiqiane35fdd92008-12-10 05:08:54 +0000690
691 virtual ~ExpectationBase();
692
693 // Where in the source file was the expectation spec defined?
694 const char* file() const { return file_; }
695 int line() const { return line_; }
vladlosev6c54a5e2009-10-21 06:15:34 +0000696 const char* source_text() const { return source_text_.c_str(); }
shiqiane35fdd92008-12-10 05:08:54 +0000697 // Returns the cardinality specified in the expectation spec.
698 const Cardinality& cardinality() const { return cardinality_; }
699
700 // Describes the source file location of this expectation.
701 void DescribeLocationTo(::std::ostream* os) const {
vladloseve5121b52011-02-11 23:50:38 +0000702 *os << FormatFileLocation(file(), line()) << " ";
shiqiane35fdd92008-12-10 05:08:54 +0000703 }
704
705 // Describes how many times a function call matching this
706 // expectation has occurred.
vladlosev4d60a592011-10-24 21:16:22 +0000707 void DescribeCallCountTo(::std::ostream* os) const
708 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +0000709
710 // If this mock method has an extra matcher (i.e. .With(matcher)),
711 // describes it to the ostream.
712 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;
zhanyong.wan32de5f52009-12-23 00:13:23 +0000713
shiqiane35fdd92008-12-10 05:08:54 +0000714 protected:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000715 friend class ::testing::Expectation;
zhanyong.waned6c9272011-02-23 19:39:27 +0000716 friend class UntypedFunctionMockerBase;
shiqiane35fdd92008-12-10 05:08:54 +0000717
718 enum Clause {
719 // Don't change the order of the enum members!
zhanyong.wanbf550852009-06-09 06:09:53 +0000720 kNone,
721 kWith,
722 kTimes,
723 kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000724 kAfter,
zhanyong.wanbf550852009-06-09 06:09:53 +0000725 kWillOnce,
726 kWillRepeatedly,
vladlosevab29bb62011-04-08 01:32:32 +0000727 kRetiresOnSaturation
shiqiane35fdd92008-12-10 05:08:54 +0000728 };
729
zhanyong.waned6c9272011-02-23 19:39:27 +0000730 typedef std::vector<const void*> UntypedActions;
731
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000732 // Returns an Expectation object that references and co-owns this
733 // expectation.
734 virtual Expectation GetHandle() = 0;
735
shiqiane35fdd92008-12-10 05:08:54 +0000736 // Asserts that the EXPECT_CALL() statement has the given property.
737 void AssertSpecProperty(bool property, const string& failure_message) const {
738 Assert(property, file_, line_, failure_message);
739 }
740
741 // Expects that the EXPECT_CALL() statement has the given property.
742 void ExpectSpecProperty(bool property, const string& failure_message) const {
743 Expect(property, file_, line_, failure_message);
744 }
745
746 // Explicitly specifies the cardinality of this expectation. Used
747 // by the subclasses to implement the .Times() clause.
748 void SpecifyCardinality(const Cardinality& cardinality);
749
750 // Returns true iff the user specified the cardinality explicitly
751 // using a .Times().
752 bool cardinality_specified() const { return cardinality_specified_; }
753
754 // Sets the cardinality of this expectation spec.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000755 void set_cardinality(const Cardinality& a_cardinality) {
756 cardinality_ = a_cardinality;
shiqiane35fdd92008-12-10 05:08:54 +0000757 }
758
759 // The following group of methods should only be called after the
760 // EXPECT_CALL() statement, and only when g_gmock_mutex is held by
761 // the current thread.
762
763 // Retires all pre-requisites of this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000764 void RetireAllPreRequisites()
765 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000766
767 // Returns true iff this expectation is retired.
vladlosev4d60a592011-10-24 21:16:22 +0000768 bool is_retired() const
769 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000770 g_gmock_mutex.AssertHeld();
771 return retired_;
772 }
773
774 // Retires this expectation.
vladlosev4d60a592011-10-24 21:16:22 +0000775 void Retire()
776 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000777 g_gmock_mutex.AssertHeld();
778 retired_ = true;
779 }
780
781 // Returns true iff this expectation is satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000782 bool IsSatisfied() const
783 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000784 g_gmock_mutex.AssertHeld();
785 return cardinality().IsSatisfiedByCallCount(call_count_);
786 }
787
788 // Returns true iff this expectation is saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000789 bool IsSaturated() const
790 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000791 g_gmock_mutex.AssertHeld();
792 return cardinality().IsSaturatedByCallCount(call_count_);
793 }
794
795 // Returns true iff this expectation is over-saturated.
vladlosev4d60a592011-10-24 21:16:22 +0000796 bool IsOverSaturated() const
797 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000798 g_gmock_mutex.AssertHeld();
799 return cardinality().IsOverSaturatedByCallCount(call_count_);
800 }
801
802 // Returns true iff all pre-requisites of this expectation are satisfied.
vladlosev4d60a592011-10-24 21:16:22 +0000803 bool AllPrerequisitesAreSatisfied() const
804 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000805
806 // Adds unsatisfied pre-requisites of this expectation to 'result'.
vladlosev4d60a592011-10-24 21:16:22 +0000807 void FindUnsatisfiedPrerequisites(ExpectationSet* result) const
808 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
shiqiane35fdd92008-12-10 05:08:54 +0000809
810 // Returns the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000811 int call_count() const
812 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000813 g_gmock_mutex.AssertHeld();
814 return call_count_;
815 }
816
817 // Increments the number this expectation has been invoked.
vladlosev4d60a592011-10-24 21:16:22 +0000818 void IncrementCallCount()
819 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +0000820 g_gmock_mutex.AssertHeld();
821 call_count_++;
822 }
823
zhanyong.waned6c9272011-02-23 19:39:27 +0000824 // Checks the action count (i.e. the number of WillOnce() and
825 // WillRepeatedly() clauses) against the cardinality if this hasn't
826 // been done before. Prints a warning if there are too many or too
827 // few actions.
vladlosev4d60a592011-10-24 21:16:22 +0000828 void CheckActionCountIfNotDone() const
829 GTEST_LOCK_EXCLUDED_(mutex_);
zhanyong.waned6c9272011-02-23 19:39:27 +0000830
shiqiane35fdd92008-12-10 05:08:54 +0000831 friend class ::testing::Sequence;
832 friend class ::testing::internal::ExpectationTester;
833
834 template <typename Function>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000835 friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +0000836
zhanyong.waned6c9272011-02-23 19:39:27 +0000837 // Implements the .Times() clause.
838 void UntypedTimes(const Cardinality& a_cardinality);
839
shiqiane35fdd92008-12-10 05:08:54 +0000840 // This group of fields are part of the spec and won't change after
841 // an EXPECT_CALL() statement finishes.
vladlosev6c54a5e2009-10-21 06:15:34 +0000842 const char* file_; // The file that contains the expectation.
843 int line_; // The line number of the expectation.
844 const string source_text_; // The EXPECT_CALL(...) source text.
shiqiane35fdd92008-12-10 05:08:54 +0000845 // True iff the cardinality is specified explicitly.
846 bool cardinality_specified_;
847 Cardinality cardinality_; // The cardinality of the expectation.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000848 // The immediate pre-requisites (i.e. expectations that must be
849 // satisfied before this expectation can be matched) of this
850 // expectation. We use linked_ptr in the set because we want an
851 // Expectation object to be co-owned by its FunctionMocker and its
852 // successors. This allows multiple mock objects to be deleted at
853 // different times.
854 ExpectationSet immediate_prerequisites_;
shiqiane35fdd92008-12-10 05:08:54 +0000855
856 // This group of fields are the current state of the expectation,
857 // and can change as the mock function is called.
858 int call_count_; // How many times this expectation has been invoked.
859 bool retired_; // True iff this expectation has retired.
zhanyong.waned6c9272011-02-23 19:39:27 +0000860 UntypedActions untyped_actions_;
861 bool extra_matcher_specified_;
862 bool repeated_action_specified_; // True if a WillRepeatedly() was specified.
863 bool retires_on_saturation_;
864 Clause last_clause_;
865 mutable bool action_count_checked_; // Under mutex_.
866 mutable Mutex mutex_; // Protects action_count_checked_.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000867
868 GTEST_DISALLOW_ASSIGN_(ExpectationBase);
shiqiane35fdd92008-12-10 05:08:54 +0000869}; // class ExpectationBase
870
871// Impements an expectation for the given function type.
872template <typename F>
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000873class TypedExpectation : public ExpectationBase {
shiqiane35fdd92008-12-10 05:08:54 +0000874 public:
875 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
876 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
877 typedef typename Function<F>::Result Result;
878
vladlosev6c54a5e2009-10-21 06:15:34 +0000879 TypedExpectation(FunctionMockerBase<F>* owner,
zhanyong.wan32de5f52009-12-23 00:13:23 +0000880 const char* a_file, int a_line, const string& a_source_text,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000881 const ArgumentMatcherTuple& m)
zhanyong.wan32de5f52009-12-23 00:13:23 +0000882 : ExpectationBase(a_file, a_line, a_source_text),
shiqiane35fdd92008-12-10 05:08:54 +0000883 owner_(owner),
884 matchers_(m),
zhanyong.wan18490652009-05-11 18:54:08 +0000885 // By default, extra_matcher_ should match anything. However,
886 // we cannot initialize it with _ as that triggers a compiler
887 // bug in Symbian's C++ compiler (cannot decide between two
888 // overloaded constructors of Matcher<const ArgumentTuple&>).
889 extra_matcher_(A<const ArgumentTuple&>()),
zhanyong.waned6c9272011-02-23 19:39:27 +0000890 repeated_action_(DoDefault()) {}
shiqiane35fdd92008-12-10 05:08:54 +0000891
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000892 virtual ~TypedExpectation() {
shiqiane35fdd92008-12-10 05:08:54 +0000893 // Check the validity of the action count if it hasn't been done
894 // yet (for example, if the expectation was never used).
895 CheckActionCountIfNotDone();
zhanyong.waned6c9272011-02-23 19:39:27 +0000896 for (UntypedActions::const_iterator it = untyped_actions_.begin();
897 it != untyped_actions_.end(); ++it) {
898 delete static_cast<const Action<F>*>(*it);
899 }
shiqiane35fdd92008-12-10 05:08:54 +0000900 }
901
zhanyong.wanbf550852009-06-09 06:09:53 +0000902 // Implements the .With() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000903 TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000904 if (last_clause_ == kWith) {
shiqiane35fdd92008-12-10 05:08:54 +0000905 ExpectSpecProperty(false,
zhanyong.wanbf550852009-06-09 06:09:53 +0000906 ".With() cannot appear "
shiqiane35fdd92008-12-10 05:08:54 +0000907 "more than once in an EXPECT_CALL().");
908 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +0000909 ExpectSpecProperty(last_clause_ < kWith,
910 ".With() must be the first "
shiqiane35fdd92008-12-10 05:08:54 +0000911 "clause in an EXPECT_CALL().");
912 }
zhanyong.wanbf550852009-06-09 06:09:53 +0000913 last_clause_ = kWith;
shiqiane35fdd92008-12-10 05:08:54 +0000914
915 extra_matcher_ = m;
vladlosev6c54a5e2009-10-21 06:15:34 +0000916 extra_matcher_specified_ = true;
shiqiane35fdd92008-12-10 05:08:54 +0000917 return *this;
918 }
919
920 // Implements the .Times() clause.
zhanyong.wan32de5f52009-12-23 00:13:23 +0000921 TypedExpectation& Times(const Cardinality& a_cardinality) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000922 ExpectationBase::UntypedTimes(a_cardinality);
shiqiane35fdd92008-12-10 05:08:54 +0000923 return *this;
924 }
925
926 // Implements the .Times() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000927 TypedExpectation& Times(int n) {
shiqiane35fdd92008-12-10 05:08:54 +0000928 return Times(Exactly(n));
929 }
930
931 // Implements the .InSequence() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000932 TypedExpectation& InSequence(const Sequence& s) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000933 ExpectSpecProperty(last_clause_ <= kInSequence,
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000934 ".InSequence() cannot appear after .After(),"
935 " .WillOnce(), .WillRepeatedly(), or "
shiqiane35fdd92008-12-10 05:08:54 +0000936 ".RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000937 last_clause_ = kInSequence;
shiqiane35fdd92008-12-10 05:08:54 +0000938
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000939 s.AddExpectation(GetHandle());
shiqiane35fdd92008-12-10 05:08:54 +0000940 return *this;
941 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000942 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {
shiqiane35fdd92008-12-10 05:08:54 +0000943 return InSequence(s1).InSequence(s2);
944 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000945 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
946 const Sequence& s3) {
shiqiane35fdd92008-12-10 05:08:54 +0000947 return InSequence(s1, s2).InSequence(s3);
948 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000949 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
950 const Sequence& s3, const Sequence& s4) {
shiqiane35fdd92008-12-10 05:08:54 +0000951 return InSequence(s1, s2, s3).InSequence(s4);
952 }
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000953 TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,
954 const Sequence& s3, const Sequence& s4,
955 const Sequence& s5) {
shiqiane35fdd92008-12-10 05:08:54 +0000956 return InSequence(s1, s2, s3, s4).InSequence(s5);
957 }
958
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000959 // Implements that .After() clause.
960 TypedExpectation& After(const ExpectationSet& s) {
961 ExpectSpecProperty(last_clause_ <= kAfter,
962 ".After() cannot appear after .WillOnce(),"
963 " .WillRepeatedly(), or "
964 ".RetiresOnSaturation().");
965 last_clause_ = kAfter;
966
967 for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {
968 immediate_prerequisites_ += *it;
969 }
970 return *this;
971 }
972 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {
973 return After(s1).After(s2);
974 }
975 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
976 const ExpectationSet& s3) {
977 return After(s1, s2).After(s3);
978 }
979 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
980 const ExpectationSet& s3, const ExpectationSet& s4) {
981 return After(s1, s2, s3).After(s4);
982 }
983 TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,
984 const ExpectationSet& s3, const ExpectationSet& s4,
985 const ExpectationSet& s5) {
986 return After(s1, s2, s3, s4).After(s5);
987 }
988
shiqiane35fdd92008-12-10 05:08:54 +0000989 // Implements the .WillOnce() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +0000990 TypedExpectation& WillOnce(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +0000991 ExpectSpecProperty(last_clause_ <= kWillOnce,
shiqiane35fdd92008-12-10 05:08:54 +0000992 ".WillOnce() cannot appear after "
993 ".WillRepeatedly() or .RetiresOnSaturation().");
zhanyong.wanbf550852009-06-09 06:09:53 +0000994 last_clause_ = kWillOnce;
shiqiane35fdd92008-12-10 05:08:54 +0000995
zhanyong.waned6c9272011-02-23 19:39:27 +0000996 untyped_actions_.push_back(new Action<F>(action));
shiqiane35fdd92008-12-10 05:08:54 +0000997 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +0000998 set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +0000999 }
1000 return *this;
1001 }
1002
1003 // Implements the .WillRepeatedly() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001004 TypedExpectation& WillRepeatedly(const Action<F>& action) {
zhanyong.wanbf550852009-06-09 06:09:53 +00001005 if (last_clause_ == kWillRepeatedly) {
shiqiane35fdd92008-12-10 05:08:54 +00001006 ExpectSpecProperty(false,
1007 ".WillRepeatedly() cannot appear "
1008 "more than once in an EXPECT_CALL().");
1009 } else {
zhanyong.wanbf550852009-06-09 06:09:53 +00001010 ExpectSpecProperty(last_clause_ < kWillRepeatedly,
shiqiane35fdd92008-12-10 05:08:54 +00001011 ".WillRepeatedly() cannot appear "
1012 "after .RetiresOnSaturation().");
1013 }
zhanyong.wanbf550852009-06-09 06:09:53 +00001014 last_clause_ = kWillRepeatedly;
shiqiane35fdd92008-12-10 05:08:54 +00001015 repeated_action_specified_ = true;
1016
1017 repeated_action_ = action;
1018 if (!cardinality_specified()) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001019 set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));
shiqiane35fdd92008-12-10 05:08:54 +00001020 }
1021
1022 // Now that no more action clauses can be specified, we check
1023 // whether their count makes sense.
1024 CheckActionCountIfNotDone();
1025 return *this;
1026 }
1027
1028 // Implements the .RetiresOnSaturation() clause.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001029 TypedExpectation& RetiresOnSaturation() {
zhanyong.wanbf550852009-06-09 06:09:53 +00001030 ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,
shiqiane35fdd92008-12-10 05:08:54 +00001031 ".RetiresOnSaturation() cannot appear "
1032 "more than once.");
zhanyong.wanbf550852009-06-09 06:09:53 +00001033 last_clause_ = kRetiresOnSaturation;
shiqiane35fdd92008-12-10 05:08:54 +00001034 retires_on_saturation_ = true;
1035
1036 // Now that no more action clauses can be specified, we check
1037 // whether their count makes sense.
1038 CheckActionCountIfNotDone();
1039 return *this;
1040 }
1041
1042 // Returns the matchers for the arguments as specified inside the
1043 // EXPECT_CALL() macro.
1044 const ArgumentMatcherTuple& matchers() const {
1045 return matchers_;
1046 }
1047
zhanyong.wanbf550852009-06-09 06:09:53 +00001048 // Returns the matcher specified by the .With() clause.
shiqiane35fdd92008-12-10 05:08:54 +00001049 const Matcher<const ArgumentTuple&>& extra_matcher() const {
1050 return extra_matcher_;
1051 }
1052
shiqiane35fdd92008-12-10 05:08:54 +00001053 // Returns the action specified by the .WillRepeatedly() clause.
1054 const Action<F>& repeated_action() const { return repeated_action_; }
1055
zhanyong.waned6c9272011-02-23 19:39:27 +00001056 // If this mock method has an extra matcher (i.e. .With(matcher)),
1057 // describes it to the ostream.
1058 virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001059 if (extra_matcher_specified_) {
1060 *os << " Expected args: ";
1061 extra_matcher_.DescribeTo(os);
1062 *os << "\n";
1063 }
1064 }
1065
shiqiane35fdd92008-12-10 05:08:54 +00001066 private:
1067 template <typename Function>
1068 friend class FunctionMockerBase;
1069
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001070 // Returns an Expectation object that references and co-owns this
1071 // expectation.
1072 virtual Expectation GetHandle() {
1073 return owner_->GetHandleOf(this);
1074 }
1075
shiqiane35fdd92008-12-10 05:08:54 +00001076 // The following methods will be called only after the EXPECT_CALL()
1077 // statement finishes and when the current thread holds
1078 // g_gmock_mutex.
1079
1080 // Returns true iff this expectation matches the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001081 bool Matches(const ArgumentTuple& args) const
1082 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001083 g_gmock_mutex.AssertHeld();
1084 return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);
1085 }
1086
1087 // Returns true iff this expectation should handle the given arguments.
vladlosev4d60a592011-10-24 21:16:22 +00001088 bool ShouldHandleArguments(const ArgumentTuple& args) const
1089 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001090 g_gmock_mutex.AssertHeld();
1091
1092 // In case the action count wasn't checked when the expectation
1093 // was defined (e.g. if this expectation has no WillRepeatedly()
1094 // or RetiresOnSaturation() clause), we check it when the
1095 // expectation is used for the first time.
1096 CheckActionCountIfNotDone();
1097 return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);
1098 }
1099
1100 // Describes the result of matching the arguments against this
1101 // expectation to the given ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001102 void ExplainMatchResultTo(
1103 const ArgumentTuple& args,
1104 ::std::ostream* os) const
1105 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001106 g_gmock_mutex.AssertHeld();
1107
1108 if (is_retired()) {
1109 *os << " Expected: the expectation is active\n"
1110 << " Actual: it is retired\n";
1111 } else if (!Matches(args)) {
1112 if (!TupleMatches(matchers_, args)) {
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001113 ExplainMatchFailureTupleTo(matchers_, args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001114 }
zhanyong.wan82113312010-01-08 21:55:40 +00001115 StringMatchResultListener listener;
1116 if (!extra_matcher_.MatchAndExplain(args, &listener)) {
zhanyong.wan2661c682009-06-09 05:42:12 +00001117 *os << " Expected args: ";
shiqiane35fdd92008-12-10 05:08:54 +00001118 extra_matcher_.DescribeTo(os);
zhanyong.wan2661c682009-06-09 05:42:12 +00001119 *os << "\n Actual: don't match";
shiqiane35fdd92008-12-10 05:08:54 +00001120
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001121 internal::PrintIfNotEmpty(listener.str(), os);
shiqiane35fdd92008-12-10 05:08:54 +00001122 *os << "\n";
1123 }
1124 } else if (!AllPrerequisitesAreSatisfied()) {
1125 *os << " Expected: all pre-requisites are satisfied\n"
1126 << " Actual: the following immediate pre-requisites "
1127 << "are not satisfied:\n";
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001128 ExpectationSet unsatisfied_prereqs;
shiqiane35fdd92008-12-10 05:08:54 +00001129 FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);
1130 int i = 0;
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001131 for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();
shiqiane35fdd92008-12-10 05:08:54 +00001132 it != unsatisfied_prereqs.end(); ++it) {
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001133 it->expectation_base()->DescribeLocationTo(os);
shiqiane35fdd92008-12-10 05:08:54 +00001134 *os << "pre-requisite #" << i++ << "\n";
1135 }
1136 *os << " (end of pre-requisites)\n";
1137 } else {
1138 // This line is here just for completeness' sake. It will never
zhanyong.wanb1c7f932010-03-24 17:35:11 +00001139 // be executed as currently the ExplainMatchResultTo() function
shiqiane35fdd92008-12-10 05:08:54 +00001140 // is called only when the mock function call does NOT match the
1141 // expectation.
1142 *os << "The call matches the expectation.\n";
1143 }
1144 }
1145
1146 // Returns the action that should be taken for the current invocation.
vladlosev4d60a592011-10-24 21:16:22 +00001147 const Action<F>& GetCurrentAction(
1148 const FunctionMockerBase<F>* mocker,
1149 const ArgumentTuple& args) const
1150 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001151 g_gmock_mutex.AssertHeld();
1152 const int count = call_count();
1153 Assert(count >= 1, __FILE__, __LINE__,
1154 "call_count() is <= 0 when GetCurrentAction() is "
1155 "called - this should never happen.");
1156
zhanyong.waned6c9272011-02-23 19:39:27 +00001157 const int action_count = static_cast<int>(untyped_actions_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001158 if (action_count > 0 && !repeated_action_specified_ &&
1159 count > action_count) {
1160 // If there is at least one WillOnce() and no WillRepeatedly(),
1161 // we warn the user when the WillOnce() clauses ran out.
1162 ::std::stringstream ss;
1163 DescribeLocationTo(&ss);
vladlosev6c54a5e2009-10-21 06:15:34 +00001164 ss << "Actions ran out in " << source_text() << "...\n"
shiqiane35fdd92008-12-10 05:08:54 +00001165 << "Called " << count << " times, but only "
1166 << action_count << " WillOnce()"
1167 << (action_count == 1 ? " is" : "s are") << " specified - ";
1168 mocker->DescribeDefaultActionTo(args, &ss);
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001169 Log(kWarning, ss.str(), 1);
shiqiane35fdd92008-12-10 05:08:54 +00001170 }
1171
zhanyong.waned6c9272011-02-23 19:39:27 +00001172 return count <= action_count ?
1173 *static_cast<const Action<F>*>(untyped_actions_[count - 1]) :
1174 repeated_action();
shiqiane35fdd92008-12-10 05:08:54 +00001175 }
1176
1177 // Given the arguments of a mock function call, if the call will
1178 // over-saturate this expectation, returns the default action;
1179 // otherwise, returns the next action in this expectation. Also
1180 // describes *what* happened to 'what', and explains *why* Google
1181 // Mock does it to 'why'. This method is not const as it calls
zhanyong.waned6c9272011-02-23 19:39:27 +00001182 // IncrementCallCount(). A return value of NULL means the default
1183 // action.
vladlosev4d60a592011-10-24 21:16:22 +00001184 const Action<F>* GetActionForArguments(
1185 const FunctionMockerBase<F>* mocker,
1186 const ArgumentTuple& args,
1187 ::std::ostream* what,
1188 ::std::ostream* why)
1189 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001190 g_gmock_mutex.AssertHeld();
1191 if (IsSaturated()) {
1192 // We have an excessive call.
1193 IncrementCallCount();
1194 *what << "Mock function called more times than expected - ";
1195 mocker->DescribeDefaultActionTo(args, what);
1196 DescribeCallCountTo(why);
1197
zhanyong.waned6c9272011-02-23 19:39:27 +00001198 // TODO(wan@google.com): allow the user to control whether
1199 // unexpected calls should fail immediately or continue using a
1200 // flag --gmock_unexpected_calls_are_fatal.
1201 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001202 }
1203
1204 IncrementCallCount();
1205 RetireAllPreRequisites();
1206
zhanyong.waned6c9272011-02-23 19:39:27 +00001207 if (retires_on_saturation_ && IsSaturated()) {
shiqiane35fdd92008-12-10 05:08:54 +00001208 Retire();
1209 }
1210
1211 // Must be done after IncrementCount()!
vladlosev6c54a5e2009-10-21 06:15:34 +00001212 *what << "Mock function call matches " << source_text() <<"...\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001213 return &(GetCurrentAction(mocker, args));
shiqiane35fdd92008-12-10 05:08:54 +00001214 }
1215
1216 // All the fields below won't change once the EXPECT_CALL()
1217 // statement finishes.
1218 FunctionMockerBase<F>* const owner_;
1219 ArgumentMatcherTuple matchers_;
1220 Matcher<const ArgumentTuple&> extra_matcher_;
shiqiane35fdd92008-12-10 05:08:54 +00001221 Action<F> repeated_action_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001222
1223 GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation);
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001224}; // class TypedExpectation
shiqiane35fdd92008-12-10 05:08:54 +00001225
1226// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for
1227// specifying the default behavior of, or expectation on, a mock
1228// function.
1229
1230// Note: class MockSpec really belongs to the ::testing namespace.
1231// However if we define it in ::testing, MSVC will complain when
1232// classes in ::testing::internal declare it as a friend class
1233// template. To workaround this compiler bug, we define MockSpec in
1234// ::testing::internal and import it into ::testing.
1235
zhanyong.waned6c9272011-02-23 19:39:27 +00001236// Logs a message including file and line number information.
vladlosev587c1b32011-05-20 00:42:22 +00001237GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
1238 const char* file, int line,
1239 const string& message);
zhanyong.waned6c9272011-02-23 19:39:27 +00001240
shiqiane35fdd92008-12-10 05:08:54 +00001241template <typename F>
1242class MockSpec {
1243 public:
1244 typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;
1245 typedef typename internal::Function<F>::ArgumentMatcherTuple
1246 ArgumentMatcherTuple;
1247
1248 // Constructs a MockSpec object, given the function mocker object
1249 // that the spec is associated with.
1250 explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker)
1251 : function_mocker_(function_mocker) {}
1252
1253 // Adds a new default action spec to the function mocker and returns
1254 // the newly created spec.
zhanyong.waned6c9272011-02-23 19:39:27 +00001255 internal::OnCallSpec<F>& InternalDefaultActionSetAt(
shiqiane35fdd92008-12-10 05:08:54 +00001256 const char* file, int line, const char* obj, const char* call) {
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001257 LogWithLocation(internal::kInfo, file, line,
shiqiane35fdd92008-12-10 05:08:54 +00001258 string("ON_CALL(") + obj + ", " + call + ") invoked");
zhanyong.waned6c9272011-02-23 19:39:27 +00001259 return function_mocker_->AddNewOnCallSpec(file, line, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001260 }
1261
1262 // Adds a new expectation spec to the function mocker and returns
1263 // the newly created spec.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001264 internal::TypedExpectation<F>& InternalExpectedAt(
shiqiane35fdd92008-12-10 05:08:54 +00001265 const char* file, int line, const char* obj, const char* call) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001266 const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")");
zhanyong.wan2fd619e2012-05-31 20:40:56 +00001267 LogWithLocation(internal::kInfo, file, line, source_text + " invoked");
vladlosev6c54a5e2009-10-21 06:15:34 +00001268 return function_mocker_->AddNewExpectation(
1269 file, line, source_text, matchers_);
shiqiane35fdd92008-12-10 05:08:54 +00001270 }
1271
1272 private:
1273 template <typename Function>
1274 friend class internal::FunctionMocker;
1275
1276 void SetMatchers(const ArgumentMatcherTuple& matchers) {
1277 matchers_ = matchers;
1278 }
1279
shiqiane35fdd92008-12-10 05:08:54 +00001280 // The function mocker that owns this spec.
1281 internal::FunctionMockerBase<F>* const function_mocker_;
1282 // The argument matchers specified in the spec.
1283 ArgumentMatcherTuple matchers_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001284
1285 GTEST_DISALLOW_ASSIGN_(MockSpec);
shiqiane35fdd92008-12-10 05:08:54 +00001286}; // class MockSpec
1287
1288// MSVC warns about using 'this' in base member initializer list, so
1289// we need to temporarily disable the warning. We have to do it for
1290// the entire class to suppress the warning, even though it's about
1291// the constructor only.
1292
1293#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001294# pragma warning(push) // Saves the current warning state.
1295# pragma warning(disable:4355) // Temporarily disables warning 4355.
shiqiane35fdd92008-12-10 05:08:54 +00001296#endif // _MSV_VER
1297
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001298// C++ treats the void type specially. For example, you cannot define
1299// a void-typed variable or pass a void value to a function.
1300// ActionResultHolder<T> holds a value of type T, where T must be a
1301// copyable type or void (T doesn't need to be default-constructable).
1302// It hides the syntactic difference between void and other types, and
1303// is used to unify the code for invoking both void-returning and
zhanyong.waned6c9272011-02-23 19:39:27 +00001304// non-void-returning mock functions.
1305
1306// Untyped base class for ActionResultHolder<T>.
1307class UntypedActionResultHolderBase {
1308 public:
1309 virtual ~UntypedActionResultHolderBase() {}
1310
1311 // Prints the held value as an action's result to os.
1312 virtual void PrintAsActionResult(::std::ostream* os) const = 0;
1313};
1314
1315// This generic definition is used when T is not void.
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001316template <typename T>
zhanyong.waned6c9272011-02-23 19:39:27 +00001317class ActionResultHolder : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001318 public:
zhanyong.wan32de5f52009-12-23 00:13:23 +00001319 explicit ActionResultHolder(T a_value) : value_(a_value) {}
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001320
1321 // The compiler-generated copy constructor and assignment operator
1322 // are exactly what we need, so we don't need to define them.
1323
zhanyong.waned6c9272011-02-23 19:39:27 +00001324 // Returns the held value and deletes this object.
1325 T GetValueAndDelete() const {
1326 T retval(value_);
1327 delete this;
1328 return retval;
1329 }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001330
1331 // Prints the held value as an action's result to os.
zhanyong.waned6c9272011-02-23 19:39:27 +00001332 virtual void PrintAsActionResult(::std::ostream* os) const {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001333 *os << "\n Returns: ";
vladloseve2e8ba42010-05-13 18:16:03 +00001334 // T may be a reference type, so we don't use UniversalPrint().
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001335 UniversalPrinter<T>::Print(value_, os);
1336 }
1337
1338 // Performs the given mock function's default action and returns the
zhanyong.waned6c9272011-02-23 19:39:27 +00001339 // result in a new-ed ActionResultHolder.
1340 template <typename F>
1341 static ActionResultHolder* PerformDefaultAction(
1342 const FunctionMockerBase<F>* func_mocker,
1343 const typename Function<F>::ArgumentTuple& args,
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001344 const string& call_description) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001345 return new ActionResultHolder(
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001346 func_mocker->PerformDefaultAction(args, call_description));
1347 }
1348
zhanyong.waned6c9272011-02-23 19:39:27 +00001349 // Performs the given action and returns the result in a new-ed
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001350 // ActionResultHolder.
zhanyong.waned6c9272011-02-23 19:39:27 +00001351 template <typename F>
1352 static ActionResultHolder*
1353 PerformAction(const Action<F>& action,
1354 const typename Function<F>::ArgumentTuple& args) {
1355 return new ActionResultHolder(action.Perform(args));
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001356 }
1357
1358 private:
1359 T value_;
zhanyong.wan32de5f52009-12-23 00:13:23 +00001360
1361 // T could be a reference type, so = isn't supported.
1362 GTEST_DISALLOW_ASSIGN_(ActionResultHolder);
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001363};
1364
1365// Specialization for T = void.
1366template <>
zhanyong.waned6c9272011-02-23 19:39:27 +00001367class ActionResultHolder<void> : public UntypedActionResultHolderBase {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001368 public:
zhanyong.waned6c9272011-02-23 19:39:27 +00001369 void GetValueAndDelete() const { delete this; }
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001370
zhanyong.waned6c9272011-02-23 19:39:27 +00001371 virtual void PrintAsActionResult(::std::ostream* /* os */) const {}
1372
1373 // Performs the given mock function's default action and returns NULL;
1374 template <typename F>
1375 static ActionResultHolder* PerformDefaultAction(
1376 const FunctionMockerBase<F>* func_mocker,
1377 const typename Function<F>::ArgumentTuple& args,
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001378 const string& call_description) {
1379 func_mocker->PerformDefaultAction(args, call_description);
zhanyong.waned6c9272011-02-23 19:39:27 +00001380 return NULL;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001381 }
1382
zhanyong.waned6c9272011-02-23 19:39:27 +00001383 // Performs the given action and returns NULL.
1384 template <typename F>
1385 static ActionResultHolder* PerformAction(
1386 const Action<F>& action,
1387 const typename Function<F>::ArgumentTuple& args) {
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001388 action.Perform(args);
zhanyong.waned6c9272011-02-23 19:39:27 +00001389 return NULL;
zhanyong.wan9413f2f2009-05-29 19:50:06 +00001390 }
1391};
1392
shiqiane35fdd92008-12-10 05:08:54 +00001393// The base of the function mocker class for the given function type.
1394// We put the methods in this class instead of its child to avoid code
1395// bloat.
1396template <typename F>
1397class FunctionMockerBase : public UntypedFunctionMockerBase {
1398 public:
1399 typedef typename Function<F>::Result Result;
1400 typedef typename Function<F>::ArgumentTuple ArgumentTuple;
1401 typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;
1402
zhanyong.waned6c9272011-02-23 19:39:27 +00001403 FunctionMockerBase() : current_spec_(this) {}
shiqiane35fdd92008-12-10 05:08:54 +00001404
1405 // The destructor verifies that all expectations on this mock
1406 // function have been satisfied. If not, it will report Google Test
1407 // non-fatal failures for the violations.
vladlosev4d60a592011-10-24 21:16:22 +00001408 virtual ~FunctionMockerBase()
1409 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001410 MutexLock l(&g_gmock_mutex);
1411 VerifyAndClearExpectationsLocked();
1412 Mock::UnregisterLocked(this);
zhanyong.waned6c9272011-02-23 19:39:27 +00001413 ClearDefaultActionsLocked();
shiqiane35fdd92008-12-10 05:08:54 +00001414 }
1415
1416 // Returns the ON_CALL spec that matches this mock function with the
1417 // given arguments; returns NULL if no matching ON_CALL is found.
1418 // L = *
zhanyong.waned6c9272011-02-23 19:39:27 +00001419 const OnCallSpec<F>* FindOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001420 const ArgumentTuple& args) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001421 for (UntypedOnCallSpecs::const_reverse_iterator it
1422 = untyped_on_call_specs_.rbegin();
1423 it != untyped_on_call_specs_.rend(); ++it) {
1424 const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);
1425 if (spec->Matches(args))
1426 return spec;
shiqiane35fdd92008-12-10 05:08:54 +00001427 }
1428
1429 return NULL;
1430 }
1431
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001432 // Performs the default action of this mock function on the given
1433 // arguments and returns the result. Asserts (or throws if
1434 // exceptions are enabled) with a helpful call descrption if there
1435 // is no valid return value. This method doesn't depend on the
1436 // mutable state of this object, and thus can be called concurrently
1437 // without locking.
shiqiane35fdd92008-12-10 05:08:54 +00001438 // L = *
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001439 Result PerformDefaultAction(const ArgumentTuple& args,
1440 const string& call_description) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001441 const OnCallSpec<F>* const spec =
1442 this->FindOnCallSpec(args);
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001443 if (spec != NULL) {
1444 return spec->GetAction().Perform(args);
1445 }
zhanyong.wanedd4ab42013-02-28 22:58:51 +00001446 const string message = call_description +
1447 "\n The mock function has no default action "
1448 "set, and its return type has no default value set.";
1449#if GTEST_HAS_EXCEPTIONS
1450 if (!DefaultValue<Result>::Exists()) {
1451 throw std::runtime_error(message);
1452 }
1453#else
1454 Assert(DefaultValue<Result>::Exists(), "", -1, message);
1455#endif
zhanyong.wan5b95fa72009-01-27 22:28:45 +00001456 return DefaultValue<Result>::Get();
shiqiane35fdd92008-12-10 05:08:54 +00001457 }
1458
zhanyong.waned6c9272011-02-23 19:39:27 +00001459 // Performs the default action with the given arguments and returns
1460 // the action's result. The call description string will be used in
1461 // the error message to describe the call in the case the default
1462 // action fails. The caller is responsible for deleting the result.
1463 // L = *
1464 virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction(
1465 const void* untyped_args, // must point to an ArgumentTuple
1466 const string& call_description) const {
1467 const ArgumentTuple& args =
1468 *static_cast<const ArgumentTuple*>(untyped_args);
1469 return ResultHolder::PerformDefaultAction(this, args, call_description);
shiqiane35fdd92008-12-10 05:08:54 +00001470 }
1471
zhanyong.waned6c9272011-02-23 19:39:27 +00001472 // Performs the given action with the given arguments and returns
1473 // the action's result. The caller is responsible for deleting the
1474 // result.
1475 // L = *
1476 virtual UntypedActionResultHolderBase* UntypedPerformAction(
1477 const void* untyped_action, const void* untyped_args) const {
1478 // Make a copy of the action before performing it, in case the
1479 // action deletes the mock object (and thus deletes itself).
1480 const Action<F> action = *static_cast<const Action<F>*>(untyped_action);
1481 const ArgumentTuple& args =
1482 *static_cast<const ArgumentTuple*>(untyped_args);
1483 return ResultHolder::PerformAction(action, args);
1484 }
shiqiane35fdd92008-12-10 05:08:54 +00001485
zhanyong.waned6c9272011-02-23 19:39:27 +00001486 // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():
1487 // clears the ON_CALL()s set on this mock function.
vladlosev4d60a592011-10-24 21:16:22 +00001488 virtual void ClearDefaultActionsLocked()
1489 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001490 g_gmock_mutex.AssertHeld();
vladlosev9bcb5f92011-10-24 23:41:07 +00001491
1492 // Deleting our default actions may trigger other mock objects to be
1493 // deleted, for example if an action contains a reference counted smart
1494 // pointer to that mock object, and that is the last reference. So if we
1495 // delete our actions within the context of the global mutex we may deadlock
1496 // when this method is called again. Instead, make a copy of the set of
1497 // actions to delete, clear our set within the mutex, and then delete the
1498 // actions outside of the mutex.
1499 UntypedOnCallSpecs specs_to_delete;
1500 untyped_on_call_specs_.swap(specs_to_delete);
1501
1502 g_gmock_mutex.Unlock();
zhanyong.waned6c9272011-02-23 19:39:27 +00001503 for (UntypedOnCallSpecs::const_iterator it =
vladlosev9bcb5f92011-10-24 23:41:07 +00001504 specs_to_delete.begin();
1505 it != specs_to_delete.end(); ++it) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001506 delete static_cast<const OnCallSpec<F>*>(*it);
shiqiane35fdd92008-12-10 05:08:54 +00001507 }
vladlosev9bcb5f92011-10-24 23:41:07 +00001508
1509 // Lock the mutex again, since the caller expects it to be locked when we
1510 // return.
1511 g_gmock_mutex.Lock();
shiqiane35fdd92008-12-10 05:08:54 +00001512 }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001513
shiqiane35fdd92008-12-10 05:08:54 +00001514 protected:
1515 template <typename Function>
1516 friend class MockSpec;
1517
zhanyong.waned6c9272011-02-23 19:39:27 +00001518 typedef ActionResultHolder<Result> ResultHolder;
1519
shiqiane35fdd92008-12-10 05:08:54 +00001520 // Returns the result of invoking this mock function with the given
1521 // arguments. This function can be safely called from multiple
1522 // threads concurrently.
vladlosev4d60a592011-10-24 21:16:22 +00001523 Result InvokeWith(const ArgumentTuple& args)
1524 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001525 return static_cast<const ResultHolder*>(
1526 this->UntypedInvokeWith(&args))->GetValueAndDelete();
1527 }
shiqiane35fdd92008-12-10 05:08:54 +00001528
1529 // Adds and returns a default action spec for this mock function.
zhanyong.waned6c9272011-02-23 19:39:27 +00001530 OnCallSpec<F>& AddNewOnCallSpec(
shiqiane35fdd92008-12-10 05:08:54 +00001531 const char* file, int line,
vladlosev4d60a592011-10-24 21:16:22 +00001532 const ArgumentMatcherTuple& m)
1533 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001534 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001535 OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);
1536 untyped_on_call_specs_.push_back(on_call_spec);
1537 return *on_call_spec;
shiqiane35fdd92008-12-10 05:08:54 +00001538 }
1539
1540 // Adds and returns an expectation spec for this mock function.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001541 TypedExpectation<F>& AddNewExpectation(
vladlosev6c54a5e2009-10-21 06:15:34 +00001542 const char* file,
1543 int line,
1544 const string& source_text,
vladlosev4d60a592011-10-24 21:16:22 +00001545 const ArgumentMatcherTuple& m)
1546 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.wandf35a762009-04-22 22:25:31 +00001547 Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);
zhanyong.waned6c9272011-02-23 19:39:27 +00001548 TypedExpectation<F>* const expectation =
1549 new TypedExpectation<F>(this, file, line, source_text, m);
1550 const linked_ptr<ExpectationBase> untyped_expectation(expectation);
1551 untyped_expectations_.push_back(untyped_expectation);
shiqiane35fdd92008-12-10 05:08:54 +00001552
1553 // Adds this expectation into the implicit sequence if there is one.
1554 Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();
1555 if (implicit_sequence != NULL) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001556 implicit_sequence->AddExpectation(Expectation(untyped_expectation));
shiqiane35fdd92008-12-10 05:08:54 +00001557 }
1558
1559 return *expectation;
1560 }
1561
1562 // The current spec (either default action spec or expectation spec)
1563 // being described on this function mocker.
1564 MockSpec<F>& current_spec() { return current_spec_; }
zhanyong.wan32de5f52009-12-23 00:13:23 +00001565
shiqiane35fdd92008-12-10 05:08:54 +00001566 private:
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001567 template <typename Func> friend class TypedExpectation;
shiqiane35fdd92008-12-10 05:08:54 +00001568
zhanyong.waned6c9272011-02-23 19:39:27 +00001569 // Some utilities needed for implementing UntypedInvokeWith().
shiqiane35fdd92008-12-10 05:08:54 +00001570
1571 // Describes what default action will be performed for the given
1572 // arguments.
1573 // L = *
1574 void DescribeDefaultActionTo(const ArgumentTuple& args,
1575 ::std::ostream* os) const {
zhanyong.waned6c9272011-02-23 19:39:27 +00001576 const OnCallSpec<F>* const spec = FindOnCallSpec(args);
shiqiane35fdd92008-12-10 05:08:54 +00001577
1578 if (spec == NULL) {
1579 *os << (internal::type_equals<Result, void>::value ?
1580 "returning directly.\n" :
1581 "returning default value.\n");
1582 } else {
1583 *os << "taking default action specified at:\n"
vladloseve5121b52011-02-11 23:50:38 +00001584 << FormatFileLocation(spec->file(), spec->line()) << "\n";
shiqiane35fdd92008-12-10 05:08:54 +00001585 }
1586 }
1587
1588 // Writes a message that the call is uninteresting (i.e. neither
1589 // explicitly expected nor explicitly unexpected) to the given
1590 // ostream.
vladlosev4d60a592011-10-24 21:16:22 +00001591 virtual void UntypedDescribeUninterestingCall(
1592 const void* untyped_args,
1593 ::std::ostream* os) const
1594 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001595 const ArgumentTuple& args =
1596 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001597 *os << "Uninteresting mock function call - ";
1598 DescribeDefaultActionTo(args, os);
1599 *os << " Function call: " << Name();
vladloseve2e8ba42010-05-13 18:16:03 +00001600 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001601 }
1602
zhanyong.waned6c9272011-02-23 19:39:27 +00001603 // Returns the expectation that matches the given function arguments
1604 // (or NULL is there's no match); when a match is found,
1605 // untyped_action is set to point to the action that should be
1606 // performed (or NULL if the action is "do default"), and
1607 // is_excessive is modified to indicate whether the call exceeds the
1608 // expected number.
1609 //
shiqiane35fdd92008-12-10 05:08:54 +00001610 // Critical section: We must find the matching expectation and the
1611 // corresponding action that needs to be taken in an ATOMIC
1612 // transaction. Otherwise another thread may call this mock
1613 // method in the middle and mess up the state.
1614 //
1615 // However, performing the action has to be left out of the critical
1616 // section. The reason is that we have no control on what the
1617 // action does (it can invoke an arbitrary user function or even a
1618 // mock function) and excessive locking could cause a dead lock.
zhanyong.waned6c9272011-02-23 19:39:27 +00001619 virtual const ExpectationBase* UntypedFindMatchingExpectation(
1620 const void* untyped_args,
1621 const void** untyped_action, bool* is_excessive,
vladlosev4d60a592011-10-24 21:16:22 +00001622 ::std::ostream* what, ::std::ostream* why)
1623 GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001624 const ArgumentTuple& args =
1625 *static_cast<const ArgumentTuple*>(untyped_args);
shiqiane35fdd92008-12-10 05:08:54 +00001626 MutexLock l(&g_gmock_mutex);
zhanyong.waned6c9272011-02-23 19:39:27 +00001627 TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);
1628 if (exp == NULL) { // A match wasn't found.
shiqiane35fdd92008-12-10 05:08:54 +00001629 this->FormatUnexpectedCallMessageLocked(args, what, why);
zhanyong.waned6c9272011-02-23 19:39:27 +00001630 return NULL;
shiqiane35fdd92008-12-10 05:08:54 +00001631 }
1632
1633 // This line must be done before calling GetActionForArguments(),
1634 // which will increment the call count for *exp and thus affect
1635 // its saturation status.
zhanyong.waned6c9272011-02-23 19:39:27 +00001636 *is_excessive = exp->IsSaturated();
1637 const Action<F>* action = exp->GetActionForArguments(this, args, what, why);
1638 if (action != NULL && action->IsDoDefault())
1639 action = NULL; // Normalize "do default" to NULL.
1640 *untyped_action = action;
1641 return exp;
1642 }
1643
1644 // Prints the given function arguments to the ostream.
1645 virtual void UntypedPrintArgs(const void* untyped_args,
1646 ::std::ostream* os) const {
1647 const ArgumentTuple& args =
1648 *static_cast<const ArgumentTuple*>(untyped_args);
1649 UniversalPrint(args, os);
shiqiane35fdd92008-12-10 05:08:54 +00001650 }
1651
1652 // Returns the expectation that matches the arguments, or NULL if no
1653 // expectation matches them.
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001654 TypedExpectation<F>* FindMatchingExpectationLocked(
vladlosev4d60a592011-10-24 21:16:22 +00001655 const ArgumentTuple& args) const
1656 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001657 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001658 for (typename UntypedExpectations::const_reverse_iterator it =
1659 untyped_expectations_.rbegin();
1660 it != untyped_expectations_.rend(); ++it) {
1661 TypedExpectation<F>* const exp =
1662 static_cast<TypedExpectation<F>*>(it->get());
shiqiane35fdd92008-12-10 05:08:54 +00001663 if (exp->ShouldHandleArguments(args)) {
1664 return exp;
1665 }
1666 }
1667 return NULL;
1668 }
1669
1670 // Returns a message that the arguments don't match any expectation.
vladlosev4d60a592011-10-24 21:16:22 +00001671 void FormatUnexpectedCallMessageLocked(
1672 const ArgumentTuple& args,
1673 ::std::ostream* os,
1674 ::std::ostream* why) const
1675 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001676 g_gmock_mutex.AssertHeld();
1677 *os << "\nUnexpected mock function call - ";
1678 DescribeDefaultActionTo(args, os);
1679 PrintTriedExpectationsLocked(args, why);
1680 }
1681
1682 // Prints a list of expectations that have been tried against the
1683 // current mock function call.
vladlosev4d60a592011-10-24 21:16:22 +00001684 void PrintTriedExpectationsLocked(
1685 const ArgumentTuple& args,
1686 ::std::ostream* why) const
1687 GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
shiqiane35fdd92008-12-10 05:08:54 +00001688 g_gmock_mutex.AssertHeld();
zhanyong.waned6c9272011-02-23 19:39:27 +00001689 const int count = static_cast<int>(untyped_expectations_.size());
shiqiane35fdd92008-12-10 05:08:54 +00001690 *why << "Google Mock tried the following " << count << " "
1691 << (count == 1 ? "expectation, but it didn't match" :
1692 "expectations, but none matched")
1693 << ":\n";
1694 for (int i = 0; i < count; i++) {
zhanyong.waned6c9272011-02-23 19:39:27 +00001695 TypedExpectation<F>* const expectation =
1696 static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());
shiqiane35fdd92008-12-10 05:08:54 +00001697 *why << "\n";
zhanyong.waned6c9272011-02-23 19:39:27 +00001698 expectation->DescribeLocationTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001699 if (count > 1) {
vladlosev6c54a5e2009-10-21 06:15:34 +00001700 *why << "tried expectation #" << i << ": ";
shiqiane35fdd92008-12-10 05:08:54 +00001701 }
zhanyong.waned6c9272011-02-23 19:39:27 +00001702 *why << expectation->source_text() << "...\n";
1703 expectation->ExplainMatchResultTo(args, why);
1704 expectation->DescribeCallCountTo(why);
shiqiane35fdd92008-12-10 05:08:54 +00001705 }
1706 }
1707
shiqiane35fdd92008-12-10 05:08:54 +00001708 // The current spec (either default action spec or expectation spec)
1709 // being described on this function mocker.
1710 MockSpec<F> current_spec_;
1711
zhanyong.wan16cf4732009-05-14 20:55:30 +00001712 // There is no generally useful and implementable semantics of
1713 // copying a mock object, so copying a mock is usually a user error.
1714 // Thus we disallow copying function mockers. If the user really
1715 // wants to copy a mock object, he should implement his own copy
1716 // operation, for example:
1717 //
1718 // class MockFoo : public Foo {
1719 // public:
1720 // // Defines a copy constructor explicitly.
1721 // MockFoo(const MockFoo& src) {}
1722 // ...
1723 // };
1724 GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase);
shiqiane35fdd92008-12-10 05:08:54 +00001725}; // class FunctionMockerBase
1726
1727#ifdef _MSC_VER
zhanyong.wan658ac0b2011-02-24 07:29:13 +00001728# pragma warning(pop) // Restores the warning state.
shiqiane35fdd92008-12-10 05:08:54 +00001729#endif // _MSV_VER
1730
1731// Implements methods of FunctionMockerBase.
1732
1733// Verifies that all expectations on this mock function have been
1734// satisfied. Reports one or more Google Test non-fatal failures and
1735// returns false if not.
shiqiane35fdd92008-12-10 05:08:54 +00001736
1737// Reports an uninteresting call (whose description is in msg) in the
1738// manner specified by 'reaction'.
1739void ReportUninterestingCall(CallReaction reaction, const string& msg);
1740
shiqiane35fdd92008-12-10 05:08:54 +00001741} // namespace internal
1742
1743// The style guide prohibits "using" statements in a namespace scope
1744// inside a header file. However, the MockSpec class template is
1745// meant to be defined in the ::testing namespace. The following line
1746// is just a trick for working around a bug in MSVC 8.0, which cannot
1747// handle it if we define MockSpec in ::testing.
1748using internal::MockSpec;
1749
1750// Const(x) is a convenient function for obtaining a const reference
1751// to x. This is useful for setting expectations on an overloaded
1752// const mock method, e.g.
1753//
1754// class MockFoo : public FooInterface {
1755// public:
1756// MOCK_METHOD0(Bar, int());
1757// MOCK_CONST_METHOD0(Bar, int&());
1758// };
1759//
1760// MockFoo foo;
1761// // Expects a call to non-const MockFoo::Bar().
1762// EXPECT_CALL(foo, Bar());
1763// // Expects a call to const MockFoo::Bar().
1764// EXPECT_CALL(Const(foo), Bar());
1765template <typename T>
1766inline const T& Const(const T& x) { return x; }
1767
zhanyong.wan41b9b0b2009-07-01 19:04:51 +00001768// Constructs an Expectation object that references and co-owns exp.
1769inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT
1770 : expectation_base_(exp.GetHandle().expectation_base()) {}
1771
shiqiane35fdd92008-12-10 05:08:54 +00001772} // namespace testing
1773
1774// A separate macro is required to avoid compile errors when the name
1775// of the method used in call is a result of macro expansion.
1776// See CompilesWithMethodNameExpandedFromMacro tests in
1777// internal/gmock-spec-builders_test.cc for more details.
zhanyong.wane0d051e2009-02-19 00:33:37 +00001778#define GMOCK_ON_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001779 ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \
1780 #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001781#define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001782
zhanyong.wane0d051e2009-02-19 00:33:37 +00001783#define GMOCK_EXPECT_CALL_IMPL_(obj, call) \
shiqiane35fdd92008-12-10 05:08:54 +00001784 ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call)
zhanyong.wane0d051e2009-02-19 00:33:37 +00001785#define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call)
shiqiane35fdd92008-12-10 05:08:54 +00001786
1787#endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_