Debian Codegraph @

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

raw
1 // Copyright 2008 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 This file defines base classes used for creating mocks in
17 * JavaScript. The API was inspired by EasyMock.
18 *
19 * The basic API is:
20 * <ul>
21 * <li>Create an object to be mocked
22 * <li>Create a mock object, passing in the above object to the constructor
23 * <li>Set expectations by calling methods on the mock object
24 * <li>Call $replay() on the mock object
25 * <li>Pass the mock to code that will make real calls on it
26 * <li>Call $verify() to make sure that expectations were met
27 * </ul>
28 *
29 * For examples, please see the unit tests for LooseMock and StrictMock.
30 *
31 * Still TODO
32 * implement better (and pluggable) argument matching
33 * Have the exceptions for LooseMock show the number of expected/actual calls
34 * loose and strict mocks share a lot of code - move it to the base class
35 *
36 */
37
38 goog.setTestOnly('goog.testing.Mock');
39 goog.provide('goog.testing.Mock');
40 goog.provide('goog.testing.MockExpectation');
41
42 goog.require('goog.array');
43 goog.require('goog.object');
44 goog.require('goog.testing.JsUnitException');
45 goog.require('goog.testing.MockInterface');
46 goog.require('goog.testing.mockmatchers');
47
48
49
50 /**
51 * This is a class that represents an expectation.
52 * @param {string} name The name of the method for this expectation.
53 * @constructor
54 * @final
55 */
56 goog.testing.MockExpectation = function(name) {
57 /**
58 * The name of the method that is expected to be called.
59 * @type {string}
60 */
61 this.name = name;
62
63 /**
64 * An array of error messages for expectations not met.
65 * @type {Array<string>}
66 */
67 this.errorMessages = [];
68 };
69
70
71 /**
72 * The minimum number of times this method should be called.
73 * @type {number}
74 */
75 goog.testing.MockExpectation.prototype.minCalls = 1;
76
77
78 /**
79 * The maximum number of times this method should be called.
80 * @type {number}
81 */
82 goog.testing.MockExpectation.prototype.maxCalls = 1;
83
84
85 /**
86 * The value that this method should return.
87 * @type {*}
88 */
89 goog.testing.MockExpectation.prototype.returnValue;
90
91
92 /**
93 * The value that will be thrown when the method is called
94 * @type {*}
95 */
96 goog.testing.MockExpectation.prototype.exceptionToThrow;
97
98
99 /**
100 * The arguments that are expected to be passed to this function
101 * @type {Array<*>}
102 */
103 goog.testing.MockExpectation.prototype.argumentList;
104
105
106 /**
107 * The number of times this method is called by real code.
108 * @type {number}
109 */
110 goog.testing.MockExpectation.prototype.actualCalls = 0;
111
112
113 /**
114 * The number of times this method is called during the verification phase.
115 * @type {number}
116 */
117 goog.testing.MockExpectation.prototype.verificationCalls = 0;
118
119
120 /**
121 * The function which will be executed when this method is called.
122 * Method arguments will be passed to this function, and return value
123 * of this function will be returned by the method.
124 * @type {Function}
125 */
126 goog.testing.MockExpectation.prototype.toDo;
127
128
129 /**
130 * Allow expectation failures to include messages.
131 * @param {string} message The failure message.
132 */
133 goog.testing.MockExpectation.prototype.addErrorMessage = function(message) {
134 this.errorMessages.push(message);
135 };
136
137
138 /**
139 * Get the error messages seen so far.
140 * @return {string} Error messages separated by \n.
141 */
142 goog.testing.MockExpectation.prototype.getErrorMessage = function() {
143 return this.errorMessages.join('\n');
144 };
145
146
147 /**
148 * Get how many error messages have been seen so far.
149 * @return {number} Count of error messages.
150 */
151 goog.testing.MockExpectation.prototype.getErrorMessageCount = function() {
152 return this.errorMessages.length;
153 };
154
155
156
157 /**
158 * The base class for a mock object.
159 * @param {Object|Function} objectToMock The object that should be mocked, or
160 * the constructor of an object to mock.
161 * @param {boolean=} opt_mockStaticMethods An optional argument denoting that
162 * a mock should be constructed from the static functions of a class.
163 * @param {boolean=} opt_createProxy An optional argument denoting that
164 * a proxy for the target mock should be created.
165 * @constructor
166 * @implements {goog.testing.MockInterface}
167 */
168 goog.testing.Mock = function(
169 objectToMock, opt_mockStaticMethods, opt_createProxy) {
170 if (!goog.isObject(objectToMock) && !goog.isFunction(objectToMock)) {
171 throw new Error('objectToMock must be an object or constructor.');
172 }
173 if (opt_createProxy && !opt_mockStaticMethods &&
174 goog.isFunction(objectToMock)) {
175 /**
176 * @constructor
177 * @final
178 */
179 var tempCtor = function() {};
180 goog.inherits(tempCtor, objectToMock);
181 this.$proxy = new tempCtor();
182 } else if (
183 opt_createProxy && opt_mockStaticMethods &&
184 goog.isFunction(objectToMock)) {
185 throw new Error('Cannot create a proxy when opt_mockStaticMethods is true');
186 } else if (opt_createProxy && !goog.isFunction(objectToMock)) {
187 throw new Error('Must have a constructor to create a proxy');
188 }
189
190 if (goog.isFunction(objectToMock) && !opt_mockStaticMethods) {
191 this.$initializeFunctions_(objectToMock.prototype);
192 } else {
193 this.$initializeFunctions_(objectToMock);
194 }
195 this.$argumentListVerifiers_ = {};
196 };
197
198
199 /**
200 * Option that may be passed when constructing function, method, and
201 * constructor mocks. Indicates that the expected calls should be accepted in
202 * any order.
203 * @const
204 * @type {number}
205 */
206 goog.testing.Mock.LOOSE = 1;
207
208
209 /**
210 * Option that may be passed when constructing function, method, and
211 * constructor mocks. Indicates that the expected calls should be accepted in
212 * the recorded order only.
213 * @const
214 * @type {number}
215 */
216 goog.testing.Mock.STRICT = 0;
217
218
219 /**
220 * This array contains the name of the functions that are part of the base
221 * Object prototype.
222 * Basically a copy of goog.object.PROTOTYPE_FIELDS_.
223 * @const
224 * @type {!Array<string>}
225 * @private
226 */
227 goog.testing.Mock.OBJECT_PROTOTYPE_FIELDS_ = [
228 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
229 'toLocaleString', 'toString', 'valueOf'
230 ];
231
232
233 /**
234 * This array contains the name of the functions that are part of the base
235 * Function prototype. The restricted field 'caller' and 'arguments' are
236 * excluded.
237 * @const
238 * @type {!Array<string>}
239 * @private
240 */
241 goog.testing.Mock.FUNCTION_PROTOTYPE_FIELDS_ = ['apply', 'bind', 'call'];
242
243
244 /**
245 * A proxy for the mock. This can be used for dependency injection in lieu of
246 * the mock if the test requires a strict instanceof check.
247 * @type {Object}
248 */
249 goog.testing.Mock.prototype.$proxy = null;
250
251
252 /**
253 * Map of argument name to optional argument list verifier function.
254 * @type {Object}
255 */
256 goog.testing.Mock.prototype.$argumentListVerifiers_;
257
258
259 /**
260 * Whether or not we are in recording mode.
261 * @type {boolean}
262 * @private
263 */
264 goog.testing.Mock.prototype.$recording_ = true;
265
266
267 /**
268 * The expectation currently being created. All methods that modify the
269 * current expectation return the Mock object for easy chaining, so this is
270 * where we keep track of the expectation that's currently being modified.
271 * @type {goog.testing.MockExpectation}
272 * @protected
273 */
274 goog.testing.Mock.prototype.$pendingExpectation;
275
276
277 /**
278 * First exception thrown by this mock; used in $verify.
279 * @type {Object}
280 * @private
281 */
282 goog.testing.Mock.prototype.$threwException_ = null;
283
284
285 /**
286 * Initializes the functions on the mock object.
287 * @param {Object} objectToMock The object being mocked.
288 * @private
289 */
290 goog.testing.Mock.prototype.$initializeFunctions_ = function(objectToMock) {
291 // Gets the object properties.
292 var enumerableProperties = goog.object.getAllPropertyNames(
293 objectToMock, false /* opt_includeObjectPrototype */,
294 false /* opt_includeFunctionPrototype */);
295
296 if (goog.isFunction(objectToMock)) {
297 for (var i = 0; i < goog.testing.Mock.FUNCTION_PROTOTYPE_FIELDS_.length;
298 i++) {
299 var prop = goog.testing.Mock.FUNCTION_PROTOTYPE_FIELDS_[i];
300 // Look at b/6758711 if you're considering adding ALL properties to ALL
301 // mocks.
302 if (objectToMock[prop] !== Function.prototype[prop]) {
303 enumerableProperties.push(prop);
304 }
305 }
306 }
307
308 // The non enumerable properties are added if they override the ones in the
309 // Object prototype. This is due to the fact that IE8 does not enumerate any
310 // of the prototype Object functions even when overriden and mocking these is
311 // sometimes needed.
312 for (var i = 0; i < goog.testing.Mock.OBJECT_PROTOTYPE_FIELDS_.length; i++) {
313 var prop = goog.testing.Mock.OBJECT_PROTOTYPE_FIELDS_[i];
314 // Look at b/6758711 if you're considering adding ALL properties to ALL
315 // mocks.
316 if (objectToMock[prop] !== Object.prototype[prop]) {
317 enumerableProperties.push(prop);
318 }
319 }
320
321 // Adds the properties to the mock.
322 for (var i = 0; i < enumerableProperties.length; i++) {
323 var prop = enumerableProperties[i];
324 if (typeof objectToMock[prop] == 'function') {
325 this[prop] = goog.bind(this.$mockMethod, this, prop);
326 if (this.$proxy) {
327 this.$proxy[prop] = goog.bind(this.$mockMethod, this, prop);
328 }
329 }
330 }
331 };
332
333
334 /**
335 * Registers a verifier function to use when verifying method argument lists.
336 * @param {string} methodName The name of the method for which the verifierFn
337 * should be used.
338 * @param {Function} fn Argument list verifier function. Should take 2 argument
339 * arrays as arguments, and return true if they are considered equivalent.
340 * @return {!goog.testing.Mock} This mock object.
341 */
342 goog.testing.Mock.prototype.$registerArgumentListVerifier = function(
343 methodName, fn) {
344 this.$argumentListVerifiers_[methodName] = fn;
345 return this;
346 };
347
348
349 /**
350 * The function that replaces all methods on the mock object.
351 * @param {string} name The name of the method being mocked.
352 * @return {*} In record mode, returns the mock object. In replay mode, returns
353 * whatever the creator of the mock set as the return value.
354 */
355 goog.testing.Mock.prototype.$mockMethod = function(name) {
356 try {
357 // Shift off the name argument so that args contains the arguments to
358 // the mocked method.
359 var args = goog.array.slice(arguments, 1);
360 if (this.$recording_) {
361 this.$pendingExpectation = new goog.testing.MockExpectation(name);
362 this.$pendingExpectation.argumentList = args;
363 this.$recordExpectation();
364 return this;
365 } else {
366 return this.$recordCall(name, args);
367 }
368 } catch (ex) {
369 this.$recordAndThrow(ex);
370 }
371 };
372
373
374 /**
375 * Records the currently pending expectation, intended to be overridden by a
376 * subclass.
377 * @protected
378 */
379 goog.testing.Mock.prototype.$recordExpectation = function() {};
380
381
382 /**
383 * Records an actual method call, intended to be overridden by a
384 * subclass. The subclass must find the pending expectation and return the
385 * correct value.
386 * @param {string} name The name of the method being called.
387 * @param {Array<?>} args The arguments to the method.
388 * @return {*} The return expected by the mock.
389 * @protected
390 */
391 goog.testing.Mock.prototype.$recordCall = function(name, args) {
392 return undefined;
393 };
394
395
396 /**
397 * If the expectation expects to throw, this method will throw.
398 * @param {goog.testing.MockExpectation} expectation The expectation.
399 */
400 goog.testing.Mock.prototype.$maybeThrow = function(expectation) {
401 if (typeof expectation.exceptionToThrow != 'undefined') {
402 throw expectation.exceptionToThrow;
403 }
404 };
405
406
407 /**
408 * If this expectation defines a function to be called,
409 * it will be called and its result will be returned.
410 * Otherwise, if the expectation expects to throw, it will throw.
411 * Otherwise, this method will return defined value.
412 * @param {goog.testing.MockExpectation} expectation The expectation.
413 * @param {Array<?>} args The arguments to the method.
414 * @return {*} The return value expected by the mock.
415 */
416 goog.testing.Mock.prototype.$do = function(expectation, args) {
417 if (typeof expectation.toDo == 'undefined') {
418 this.$maybeThrow(expectation);
419 return expectation.returnValue;
420 } else {
421 return expectation.toDo.apply(this, args);
422 }
423 };
424
425
426 /**
427 * Specifies a return value for the currently pending expectation.
428 * @param {*} val The return value.
429 * @return {!goog.testing.Mock} This mock object.
430 */
431 goog.testing.Mock.prototype.$returns = function(val) {
432 this.$pendingExpectation.returnValue = val;
433 return this;
434 };
435
436
437 /**
438 * Specifies a value for the currently pending expectation to throw.
439 * @param {*} val The value to throw.
440 * @return {!goog.testing.Mock} This mock object.
441 */
442 goog.testing.Mock.prototype.$throws = function(val) {
443 this.$pendingExpectation.exceptionToThrow = val;
444 return this;
445 };
446
447
448 /**
449 * Specifies a function to call for currently pending expectation.
450 * Note, that using this method overrides declarations made
451 * using $returns() and $throws() methods.
452 * @param {Function} func The function to call.
453 * @return {!goog.testing.Mock} This mock object.
454 */
455 goog.testing.Mock.prototype.$does = function(func) {
456 this.$pendingExpectation.toDo = func;
457 return this;
458 };
459
460
461 /**
462 * Allows the expectation to be called 0 or 1 times.
463 * @return {!goog.testing.Mock} This mock object.
464 */
465 goog.testing.Mock.prototype.$atMostOnce = function() {
466 this.$pendingExpectation.minCalls = 0;
467 this.$pendingExpectation.maxCalls = 1;
468 return this;
469 };
470
471
472 /**
473 * Allows the expectation to be called any number of times, as long as it's
474 * called once.
475 * @return {!goog.testing.Mock} This mock object.
476 */
477 goog.testing.Mock.prototype.$atLeastOnce = function() {
478 this.$pendingExpectation.maxCalls = Infinity;
479 return this;
480 };
481
482
483 /**
484 * Allows the expectation to be called exactly once.
485 * @return {!goog.testing.Mock} This mock object.
486 */
487 goog.testing.Mock.prototype.$once = function() {
488 this.$pendingExpectation.minCalls = 1;
489 this.$pendingExpectation.maxCalls = 1;
490 return this;
491 };
492
493
494 /**
495 * Disallows the expectation from being called.
496 * @return {!goog.testing.Mock} This mock object.
497 */
498 goog.testing.Mock.prototype.$never = function() {
499 this.$pendingExpectation.minCalls = 0;
500 this.$pendingExpectation.maxCalls = 0;
501 return this;
502 };
503
504
505 /**
506 * Allows the expectation to be called any number of times.
507 * @return {!goog.testing.Mock} This mock object.
508 */
509 goog.testing.Mock.prototype.$anyTimes = function() {
510 this.$pendingExpectation.minCalls = 0;
511 this.$pendingExpectation.maxCalls = Infinity;
512 return this;
513 };
514
515
516 /**
517 * Specifies the number of times the expectation should be called.
518 * @param {number} times The number of times this method will be called.
519 * @return {!goog.testing.Mock} This mock object.
520 */
521 goog.testing.Mock.prototype.$times = function(times) {
522 this.$pendingExpectation.minCalls = times;
523 this.$pendingExpectation.maxCalls = times;
524 return this;
525 };
526
527
528 /**
529 * Switches from recording to replay mode.
530 * @override
531 */
532 goog.testing.Mock.prototype.$replay = function() {
533 this.$recording_ = false;
534 };
535
536
537 /**
538 * Resets the state of this mock object. This clears all pending expectations
539 * without verifying, and puts the mock in recording mode.
540 * @override
541 */
542 goog.testing.Mock.prototype.$reset = function() {
543 this.$recording_ = true;
544 this.$threwException_ = null;
545 delete this.$pendingExpectation;
546 };
547
548
549 /**
550 * Throws an exception and records that an exception was thrown.
551 * @param {string} comment A short comment about the exception.
552 * @param {?string=} opt_message A longer message about the exception.
553 * @throws {Object} JsUnitException object.
554 * @protected
555 */
556 goog.testing.Mock.prototype.$throwException = function(comment, opt_message) {
557 this.$recordAndThrow(new goog.testing.JsUnitException(comment, opt_message));
558 };
559
560
561 /**
562 * Throws an exception and records that an exception was thrown.
563 * @param {Object} ex Exception.
564 * @throws {Object} #ex.
565 * @protected
566 */
567 goog.testing.Mock.prototype.$recordAndThrow = function(ex) {
568 // If it's an assert exception, record it.
569 if (ex['isJsUnitException']) {
570 var testRunner = goog.global['G_testRunner'];
571 if (testRunner) {
572 var logTestFailureFunction = testRunner['logTestFailure'];
573 if (logTestFailureFunction) {
574 logTestFailureFunction.call(testRunner, ex);
575 }
576 }
577
578 if (!this.$threwException_) {
579 // Only remember first exception thrown.
580 this.$threwException_ = ex;
581 }
582 }
583 throw ex;
584 };
585
586
587 /**
588 * Verify that all of the expectations were met. Should be overridden by
589 * subclasses.
590 * @override
591 */
592 goog.testing.Mock.prototype.$verify = function() {
593 if (this.$threwException_) {
594 throw this.$threwException_;
595 }
596 };
597
598
599 /**
600 * Verifies that a method call matches an expectation.
601 * @param {goog.testing.MockExpectation} expectation The expectation to check.
602 * @param {string} name The name of the called method.
603 * @param {Array<*>?} args The arguments passed to the mock.
604 * @return {boolean} Whether the call matches the expectation.
605 */
606 goog.testing.Mock.prototype.$verifyCall = function(expectation, name, args) {
607 if (expectation.name != name) {
608 return false;
609 }
610 var verifierFn =
611 this.$argumentListVerifiers_.hasOwnProperty(expectation.name) ?
612 this.$argumentListVerifiers_[expectation.name] :
613 goog.testing.mockmatchers.flexibleArrayMatcher;
614
615 return verifierFn(expectation.argumentList, args, expectation);
616 };
617
618
619 /**
620 * Render the provided argument array to a string to help
621 * clients with debugging tests.
622 * @param {Array<*>?} args The arguments passed to the mock.
623 * @return {string} Human-readable string.
624 */
625 goog.testing.Mock.prototype.$argumentsAsString = function(args) {
626 var retVal = [];
627 for (var i = 0; i < args.length; i++) {
628 try {
629 retVal.push(goog.typeOf(args[i]));
630 } catch (e) {
631 retVal.push('[unknown]');
632 }
633 }
634 return '(' + retVal.join(', ') + ')';
635 };
636
637
638 /**
639 * Throw an exception based on an incorrect method call.
640 * @param {string} name Name of method called.
641 * @param {Array<*>?} args Arguments passed to the mock.
642 * @param {goog.testing.MockExpectation=} opt_expectation Expected next call,
643 * if any.
644 */
645 goog.testing.Mock.prototype.$throwCallException = function(
646 name, args, opt_expectation) {
647 var errorStringBuffer = [];
648 var actualArgsString = this.$argumentsAsString(args);
649 var expectedArgsString = opt_expectation ?
650 this.$argumentsAsString(opt_expectation.argumentList) :
651 '';
652
653 if (opt_expectation && opt_expectation.name == name) {
654 errorStringBuffer.push(
655 'Bad arguments to ', name, '().\n', 'Actual: ', actualArgsString, '\n',
656 'Expected: ', expectedArgsString, '\n',
657 opt_expectation.getErrorMessage());
658 } else {
659 errorStringBuffer.push('Unexpected call to ', name, actualArgsString, '.');
660 if (opt_expectation) {
661 errorStringBuffer.push(
662 '\nNext expected call was to ', opt_expectation.name,
663 expectedArgsString);
664 }
665 }
666 this.$throwException(errorStringBuffer.join(''));
667 };