File: mock.js

package info (click to toggle)
aseba-plugin-blockly 20180211%2Bgit-2
  • links: PTS
  • area: non-free
  • in suites: buster
  • size: 64,472 kB
  • sloc: xml: 7,976; python: 2,314; sh: 261; lisp: 24; makefile: 10
file content (981 lines) | stat: -rw-r--r-- 29,226 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
// Copyright 2012 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Provides a mocking framework in Closure to make unit tests easy
 * to write and understand. The methods provided here can be used to replace
 * implementations of existing objects with 'mock' objects to abstract out
 * external services and dependencies thereby isolating the code under test.
 * Apart from mocking, methods are also provided to just monitor calls to an
 * object (spying) and returning specific values for some or all the inputs to
 * methods (stubbing).
 *
 * Design doc : http://go/closuremock
 *
 */


goog.provide('goog.labs.mock');
goog.provide('goog.labs.mock.VerificationError');

goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug');
goog.require('goog.debug.Error');
goog.require('goog.functions');
goog.require('goog.labs.mock.verification');
goog.require('goog.labs.mock.verification.VerificationMode');
goog.require('goog.object');

goog.setTestOnly('goog.labs.mock');


/**
 * Mocks a given object or class.
 *
 * @param {!Object} objectOrClass An instance or a constructor of a class to be
 *     mocked.
 * @return {!Object} The mocked object.
 */
goog.labs.mock.mock = function(objectOrClass) {
  // Go over properties of 'objectOrClass' and create a MockManager to
  // be used for stubbing out calls to methods.
  var mockObjectManager = new goog.labs.mock.MockObjectManager_(objectOrClass);
  var mockedObject = mockObjectManager.getMockedItem();
  goog.asserts.assertObject(mockedObject);
  return /** @type {!Object} */ (mockedObject);
};


/**
 * Mocks a given function.
 *
 * @param {!Function} func A function to be mocked.
 * @return {!Function} The mocked function.
 */
goog.labs.mock.mockFunction = function(func) {
  var mockFuncManager = new goog.labs.mock.MockFunctionManager_(func);
  var mockedFunction = mockFuncManager.getMockedItem();
  goog.asserts.assertFunction(mockedFunction);
  return /** @type {!Function} */ (mockedFunction);
};


/**
 * Mocks a given constructor.
 *
 * @param {!function(new:T, ...?)} ctor A constructor function to be mocked.
 * @return {!function(new:T, ...?)} The mocked constructor.
 * @template T
 */
goog.labs.mock.mockConstructor = function(ctor) {
  var mockCtor = goog.labs.mock.mockFunction(ctor);

  // Copy class members from the real constructor to the mock. Do not copy
  // the closure superClass_ property (see goog.inherits), the built-in
  // prototype property, or properties added to Function.prototype
  for (var property in ctor) {
    if (property != 'superClass_' && property != 'prototype' &&
        ctor.hasOwnProperty(property)) {
      mockCtor[property] = ctor[property];
    }
  }
  return mockCtor;
};


/**
 * Spies on a given object.
 *
 * @param {!Object} obj The object to be spied on.
 * @return {!Object} The spy object.
 */
goog.labs.mock.spy = function(obj) {
  // Go over properties of 'obj' and create a MockSpyManager_ to
  // be used for spying on calls to methods.
  var mockSpyManager = new goog.labs.mock.MockSpyManager_(obj);
  var spyObject = mockSpyManager.getMockedItem();
  goog.asserts.assert(spyObject);
  return spyObject;
};


/**
 * Returns an object that can be used to verify calls to specific methods of a
 * given mock.
 *
 * @param {!Object} obj The mocked object.
 * @param {!goog.labs.mock.verification.VerificationMode=} opt_verificationMode The mode
 *     under which to verify invocations.
 * @return {?} The verifier. Return type {?} to avoid compilation errors.
 */
goog.labs.mock.verify = function(obj, opt_verificationMode) {
  var mode = opt_verificationMode || goog.labs.mock.verification.atLeast(1);
  obj.$verificationModeSetter(mode);

  return obj.$callVerifier;
};


/**
 * Returns a name to identify a function. Named functions return their names,
 * unnamed functions return a string of the form '#anonymous{ID}' where ID is
 * a unique identifier for each anonymous function.
 * @private
 * @param {!Function} func The function.
 * @return {string} The function name.
 */
goog.labs.mock.getFunctionName_ = function(func) {
  var funcName = goog.debug.getFunctionName(func);
  if (funcName == '' || funcName == '[Anonymous]') {
    funcName = '#anonymous' + goog.labs.mock.getUid(func);
  }
  return funcName;
};


/**
 * Returns a nicely formatted, readable representation of a method call.
 * @private
 * @param {string} methodName The name of the method.
 * @param {Array<?>=} opt_args The method arguments.
 * @return {string} The string representation of the method call.
 */
goog.labs.mock.formatMethodCall_ = function(methodName, opt_args) {
  opt_args = opt_args || [];
  opt_args = goog.array.map(opt_args, function(arg) {
    if (goog.isFunction(arg)) {
      var funcName = goog.labs.mock.getFunctionName_(arg);
      return '<function ' + funcName + '>';
    } else {
      var isObjectWithClass = goog.isObject(arg) && !goog.isFunction(arg) &&
          !goog.isArray(arg) && arg.constructor != Object;

      if (isObjectWithClass) {
        return arg.toString();
      }

      return goog.labs.mock.formatValue_(arg);
    }
  });
  return methodName + '(' + opt_args.join(', ') + ')';
};


/**
 * An array to store objects for unique id generation.
 * @private
 * @type {!Array<!Object>}
 */
goog.labs.mock.uid_ = [];


/**
 * A unique Id generator that does not modify the object.
 * @param {Object!} obj The object whose unique ID we want to generate.
 * @return {number} an unique id for the object.
 */
goog.labs.mock.getUid = function(obj) {
  var index = goog.array.indexOf(goog.labs.mock.uid_, obj);
  if (index == -1) {
    index = goog.labs.mock.uid_.length;
    goog.labs.mock.uid_.push(obj);
  }
  return index;
};


/**
 * This is just another implementation of goog.debug.deepExpose with a more
 * compact format.
 * @private
 * @param {*} obj The object whose string representation will be returned.
 * @param {boolean=} opt_id Whether to include the id of objects or not.
 *     Defaults to true.
 * @return {string} The string representation of the object.
 */
goog.labs.mock.formatValue_ = function(obj, opt_id) {
  var id = goog.isDef(opt_id) ? opt_id : true;
  var previous = [];
  var output = [];

  var helper = function(obj) {
    var indentMultiline = function(output) {
      return output.replace(/\n/g, '\n');
    };


    try {
      if (!goog.isDef(obj)) {
        output.push('undefined');
      } else if (goog.isNull(obj)) {
        output.push('NULL');
      } else if (goog.isString(obj)) {
        output.push('"' + indentMultiline(obj) + '"');
      } else if (goog.isFunction(obj)) {
        var funcName = goog.labs.mock.getFunctionName_(obj);
        output.push('<function ' + funcName + '>');
      } else if (goog.isObject(obj)) {
        if (goog.array.contains(previous, obj)) {
          if (id) {
            output.push(
                '<recursive/dupe obj_' + goog.labs.mock.getUid(obj) + '>');
          } else {
            output.push('<recursive/dupe>');
          }
        } else {
          previous.push(obj);
          output.push('{');
          for (var x in obj) {
            output.push(' ');
            output.push(
                '"' + x + '"' +
                ':');
            helper(obj[x]);
          }
          if (id) {
            output.push(' _id:' + goog.labs.mock.getUid(obj));
          }
          output.push('}');
        }
      } else {
        output.push(obj);
      }
    } catch (e) {
      output.push('*** ' + e + ' ***');
    }
  };

  helper(obj);
  return output.join('')
      .replace(/"closure_uid_\d+"/g, '_id')
      .replace(/{ /g, '{');

};



/**
 * Error thrown when verification failed.
 *
 * @param {Array<!goog.labs.mock.MethodBinding_>} recordedCalls
 *     The recorded calls that didn't match the expectation.
 * @param {string} methodName The expected method call.
 * @param {!goog.labs.mock.verification.VerificationMode} verificationMode The
 *     expected verification mode which failed verification.
 * @param {!Array<?>} args The expected arguments.
 * @constructor
 * @extends {goog.debug.Error}
 * @final
 */
goog.labs.mock.VerificationError = function(
    recordedCalls, methodName, verificationMode, args) {
  var msg = goog.labs.mock.VerificationError.getVerificationErrorMsg_(
      recordedCalls, methodName, verificationMode, args);
  goog.labs.mock.VerificationError.base(this, 'constructor', msg);
};
goog.inherits(goog.labs.mock.VerificationError, goog.debug.Error);


/** @override */
goog.labs.mock.VerificationError.prototype.name = 'VerificationError';


/**
 * This array contains the name of the functions that are part of the base
 * Object prototype.
 * Basically a copy of goog.object.PROTOTYPE_FIELDS_.
 * @const
 * @type {!Array<string>}
 * @private
 */
goog.labs.mock.PROTOTYPE_FIELDS_ = [
  'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
  'toLocaleString', 'toString', 'valueOf'
];


/**
 * Constructs a descriptive error message for an expected method call.
 * @private
 * @param {Array<!goog.labs.mock.MethodBinding_>} recordedCalls
 *     The recorded calls that didn't match the expectation.
 * @param {string} methodName The expected method call.
 * @param {!goog.labs.mock.verification.VerificationMode} verificationMode The
 *     expected verification mode that failed verification.
 * @param {!Array<?>} args The expected arguments.
 * @return {string} The error message.
 */
goog.labs.mock.VerificationError.getVerificationErrorMsg_ = function(
    recordedCalls, methodName, verificationMode, args) {

  recordedCalls = goog.array.filter(recordedCalls, function(binding) {
    return binding.getMethodName() == methodName;
  });

  var expected = goog.labs.mock.formatMethodCall_(methodName, args);

  var msg =
      '\nExpected: ' + expected.toString() + ' ' + verificationMode.describe();
  msg += '\nRecorded: ';

  if (recordedCalls.length > 0) {
    msg += recordedCalls.join(',\n          ');
  } else {
    msg += 'No recorded calls';
  }

  return msg;
};



/**
 * Base class that provides basic functionality for creating, adding and
 * finding bindings, offering an executor method that is called when a call to
 * the stub is made, an array to hold the bindings and the mocked item, among
 * other things.
 *
 * @constructor
 * @struct
 * @private
 */
goog.labs.mock.MockManager_ = function() {
  /**
   * Proxies the methods for the mocked object or class to execute the stubs.
   * @type {!Object}
   * @protected
   */
  this.mockedItem = {};

  /**
   * A reference to the object or function being mocked.
   * @type {Object|Function}
   * @protected
   */
  this.mockee = null;

  /**
   * Holds the stub bindings established so far.
   * @protected
   */
  this.methodBindings = [];

  /**
   * Holds a reference to the binder used to define stubs.
   * @protected
   */
  this.$stubBinder = null;

  /**
   * Record method calls with no stub definitions.
   * @type {!Array<!goog.labs.mock.MethodBinding_>}
   * @private
   */
  this.callRecords_ = [];

  /**
   * Which {@code VerificationMode} to use during verification.
   * @private
   */
  this.verificationMode_ = goog.labs.mock.verification.atLeast(1);
};


/**
 * Allows callers of {@code #verify} to override the default verification
 * mode of this MockManager.
 *
 * @param {!goog.labs.mock.verification.VerificationMode} verificationMode
 * @private
 */
goog.labs.mock.MockManager_.prototype.setVerificationMode_ = function(
    verificationMode) {
  this.verificationMode_ = verificationMode;
};


/**
 * Handles the first step in creating a stub, returning a stub-binder that
 * is later used to bind a stub for a method.
 *
 * @param {string} methodName The name of the method being bound.
 * @param {...*} var_args The arguments to the method.
 * @return {!goog.labs.mock.StubBinder} The stub binder.
 * @private
 */
goog.labs.mock.MockManager_.prototype.handleMockCall_ = function(
    methodName, var_args) {
  var args = goog.array.slice(arguments, 1);
  return new goog.labs.mock.StubBinderImpl_(this, methodName, args);
};


/**
 * Returns the mock object. This should have a stubbed method for each method
 * on the object being mocked.
 *
 * @return {!Object|!Function} The mock object.
 */
goog.labs.mock.MockManager_.prototype.getMockedItem = function() {
  return this.mockedItem;
};


/**
 * Adds a binding for the method name and arguments to be stubbed.
 *
 * @param {?string} methodName The name of the stubbed method.
 * @param {!Array<?>} args The arguments passed to the method.
 * @param {!Function} func The stub function.
 * @return {!Array<?>} The array of stubs for further sequential stubs to be
 *     appended.
 */
goog.labs.mock.MockManager_.prototype.addBinding = function(
    methodName, args, func) {
  var binding = new goog.labs.mock.MethodBinding_(methodName, args, func);
  var sequentialStubsArray = [binding];
  goog.array.insertAt(this.methodBindings, sequentialStubsArray, 0);
  return sequentialStubsArray;
};


/**
 * Returns a stub, if defined, for the method name and arguments passed in.
 * If there are multiple stubs for this method name and arguments, then
 * the most recent binding will be used.
 *
 * If the next binding is a sequence of stubs, then they'll be returned
 * in order until only one is left, at which point it will be returned for every
 * subsequent call.
 *
 * @param {string} methodName The name of the stubbed method.
 * @param {!Array<?>} args The arguments passed to the method.
 * @return {?Function} The stub function or null.
 * @protected
 */
goog.labs.mock.MockManager_.prototype.getNextBinding = function(
    methodName, args) {
  var bindings = goog.array.find(this.methodBindings, function(bindingArray) {
    return bindingArray[0].matches(
        methodName, args, false /* isVerification */);
  });
  if (bindings == null) {
    return null;
  }

  if (bindings.length > 1) {
    return bindings.shift().getStub();
  }
  return bindings[0].getStub();
};


/**
 * Returns a stub, if defined, for the method name and arguments passed in as
 * parameters.
 *
 * @param {string} methodName The name of the stubbed method.
 * @param {!Array<?>} args The arguments passed to the method.
 * @return {Function} The stub function or undefined.
 * @protected
 */
goog.labs.mock.MockManager_.prototype.getExecutor = function(methodName, args) {
  return this.getNextBinding(methodName, args);
};


/**
 * Looks up the list of stubs defined on the mock object and executes the
 * function associated with that stub.
 *
 * @param {string} methodName The name of the method to execute.
 * @param {...*} var_args The arguments passed to the method.
 * @return {*} Value returned by the stub function.
 * @protected
 */
goog.labs.mock.MockManager_.prototype.executeStub = function(
    methodName, var_args) {
  var args = goog.array.slice(arguments, 1);

  // Record this call
  this.recordCall_(methodName, args);

  var func = this.getExecutor(methodName, args);
  if (func) {
    return func.apply(null, args);
  }
};


/**
 * Records a call to 'methodName' with arguments 'args'.
 *
 * @param {string} methodName The name of the called method.
 * @param {!Array<?>} args The array of arguments.
 * @private
 */
goog.labs.mock.MockManager_.prototype.recordCall_ = function(methodName, args) {
  var callRecord =
      new goog.labs.mock.MethodBinding_(methodName, args, goog.nullFunction);

  this.callRecords_.push(callRecord);
};


/**
 * Verify invocation of a method with specific arguments.
 *
 * @param {string} methodName The name of the method.
 * @param {...*} var_args The arguments passed.
 * @protected
 */
goog.labs.mock.MockManager_.prototype.verifyInvocation = function(
    methodName, var_args) {
  var args = goog.array.slice(arguments, 1);
  var count = goog.array.count(this.callRecords_, function(binding) {
    return binding.matches(methodName, args, true /* isVerification */);
  });

  if (!this.verificationMode_.verify(count)) {
    throw new goog.labs.mock.VerificationError(
        this.callRecords_, methodName, this.verificationMode_, args);
  }
};



/**
 * Sets up mock for the given object (or class), stubbing out all the defined
 * methods. By default, all stubs return {@code undefined}, though stubs can be
 * later defined using {@code goog.labs.mock.when}.
 *
 * @param {!Object|!Function} objOrClass The object or class to set up the mock
 *     for. A class is a constructor function.
 *
 * @constructor
 * @struct
 * @extends {goog.labs.mock.MockManager_}
 * @private
 */
goog.labs.mock.MockObjectManager_ = function(objOrClass) {
  goog.labs.mock.MockObjectManager_.base(this, 'constructor');

  /**
   * Proxies the calls to establish the first step of the stub bindings (object
   * and method name)
   * @private
   */
  this.objectStubBinder_ = {};

  this.mockee = objOrClass;

  /**
   * The call verifier is used to verify the calls. It maps property names to
   * the method that does call verification.
   * @type {!Object<string, function(string, ...)>}
   * @private
   */
  this.objectCallVerifier_ = {};

  var obj;
  if (goog.isFunction(objOrClass)) {
    // Create a temporary subclass with a no-op constructor so that we can
    // create an instance and determine what methods it has.
    /**
 * @constructor
 * @final
 */
    var tempCtor = function() {};
    goog.inherits(tempCtor, objOrClass);
    obj = new tempCtor();
  } else {
    obj = objOrClass;
  }

  // Put the object being mocked in the prototype chain of the mock so that
  // it has all the correct properties and instanceof works.
  /**
 * @constructor
 * @final
 */
  var mockedItemCtor = function() {};
  mockedItemCtor.prototype = obj;
  this.mockedItem = new mockedItemCtor();

  var enumerableProperties = goog.object.getAllPropertyNames(obj);
  // The non enumerable properties are added due to the fact that IE8 does not
  // enumerate any of the prototype Object functions even when overriden and
  // mocking these is sometimes needed.
  for (var i = 0; i < goog.labs.mock.PROTOTYPE_FIELDS_.length; i++) {
    var prop = goog.labs.mock.PROTOTYPE_FIELDS_[i];
    if (!goog.array.contains(enumerableProperties, prop)) {
      enumerableProperties.push(prop);
    }
  }

  // Adds the properties to the mock, creating a proxy stub for each method on
  // the instance.
  for (var i = 0; i < enumerableProperties.length; i++) {
    var prop = enumerableProperties[i];
    if (goog.isFunction(obj[prop])) {
      this.mockedItem[prop] = goog.bind(this.executeStub, this, prop);
      // The stub binder used to create bindings.
      this.objectStubBinder_[prop] =
          goog.bind(this.handleMockCall_, this, prop);
      // The verifier verifies the calls.
      this.objectCallVerifier_[prop] =
          goog.bind(this.verifyInvocation, this, prop);
    }
  }
  // The alias for stub binder exposed to the world.
  this.mockedItem.$stubBinder = this.objectStubBinder_;

  // The alias for verifier for the world.
  this.mockedItem.$callVerifier = this.objectCallVerifier_;

  this.mockedItem.$verificationModeSetter =
      goog.bind(this.setVerificationMode_, this);
};
goog.inherits(goog.labs.mock.MockObjectManager_, goog.labs.mock.MockManager_);



/**
 * Sets up the spying behavior for the given object.
 *
 * @param {!Object} obj The object to be spied on.
 *
 * @constructor
 * @struct
 * @extends {goog.labs.mock.MockObjectManager_}
 * @private
 */
goog.labs.mock.MockSpyManager_ = function(obj) {
  goog.labs.mock.MockSpyManager_.base(this, 'constructor', obj);
};
goog.inherits(
    goog.labs.mock.MockSpyManager_, goog.labs.mock.MockObjectManager_);


/**
 * Return a stub, if defined, for the method and arguments passed in. If we lack
 * a stub, instead look for a call record that matches the method and arguments.
 *
 * @return {!Function} The stub or the invocation logger, if defined.
 * @override
 */
goog.labs.mock.MockSpyManager_.prototype.getNextBinding = function(
    methodName, args) {
  var stub = goog.labs.mock.MockSpyManager_.base(
      this, 'getNextBinding', methodName, args);

  if (!stub) {
    stub = goog.bind(this.mockee[methodName], this.mockee);
  }

  return stub;
};



/**
 * Sets up mock for the given function, stubbing out. By default, all stubs
 * return {@code undefined}, though stubs can be later defined using
 * {@code goog.labs.mock.when}.
 *
 * @param {!Function} func The function to set up the mock for.
 *
 * @constructor
 * @struct
 * @extends {goog.labs.mock.MockManager_}
 * @private
 */
goog.labs.mock.MockFunctionManager_ = function(func) {
  goog.labs.mock.MockFunctionManager_.base(this, 'constructor');

  this.func_ = func;

  /**
   * The stub binder used to create bindings.
   * Sets the first argument of handleMockCall_ to the function name.
   * @type {!Function}
   * @private
   */
  this.functionStubBinder_ = this.useMockedFunctionName_(this.handleMockCall_);

  this.mockedItem = this.useMockedFunctionName_(this.executeStub);
  this.mockedItem.$stubBinder = this.functionStubBinder_;

  /**
   * The call verifier is used to verify function invocations.
   * Sets the first argument of verifyInvocation to the function name.
   * @type {!Function}
   */
  this.mockedItem.$callVerifier =
      this.useMockedFunctionName_(this.verifyInvocation);

  // This has to be repeated because if it's set in base class it will be
  // stubbed by MockObjectManager.
  this.mockedItem.$verificationModeSetter =
      goog.bind(this.setVerificationMode_, this);
};
goog.inherits(goog.labs.mock.MockFunctionManager_, goog.labs.mock.MockManager_);


/**
 * Given a method, returns a new function that calls the first one setting
 * the first argument to the mocked function name.
 * This is used to dynamically override the stub binders and call verifiers.
 * @private
 * @param {Function} nextFunc The function to override.
 * @return {!Function} The overloaded function.
 */
goog.labs.mock.MockFunctionManager_.prototype.useMockedFunctionName_ = function(
    nextFunc) {
  var mockFunctionManager = this;
  // Avoid using 'this' because this function may be called with 'new'.
  return function(var_args) {
    var args = goog.array.clone(arguments);
    var name = '#mockFor<' +
        goog.labs.mock.getFunctionName_(mockFunctionManager.func_) + '>';
    goog.array.insertAt(args, name, 0);
    return nextFunc.apply(mockFunctionManager, args);
  };
};


/**
 * A stub binder is an object that helps define the stub by binding
 * method name to the stub method.
 * @interface
 */
goog.labs.mock.StubBinder = function() {};


/**
 * Defines the function to be called for the method name and arguments bound
 * to this {@code StubBinder}.
 *
 * If {@code then} or {@code thenReturn} has been previously called
 * on this {@code StubBinder} then the given stub {@code func} will be called
 * only after the stubs passed previously have been called.  Afterwards,
 * if no other calls are made to {@code then} or {@code thenReturn} for this
 * {@code StubBinder} then the given {@code func} will be used for every further
 * invocation.
 * See #when for complete examples.
 * TODO(user): Add support for the 'Answer' interface.
 *
 * @param {!Function} func The function to call.
 * @return {!goog.labs.mock.StubBinder} Returns itself for chaining.
 */
goog.labs.mock.StubBinder.prototype.then = goog.abstractMethod;


/**
 * Defines the constant return value for the stub represented by this
 * {@code StubBinder}.
 *
 * @param {*} value The value to return.
 * @return {!goog.labs.mock.StubBinder} Returns itself for chaining.
 */
goog.labs.mock.StubBinder.prototype.thenReturn = goog.abstractMethod;


/**
 * A {@code StubBinder} which uses {@code MockManager_} to manage stub
 * bindings.
 *
 * @param {!goog.labs.mock.MockManager_}
 *   mockManager The mock manager.
 * @param {?string} name The method name.
 * @param {!Array<?>} args The other arguments to the method.
 *
 * @implements {goog.labs.mock.StubBinder}
 * @private @constructor @struct @final
 */
goog.labs.mock.StubBinderImpl_ = function(mockManager, name, args) {
  /**
   * The mock manager instance.
   * @type {!goog.labs.mock.MockManager_}
   * @private
   */
  this.mockManager_ = mockManager;

  /**
   * Holds the name of the method to be bound.
   * @type {?string}
   * @private
   */
  this.name_ = name;

  /**
   * Holds the arguments for the method.
   * @type {!Array<?>}
   * @private
   */
  this.args_ = args;

  /**
   * Stores a reference to the list of stubs to allow chaining sequential
   * stubs.
   * @private {!Array<?>}
   */
  this.sequentialStubsArray_ = [];
};


/**
 * @override
 */
goog.labs.mock.StubBinderImpl_.prototype.then = function(func) {
  if (this.sequentialStubsArray_.length) {
    this.sequentialStubsArray_.push(
        new goog.labs.mock.MethodBinding_(this.name_, this.args_, func));
  } else {
    this.sequentialStubsArray_ =
        this.mockManager_.addBinding(this.name_, this.args_, func);
  }
  return this;
};


/**
 * @override
 */
goog.labs.mock.StubBinderImpl_.prototype.thenReturn = function(value) {
  return this.then(goog.functions.constant(value));
};


/**
 * Facilitates (and is the first step in) setting up stubs. Obtains an object
 * on which, the method to be mocked is called to create a stub. Sample usage:
 *
 * var mockObj = goog.labs.mock.mock(objectBeingMocked);
 * goog.labs.mock.when(mockObj).getFoo(3).thenReturn(4);
 *
 * Subsequent calls to {@code when} take precedence over earlier calls, allowing
 * users to set up default stubs in setUp methods and then override them in
 * individual tests.
 *
 * If a user wants sequential calls to their stub to return different
 * values, they can chain calls to {@code then} or {@code thenReturn} as
 * follows:
 *
 * var mockObj = goog.labs.mock.mock(objectBeingMocked);
 * goog.labs.mock.when(mockObj).getFoo(3)
 *     .thenReturn(4)
 *     .then(function() {
 *         throw new Error('exceptional case');
 *     });
 *
 * @param {!Object} mockObject The mocked object.
 * @return {?} The property binder. Return type {?} to avoid compilation errors.
 */
goog.labs.mock.when = function(mockObject) {
  goog.asserts.assert(mockObject.$stubBinder, 'Stub binder cannot be null!');
  return mockObject.$stubBinder;
};



/**
 * Represents a binding between a method name, args and a stub.
 *
 * @param {?string} methodName The name of the method being stubbed.
 * @param {!Array<?>} args The arguments passed to the method.
 * @param {!Function} stub The stub function to be called for the given method.
 * @constructor
 * @struct
 * @private
 */
goog.labs.mock.MethodBinding_ = function(methodName, args, stub) {
  /**
   * The name of the method being stubbed.
   * @type {?string}
   * @private
   */
  this.methodName_ = methodName;

  /**
   * The arguments for the method being stubbed.
   * @type {!Array<?>}
   * @private
   */
  this.args_ = args;

  /**
   * The stub function.
   * @type {!Function}
   * @private
   */
  this.stub_ = stub;
};


/**
 * @return {!Function} The stub to be executed.
 */
goog.labs.mock.MethodBinding_.prototype.getStub = function() {
  return this.stub_;
};


/**
 * @override
 * @return {string} A readable string representation of the binding
 *  as a method call.
 */
goog.labs.mock.MethodBinding_.prototype.toString = function() {
  return goog.labs.mock.formatMethodCall_(this.methodName_ || '', this.args_);
};


/**
 * @return {string} The method name for this binding.
 */
goog.labs.mock.MethodBinding_.prototype.getMethodName = function() {
  return this.methodName_ || '';
};


/**
 * Determines whether the given args match the stored args_. Used to determine
 * which stub to invoke for a method.
 *
 * @param {string} methodName The name of the method being stubbed.
 * @param {!Array<?>} args An array of arguments.
 * @param {boolean} isVerification Whether this is a function verification call
 *     or not.
 * @return {boolean} If it matches the stored arguments.
 */
goog.labs.mock.MethodBinding_.prototype.matches = function(
    methodName, args, isVerification) {
  var specs = isVerification ? args : this.args_;
  var calls = isVerification ? this.args_ : args;

  // TODO(user): More elaborate argument matching. Think about matching
  //    objects.
  return this.methodName_ == methodName &&
      goog.array.equals(calls, specs, function(arg, spec) {
        // Duck-type to see if this is an object that implements the
        // goog.labs.testing.Matcher interface.
        if (spec && goog.isFunction(spec.matches)) {
          return spec.matches(arg);
        } else {
          return goog.array.defaultCompareEquality(spec, arg);
        }
      });
};