Debian Codegraph @

closure-library/closure/goog/labs/mock/mock.js

raw
1 // Copyright 2012 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Provides a mocking framework in Closure to make unit tests easy
17 * to write and understand. The methods provided here can be used to replace
18 * implementations of existing objects with 'mock' objects to abstract out
19 * external services and dependencies thereby isolating the code under test.
20 * Apart from mocking, methods are also provided to just monitor calls to an
21 * object (spying) and returning specific values for some or all the inputs to
22 * methods (stubbing).
23 *
24 * Design doc : http://go/closuremock
25 *
26 */
27
28
29 goog.provide('goog.labs.mock');
30 goog.provide('goog.labs.mock.VerificationError');
31
32 goog.require('goog.array');
33 goog.require('goog.asserts');
34 goog.require('goog.debug');
35 goog.require('goog.debug.Error');
36 goog.require('goog.functions');
37 goog.require('goog.labs.mock.verification');
38 goog.require('goog.labs.mock.verification.VerificationMode');
39 goog.require('goog.object');
40
41 goog.setTestOnly('goog.labs.mock');
42
43
44 /**
45 * Mocks a given object or class.
46 *
47 * @param {!Object} objectOrClass An instance or a constructor of a class to be
48 * mocked.
49 * @return {!Object} The mocked object.
50 */
51 goog.labs.mock.mock = function(objectOrClass) {
52 // Go over properties of 'objectOrClass' and create a MockManager to
53 // be used for stubbing out calls to methods.
54 var mockObjectManager = new goog.labs.mock.MockObjectManager_(objectOrClass);
55 var mockedObject = mockObjectManager.getMockedItem();
56 goog.asserts.assertObject(mockedObject);
57 return /** @type {!Object} */ (mockedObject);
58 };
59
60
61 /**
62 * Mocks a given function.
63 *
64 * @param {!Function} func A function to be mocked.
65 * @return {!Function} The mocked function.
66 */
67 goog.labs.mock.mockFunction = function(func) {
68 var mockFuncManager = new goog.labs.mock.MockFunctionManager_(func);
69 var mockedFunction = mockFuncManager.getMockedItem();
70 goog.asserts.assertFunction(mockedFunction);
71 return /** @type {!Function} */ (mockedFunction);
72 };
73
74
75 /**
76 * Mocks a given constructor.
77 *
78 * @param {!function(new:T, ...?)} ctor A constructor function to be mocked.
79 * @return {!function(new:T, ...?)} The mocked constructor.
80 * @template T
81 */
82 goog.labs.mock.mockConstructor = function(ctor) {
83 var mockCtor = goog.labs.mock.mockFunction(ctor);
84
85 // Copy class members from the real constructor to the mock. Do not copy
86 // the closure superClass_ property (see goog.inherits), the built-in
87 // prototype property, or properties added to Function.prototype
88 for (var property in ctor) {
89 if (property != 'superClass_' && property != 'prototype' &&
90 ctor.hasOwnProperty(property)) {
91 mockCtor[property] = ctor[property];
92 }
93 }
94 return mockCtor;
95 };
96
97
98 /**
99 * Spies on a given object.
100 *
101 * @param {!Object} obj The object to be spied on.
102 * @return {!Object} The spy object.
103 */
104 goog.labs.mock.spy = function(obj) {
105 // Go over properties of 'obj' and create a MockSpyManager_ to
106 // be used for spying on calls to methods.
107 var mockSpyManager = new goog.labs.mock.MockSpyManager_(obj);
108 var spyObject = mockSpyManager.getMockedItem();
109 goog.asserts.assert(spyObject);
110 return spyObject;
111 };
112
113
114 /**
115 * Returns an object that can be used to verify calls to specific methods of a
116 * given mock.
117 *
118 * @param {!Object} obj The mocked object.
119 * @param {!goog.labs.mock.verification.VerificationMode=} opt_verificationMode The mode
120 * under which to verify invocations.
121 * @return {?} The verifier. Return type {?} to avoid compilation errors.
122 */
123 goog.labs.mock.verify = function(obj, opt_verificationMode) {
124 var mode = opt_verificationMode || goog.labs.mock.verification.atLeast(1);
125 obj.$verificationModeSetter(mode);
126
127 return obj.$callVerifier;
128 };
129
130
131 /**
132 * Returns a name to identify a function. Named functions return their names,
133 * unnamed functions return a string of the form '#anonymous{ID}' where ID is
134 * a unique identifier for each anonymous function.
135 * @private
136 * @param {!Function} func The function.
137 * @return {string} The function name.
138 */
139 goog.labs.mock.getFunctionName_ = function(func) {
140 var funcName = goog.debug.getFunctionName(func);
141 if (funcName == '' || funcName == '[Anonymous]') {
142 funcName = '#anonymous' + goog.labs.mock.getUid(func);
143 }
144 return funcName;
145 };
146
147
148 /**
149 * Returns a nicely formatted, readable representation of a method call.
150 * @private
151 * @param {string} methodName The name of the method.
152 * @param {Array<?>=} opt_args The method arguments.
153 * @return {string} The string representation of the method call.
154 */
155 goog.labs.mock.formatMethodCall_ = function(methodName, opt_args) {
156 opt_args = opt_args || [];
157 opt_args = goog.array.map(opt_args, function(arg) {
158 if (goog.isFunction(arg)) {
159 var funcName = goog.labs.mock.getFunctionName_(arg);
160 return '<function ' + funcName + '>';
161 } else {
162 var isObjectWithClass = goog.isObject(arg) && !goog.isFunction(arg) &&
163 !goog.isArray(arg) && arg.constructor != Object;
164
165 if (isObjectWithClass) {
166 return arg.toString();
167 }
168
169 return goog.labs.mock.formatValue_(arg);
170 }
171 });
172 return methodName + '(' + opt_args.join(', ') + ')';
173 };
174
175
176 /**
177 * An array to store objects for unique id generation.
178 * @private
179 * @type {!Array<!Object>}
180 */
181 goog.labs.mock.uid_ = [];
182
183
184 /**
185 * A unique Id generator that does not modify the object.
186 * @param {Object!} obj The object whose unique ID we want to generate.
187 * @return {number} an unique id for the object.
188 */
189 goog.labs.mock.getUid = function(obj) {
190 var index = goog.array.indexOf(goog.labs.mock.uid_, obj);
191 if (index == -1) {
192 index = goog.labs.mock.uid_.length;
193 goog.labs.mock.uid_.push(obj);
194 }
195 return index;
196 };
197
198
199 /**
200 * This is just another implementation of goog.debug.deepExpose with a more
201 * compact format.
202 * @private
203 * @param {*} obj The object whose string representation will be returned.
204 * @param {boolean=} opt_id Whether to include the id of objects or not.
205 * Defaults to true.
206 * @return {string} The string representation of the object.
207 */
208 goog.labs.mock.formatValue_ = function(obj, opt_id) {
209 var id = goog.isDef(opt_id) ? opt_id : true;
210 var previous = [];
211 var output = [];
212
213 var helper = function(obj) {
214 var indentMultiline = function(output) {
215 return output.replace(/\n/g, '\n');
216 };
217
218
219 try {
220 if (!goog.isDef(obj)) {
221 output.push('undefined');
222 } else if (goog.isNull(obj)) {
223 output.push('NULL');
224 } else if (goog.isString(obj)) {
225 output.push('"' + indentMultiline(obj) + '"');
226 } else if (goog.isFunction(obj)) {
227 var funcName = goog.labs.mock.getFunctionName_(obj);
228 output.push('<function ' + funcName + '>');
229 } else if (goog.isObject(obj)) {
230 if (goog.array.contains(previous, obj)) {
231 if (id) {
232 output.push(
233 '<recursive/dupe obj_' + goog.labs.mock.getUid(obj) + '>');
234 } else {
235 output.push('<recursive/dupe>');
236 }
237 } else {
238 previous.push(obj);
239 output.push('{');
240 for (var x in obj) {
241 output.push(' ');
242 output.push(
243 '"' + x + '"' +
244 ':');
245 helper(obj[x]);
246 }
247 if (id) {
248 output.push(' _id:' + goog.labs.mock.getUid(obj));
249 }
250 output.push('}');
251 }
252 } else {
253 output.push(obj);
254 }
255 } catch (e) {
256 output.push('*** ' + e + ' ***');
257 }
258 };
259
260 helper(obj);
261 return output.join('')
262 .replace(/"closure_uid_\d+"/g, '_id')
263 .replace(/{ /g, '{');
264
265 };
266
267
268
269 /**
270 * Error thrown when verification failed.
271 *
272 * @param {Array<!goog.labs.mock.MethodBinding_>} recordedCalls
273 * The recorded calls that didn't match the expectation.
274 * @param {string} methodName The expected method call.
275 * @param {!goog.labs.mock.verification.VerificationMode} verificationMode The
276 * expected verification mode which failed verification.
277 * @param {!Array<?>} args The expected arguments.
278 * @constructor
279 * @extends {goog.debug.Error}
280 * @final
281 */
282 goog.labs.mock.VerificationError = function(
283 recordedCalls, methodName, verificationMode, args) {
284 var msg = goog.labs.mock.VerificationError.getVerificationErrorMsg_(
285 recordedCalls, methodName, verificationMode, args);
286 goog.labs.mock.VerificationError.base(this, 'constructor', msg);
287 };
288 goog.inherits(goog.labs.mock.VerificationError, goog.debug.Error);
289
290
291 /** @override */
292 goog.labs.mock.VerificationError.prototype.name = 'VerificationError';
293
294
295 /**
296 * This array contains the name of the functions that are part of the base
297 * Object prototype.
298 * Basically a copy of goog.object.PROTOTYPE_FIELDS_.
299 * @const
300 * @type {!Array<string>}
301 * @private
302 */
303 goog.labs.mock.PROTOTYPE_FIELDS_ = [
304 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
305 'toLocaleString', 'toString', 'valueOf'
306 ];
307
308
309 /**
310 * Constructs a descriptive error message for an expected method call.
311 * @private
312 * @param {Array<!goog.labs.mock.MethodBinding_>} recordedCalls
313 * The recorded calls that didn't match the expectation.
314 * @param {string} methodName The expected method call.
315 * @param {!goog.labs.mock.verification.VerificationMode} verificationMode The
316 * expected verification mode that failed verification.
317 * @param {!Array<?>} args The expected arguments.
318 * @return {string} The error message.
319 */
320 goog.labs.mock.VerificationError.getVerificationErrorMsg_ = function(
321 recordedCalls, methodName, verificationMode, args) {
322
323 recordedCalls = goog.array.filter(recordedCalls, function(binding) {
324 return binding.getMethodName() == methodName;
325 });
326
327 var expected = goog.labs.mock.formatMethodCall_(methodName, args);
328
329 var msg =
330 '\nExpected: ' + expected.toString() + ' ' + verificationMode.describe();
331 msg += '\nRecorded: ';
332
333 if (recordedCalls.length > 0) {
334 msg += recordedCalls.join(',\n ');
335 } else {
336 msg += 'No recorded calls';
337 }
338
339 return msg;
340 };
341
342
343
344 /**
345 * Base class that provides basic functionality for creating, adding and
346 * finding bindings, offering an executor method that is called when a call to
347 * the stub is made, an array to hold the bindings and the mocked item, among
348 * other things.
349 *
350 * @constructor
351 * @struct
352 * @private
353 */
354 goog.labs.mock.MockManager_ = function() {
355 /**
356 * Proxies the methods for the mocked object or class to execute the stubs.
357 * @type {!Object}
358 * @protected
359 */
360 this.mockedItem = {};
361
362 /**
363 * A reference to the object or function being mocked.
364 * @type {Object|Function}
365 * @protected
366 */
367 this.mockee = null;
368
369 /**
370 * Holds the stub bindings established so far.
371 * @protected
372 */
373 this.methodBindings = [];
374
375 /**
376 * Holds a reference to the binder used to define stubs.
377 * @protected
378 */
379 this.$stubBinder = null;
380
381 /**
382 * Record method calls with no stub definitions.
383 * @type {!Array<!goog.labs.mock.MethodBinding_>}
384 * @private
385 */
386 this.callRecords_ = [];
387
388 /**
389 * Which {@code VerificationMode} to use during verification.
390 * @private
391 */
392 this.verificationMode_ = goog.labs.mock.verification.atLeast(1);
393 };
394
395
396 /**
397 * Allows callers of {@code #verify} to override the default verification
398 * mode of this MockManager.
399 *
400 * @param {!goog.labs.mock.verification.VerificationMode} verificationMode
401 * @private
402 */
403 goog.labs.mock.MockManager_.prototype.setVerificationMode_ = function(
404 verificationMode) {
405 this.verificationMode_ = verificationMode;
406 };
407
408
409 /**
410 * Handles the first step in creating a stub, returning a stub-binder that
411 * is later used to bind a stub for a method.
412 *
413 * @param {string} methodName The name of the method being bound.
414 * @param {...*} var_args The arguments to the method.
415 * @return {!goog.labs.mock.StubBinder} The stub binder.
416 * @private
417 */
418 goog.labs.mock.MockManager_.prototype.handleMockCall_ = function(
419 methodName, var_args) {
420 var args = goog.array.slice(arguments, 1);
421 return new goog.labs.mock.StubBinderImpl_(this, methodName, args);
422 };
423
424
425 /**
426 * Returns the mock object. This should have a stubbed method for each method
427 * on the object being mocked.
428 *
429 * @return {!Object|!Function} The mock object.
430 */
431 goog.labs.mock.MockManager_.prototype.getMockedItem = function() {
432 return this.mockedItem;
433 };
434
435
436 /**
437 * Adds a binding for the method name and arguments to be stubbed.
438 *
439 * @param {?string} methodName The name of the stubbed method.
440 * @param {!Array<?>} args The arguments passed to the method.
441 * @param {!Function} func The stub function.
442 * @return {!Array<?>} The array of stubs for further sequential stubs to be
443 * appended.
444 */
445 goog.labs.mock.MockManager_.prototype.addBinding = function(
446 methodName, args, func) {
447 var binding = new goog.labs.mock.MethodBinding_(methodName, args, func);
448 var sequentialStubsArray = [binding];
449 goog.array.insertAt(this.methodBindings, sequentialStubsArray, 0);
450 return sequentialStubsArray;
451 };
452
453
454 /**
455 * Returns a stub, if defined, for the method name and arguments passed in.
456 * If there are multiple stubs for this method name and arguments, then
457 * the most recent binding will be used.
458 *
459 * If the next binding is a sequence of stubs, then they'll be returned
460 * in order until only one is left, at which point it will be returned for every
461 * subsequent call.
462 *
463 * @param {string} methodName The name of the stubbed method.
464 * @param {!Array<?>} args The arguments passed to the method.
465 * @return {?Function} The stub function or null.
466 * @protected
467 */
468 goog.labs.mock.MockManager_.prototype.getNextBinding = function(
469 methodName, args) {
470 var bindings = goog.array.find(this.methodBindings, function(bindingArray) {
471 return bindingArray[0].matches(
472 methodName, args, false /* isVerification */);
473 });
474 if (bindings == null) {
475 return null;
476 }
477
478 if (bindings.length > 1) {
479 return bindings.shift().getStub();
480 }
481 return bindings[0].getStub();
482 };
483
484
485 /**
486 * Returns a stub, if defined, for the method name and arguments passed in as
487 * parameters.
488 *
489 * @param {string} methodName The name of the stubbed method.
490 * @param {!Array<?>} args The arguments passed to the method.
491 * @return {Function} The stub function or undefined.
492 * @protected
493 */
494 goog.labs.mock.MockManager_.prototype.getExecutor = function(methodName, args) {
495 return this.getNextBinding(methodName, args);
496 };
497
498
499 /**
500 * Looks up the list of stubs defined on the mock object and executes the
501 * function associated with that stub.
502 *
503 * @param {string} methodName The name of the method to execute.
504 * @param {...*} var_args The arguments passed to the method.
505 * @return {*} Value returned by the stub function.
506 * @protected
507 */
508 goog.labs.mock.MockManager_.prototype.executeStub = function(
509 methodName, var_args) {
510 var args = goog.array.slice(arguments, 1);
511
512 // Record this call
513 this.recordCall_(methodName, args);
514
515 var func = this.getExecutor(methodName, args);
516 if (func) {
517 return func.apply(null, args);
518 }
519 };
520
521
522 /**
523 * Records a call to 'methodName' with arguments 'args'.
524 *
525 * @param {string} methodName The name of the called method.
526 * @param {!Array<?>} args The array of arguments.
527 * @private
528 */
529 goog.labs.mock.MockManager_.prototype.recordCall_ = function(methodName, args) {
530 var callRecord =
531 new goog.labs.mock.MethodBinding_(methodName, args, goog.nullFunction);
532
533 this.callRecords_.push(callRecord);
534 };
535
536
537 /**
538 * Verify invocation of a method with specific arguments.
539 *
540 * @param {string} methodName The name of the method.
541 * @param {...*} var_args The arguments passed.
542 * @protected
543 */
544 goog.labs.mock.MockManager_.prototype.verifyInvocation = function(
545 methodName, var_args) {
546 var args = goog.array.slice(arguments, 1);
547 var count = goog.array.count(this.callRecords_, function(binding) {
548 return binding.matches(methodName, args, true /* isVerification */);
549 });
550
551 if (!this.verificationMode_.verify(count)) {
552 throw new goog.labs.mock.VerificationError(
553 this.callRecords_, methodName, this.verificationMode_, args);
554 }
555 };
556
557
558
559 /**
560 * Sets up mock for the given object (or class), stubbing out all the defined
561 * methods. By default, all stubs return {@code undefined}, though stubs can be
562 * later defined using {@code goog.labs.mock.when}.
563 *
564 * @param {!Object|!Function} objOrClass The object or class to set up the mock
565 * for. A class is a constructor function.
566 *
567 * @constructor
568 * @struct
569 * @extends {goog.labs.mock.MockManager_}
570 * @private
571 */
572 goog.labs.mock.MockObjectManager_ = function(objOrClass) {
573 goog.labs.mock.MockObjectManager_.base(this, 'constructor');
574
575 /**
576 * Proxies the calls to establish the first step of the stub bindings (object
577 * and method name)
578 * @private
579 */
580 this.objectStubBinder_ = {};
581
582 this.mockee = objOrClass;
583
584 /**
585 * The call verifier is used to verify the calls. It maps property names to
586 * the method that does call verification.
587 * @type {!Object<string, function(string, ...)>}
588 * @private
589 */
590 this.objectCallVerifier_ = {};
591
592 var obj;
593 if (goog.isFunction(objOrClass)) {
594 // Create a temporary subclass with a no-op constructor so that we can
595 // create an instance and determine what methods it has.
596 /**
597 * @constructor
598 * @final
599 */
600 var tempCtor = function() {};
601 goog.inherits(tempCtor, objOrClass);
602 obj = new tempCtor();
603 } else {
604 obj = objOrClass;
605 }
606
607 // Put the object being mocked in the prototype chain of the mock so that
608 // it has all the correct properties and instanceof works.
609 /**
610 * @constructor
611 * @final
612 */
613 var mockedItemCtor = function() {};
614 mockedItemCtor.prototype = obj;
615 this.mockedItem = new mockedItemCtor();
616
617 var enumerableProperties = goog.object.getAllPropertyNames(obj);
618 // The non enumerable properties are added due to the fact that IE8 does not
619 // enumerate any of the prototype Object functions even when overriden and
620 // mocking these is sometimes needed.
621 for (var i = 0; i < goog.labs.mock.PROTOTYPE_FIELDS_.length; i++) {
622 var prop = goog.labs.mock.PROTOTYPE_FIELDS_[i];
623 if (!goog.array.contains(enumerableProperties, prop)) {
624 enumerableProperties.push(prop);
625 }
626 }
627
628 // Adds the properties to the mock, creating a proxy stub for each method on
629 // the instance.
630 for (var i = 0; i < enumerableProperties.length; i++) {
631 var prop = enumerableProperties[i];
632 if (goog.isFunction(obj[prop])) {
633 this.mockedItem[prop] = goog.bind(this.executeStub, this, prop);
634 // The stub binder used to create bindings.
635 this.objectStubBinder_[prop] =
636 goog.bind(this.handleMockCall_, this, prop);
637 // The verifier verifies the calls.
638 this.objectCallVerifier_[prop] =
639 goog.bind(this.verifyInvocation, this, prop);
640 }
641 }
642 // The alias for stub binder exposed to the world.
643 this.mockedItem.$stubBinder = this.objectStubBinder_;
644
645 // The alias for verifier for the world.
646 this.mockedItem.$callVerifier = this.objectCallVerifier_;
647
648 this.mockedItem.$verificationModeSetter =
649 goog.bind(this.setVerificationMode_, this);
650 };
651 goog.inherits(goog.labs.mock.MockObjectManager_, goog.labs.mock.MockManager_);
652
653
654
655 /**
656 * Sets up the spying behavior for the given object.
657 *
658 * @param {!Object} obj The object to be spied on.
659 *
660 * @constructor
661 * @struct
662 * @extends {goog.labs.mock.MockObjectManager_}
663 * @private
664 */
665 goog.labs.mock.MockSpyManager_ = function(obj) {
666 goog.labs.mock.MockSpyManager_.base(this, 'constructor', obj);
667 };
668 goog.inherits(
669 goog.labs.mock.MockSpyManager_, goog.labs.mock.MockObjectManager_);
670
671
672 /**
673 * Return a stub, if defined, for the method and arguments passed in. If we lack
674 * a stub, instead look for a call record that matches the method and arguments.
675 *
676 * @return {!Function} The stub or the invocation logger, if defined.
677 * @override
678 */
679 goog.labs.mock.MockSpyManager_.prototype.getNextBinding = function(
680 methodName, args) {
681 var stub = goog.labs.mock.MockSpyManager_.base(
682 this, 'getNextBinding', methodName, args);
683
684 if (!stub) {
685 stub = goog.bind(this.mockee[methodName], this.mockee);
686 }
687
688 return stub;
689 };
690
691
692
693 /**
694 * Sets up mock for the given function, stubbing out. By default, all stubs
695 * return {@code undefined}, though stubs can be later defined using
696 * {@code goog.labs.mock.when}.
697 *
698 * @param {!Function} func The function to set up the mock for.
699 *
700 * @constructor
701 * @struct
702 * @extends {goog.labs.mock.MockManager_}
703 * @private
704 */
705 goog.labs.mock.MockFunctionManager_ = function(func) {
706 goog.labs.mock.MockFunctionManager_.base(this, 'constructor');
707
708 this.func_ = func;
709
710 /**
711 * The stub binder used to create bindings.
712 * Sets the first argument of handleMockCall_ to the function name.
713 * @type {!Function}
714 * @private
715 */
716 this.functionStubBinder_ = this.useMockedFunctionName_(this.handleMockCall_);
717
718 this.mockedItem = this.useMockedFunctionName_(this.executeStub);
719 this.mockedItem.$stubBinder = this.functionStubBinder_;
720
721 /**
722 * The call verifier is used to verify function invocations.
723 * Sets the first argument of verifyInvocation to the function name.
724 * @type {!Function}
725 */
726 this.mockedItem.$callVerifier =
727 this.useMockedFunctionName_(this.verifyInvocation);
728
729 // This has to be repeated because if it's set in base class it will be
730 // stubbed by MockObjectManager.
731 this.mockedItem.$verificationModeSetter =
732 goog.bind(this.setVerificationMode_, this);
733 };
734 goog.inherits(goog.labs.mock.MockFunctionManager_, goog.labs.mock.MockManager_);
735
736
737 /**
738 * Given a method, returns a new function that calls the first one setting
739 * the first argument to the mocked function name.
740 * This is used to dynamically override the stub binders and call verifiers.
741 * @private
742 * @param {Function} nextFunc The function to override.
743 * @return {!Function} The overloaded function.
744 */
745 goog.labs.mock.MockFunctionManager_.prototype.useMockedFunctionName_ = function(
746 nextFunc) {
747 var mockFunctionManager = this;
748 // Avoid using 'this' because this function may be called with 'new'.
749 return function(var_args) {
750 var args = goog.array.clone(arguments);
751 var name = '#mockFor<' +
752 goog.labs.mock.getFunctionName_(mockFunctionManager.func_) + '>';
753 goog.array.insertAt(args, name, 0);
754 return nextFunc.apply(mockFunctionManager, args);
755 };
756 };
757
758
759 /**
760 * A stub binder is an object that helps define the stub by binding
761 * method name to the stub method.
762 * @interface
763 */
764 goog.labs.mock.StubBinder = function() {};
765
766
767 /**
768 * Defines the function to be called for the method name and arguments bound
769 * to this {@code StubBinder}.
770 *
771 * If {@code then} or {@code thenReturn} has been previously called
772 * on this {@code StubBinder} then the given stub {@code func} will be called
773 * only after the stubs passed previously have been called. Afterwards,
774 * if no other calls are made to {@code then} or {@code thenReturn} for this
775 * {@code StubBinder} then the given {@code func} will be used for every further
776 * invocation.
777 * See #when for complete examples.
778 * TODO(user): Add support for the 'Answer' interface.
779 *
780 * @param {!Function} func The function to call.
781 * @return {!goog.labs.mock.StubBinder} Returns itself for chaining.
782 */
783 goog.labs.mock.StubBinder.prototype.then = goog.abstractMethod;
784
785
786 /**
787 * Defines the constant return value for the stub represented by this
788 * {@code StubBinder}.
789 *
790 * @param {*} value The value to return.
791 * @return {!goog.labs.mock.StubBinder} Returns itself for chaining.
792 */
793 goog.labs.mock.StubBinder.prototype.thenReturn = goog.abstractMethod;
794
795
796 /**
797 * A {@code StubBinder} which uses {@code MockManager_} to manage stub
798 * bindings.
799 *
800 * @param {!goog.labs.mock.MockManager_}
801 * mockManager The mock manager.
802 * @param {?string} name The method name.
803 * @param {!Array<?>} args The other arguments to the method.
804 *
805 * @implements {goog.labs.mock.StubBinder}
806 * @private @constructor @struct @final
807 */
808 goog.labs.mock.StubBinderImpl_ = function(mockManager, name, args) {
809 /**
810 * The mock manager instance.
811 * @type {!goog.labs.mock.MockManager_}
812 * @private
813 */
814 this.mockManager_ = mockManager;
815
816 /**
817 * Holds the name of the method to be bound.
818 * @type {?string}
819 * @private
820 */
821 this.name_ = name;
822
823 /**
824 * Holds the arguments for the method.
825 * @type {!Array<?>}
826 * @private
827 */
828 this.args_ = args;
829
830 /**
831 * Stores a reference to the list of stubs to allow chaining sequential
832 * stubs.
833 * @private {!Array<?>}
834 */
835 this.sequentialStubsArray_ = [];
836 };
837
838
839 /**
840 * @override
841 */
842 goog.labs.mock.StubBinderImpl_.prototype.then = function(func) {
843 if (this.sequentialStubsArray_.length) {
844 this.sequentialStubsArray_.push(
845 new goog.labs.mock.MethodBinding_(this.name_, this.args_, func));
846 } else {
847 this.sequentialStubsArray_ =
848 this.mockManager_.addBinding(this.name_, this.args_, func);
849 }
850 return this;
851 };
852
853
854 /**
855 * @override
856 */
857 goog.labs.mock.StubBinderImpl_.prototype.thenReturn = function(value) {
858 return this.then(goog.functions.constant(value));
859 };
860
861
862 /**
863 * Facilitates (and is the first step in) setting up stubs. Obtains an object
864 * on which, the method to be mocked is called to create a stub. Sample usage:
865 *
866 * var mockObj = goog.labs.mock.mock(objectBeingMocked);
867 * goog.labs.mock.when(mockObj).getFoo(3).thenReturn(4);
868 *
869 * Subsequent calls to {@code when} take precedence over earlier calls, allowing
870 * users to set up default stubs in setUp methods and then override them in
871 * individual tests.
872 *
873 * If a user wants sequential calls to their stub to return different
874 * values, they can chain calls to {@code then} or {@code thenReturn} as
875 * follows:
876 *
877 * var mockObj = goog.labs.mock.mock(objectBeingMocked);
878 * goog.labs.mock.when(mockObj).getFoo(3)
879 * .thenReturn(4)
880 * .then(function() {
881 * throw new Error('exceptional case');
882 * });
883 *
884 * @param {!Object} mockObject The mocked object.
885 * @return {?} The property binder. Return type {?} to avoid compilation errors.
886 */
887 goog.labs.mock.when = function(mockObject) {
888 goog.asserts.assert(mockObject.$stubBinder, 'Stub binder cannot be null!');
889 return mockObject.$stubBinder;
890 };
891
892
893
894 /**
895 * Represents a binding between a method name, args and a stub.
896 *
897 * @param {?string} methodName The name of the method being stubbed.
898 * @param {!Array<?>} args The arguments passed to the method.
899 * @param {!Function} stub The stub function to be called for the given method.
900 * @constructor
901 * @struct
902 * @private
903 */
904 goog.labs.mock.MethodBinding_ = function(methodName, args, stub) {
905 /**
906 * The name of the method being stubbed.
907 * @type {?string}
908 * @private
909 */
910 this.methodName_ = methodName;
911
912 /**
913 * The arguments for the method being stubbed.
914 * @type {!Array<?>}
915 * @private
916 */
917 this.args_ = args;
918
919 /**
920 * The stub function.
921 * @type {!Function}
922 * @private
923 */
924 this.stub_ = stub;
925 };
926
927
928 /**
929 * @return {!Function} The stub to be executed.
930 */
931 goog.labs.mock.MethodBinding_.prototype.getStub = function() {
932 return this.stub_;
933 };
934
935
936 /**
937 * @override
938 * @return {string} A readable string representation of the binding
939 * as a method call.
940 */
941 goog.labs.mock.MethodBinding_.prototype.toString = function() {
942 return goog.labs.mock.formatMethodCall_(this.methodName_ || '', this.args_);
943 };
944
945
946 /**
947 * @return {string} The method name for this binding.
948 */
949 goog.labs.mock.MethodBinding_.prototype.getMethodName = function() {
950 return this.methodName_ || '';
951 };
952
953
954 /**
955 * Determines whether the given args match the stored args_. Used to determine
956 * which stub to invoke for a method.
957 *
958 * @param {string} methodName The name of the method being stubbed.
959 * @param {!Array<?>} args An array of arguments.
960 * @param {boolean} isVerification Whether this is a function verification call
961 * or not.
962 * @return {boolean} If it matches the stored arguments.
963 */
964 goog.labs.mock.MethodBinding_.prototype.matches = function(
965 methodName, args, isVerification) {
966 var specs = isVerification ? args : this.args_;
967 var calls = isVerification ? this.args_ : args;
968
969 // TODO(user): More elaborate argument matching. Think about matching
970 // objects.
971 return this.methodName_ == methodName &&
972 goog.array.equals(calls, specs, function(arg, spec) {
973 // Duck-type to see if this is an object that implements the
974 // goog.labs.testing.Matcher interface.
975 if (spec && goog.isFunction(spec.matches)) {
976 return spec.matches(arg);
977 } else {
978 return goog.array.defaultCompareEquality(spec, arg);
979 }
980 });
981 };