jeudi 26 mars 2015

Using function parameters to improve testability

I'm interested in finding out which is a better way to do this. Say I have the following object



var myObject = (function(){
function myObject(myName){
this.myName = myName
};

myObject.prototype.checkNameIsJames = function(){
return this.myName === 'James';
}

return myObject;
};

var newObject = new myObject('James');


To test the checkNameIsJames method, I rely on a parameter passed into the constructor. This works nicely because everywhere I can call it without parameters:



var result = newObject.checkNameIsJames().


But it is always bound (in this specific situation) to the constructor. The other way would be to supply the name as a parameter:



var myObject = (function(){
function myObject(myName){
this.myName = myName
};

myObject.prototype.checkNameIsJames = function(name){
return name === 'James';
}

return myObject;
};

var newObject = new myObject('James');


In which case I can do all kinds of unit tests with different names



var o = new myObject('James');
var result = o.checkNameIsJames(o.myName);
var result = o.checkNameIsJames('Peter');


This is a fairly contrived example, but if you imagined this as a much larger example with many objects functions and vairables, should I be aiming to use parameters as much as possible even when not technically necessary so that I can improve the coverage of my testing? Or would that be considered uneeded complexity for the sake of completing unit tests?


Aucun commentaire:

Enregistrer un commentaire