-
Notifications
You must be signed in to change notification settings - Fork 0
Home
justinperkins edited this page Sep 12, 2010
·
4 revisions
Example usage in a unittest file. Given the following code:
var Barista = Class.create({
initialize: function(name){
this.name = name;
},
makeItADouble: function(){
this._addEspresso();
},
makeItASingle: function(){
// not going to do anything, to illustrate a method not being invoked
},
withCream: function(nonDairy){
if (nonDairy) this._addSoy();
else this._addMilk();
},
_addMilk: function(){},
_addSoy: function(){},
_addEspresso: function(){},
_removeEspresso: function(){}
})
This is an example unittest:
new Test.Unit.Runner({
setup: function() {
},
teardown: function() {
},
testMakeItADouble: function(){ with(this) {
// create a new mock, passing in the class we are going to watch, and the method we are expecting to be invoked
var mock = new Latte(Barista, '_addEspresso');
// create a new class instance
var b = new Barista('justin');
// invoke a method on this class, which should invoke the _addEspresso method
b.makeItADouble();
// make sure our method was invoked
assert(mock.wasInvoked('_addEspresso'), 'Barista#makeItASingle expected to invoke _addEspresso but did not');
// after each test, make sure to call teardown on the mock instance to ensure the expectation wrappers are removed
mock.teardown();
}},
testMakeItASingle: function(){ with(this) {
var mock = new Latte(Barista);
var b = new Barista('justin');
mock.expects('_removeEspresso');
b.makeItASingle();
assert(mock.wasInvoked('_removeEspresso'), 'Barista#makeItASingle expected to invoke _removeEspresso but did not (this was an intentional failure to illustrate failed expectations)');
mock.teardown();
}},
testWithCream: function(){ with(this) {
var mock = new Latte(Barista);
var b = new Barista('justin');
mock.expects('_addMilk');
b.withCream();
assert(mock.wasInvoked('_addMilk'), 'Barista#withCream expected to invoke _addMilk but did not');
mock.reset('_addMilk');
mock.expects('_addSoy');
b.withCream(true);
assert(mock.notInvoked('_addMilk'), 'Barista#withCream expected not to invoke _addMilk but did');
assert(mock.wasInvoked('_addSoy'), 'Barista#withCream expected not to invoke _addSoy but did not');
mock.teardown();
}}
}, {testLog: "testlog"});
</code.