在現(xiàn)在的軟件開發(fā)中,單元測試已經(jīng)變得越來越重要了.相比程序員與測試QA的手工測試,單元測試可以在項目每次build的時候集成運行,來為程序員提供Regression Test的反饋.這在敏捷開發(fā)中為程序員提供了很重要的支持,可以很容易的進行重構(gòu). 現(xiàn)在的主流編程語言都有很好的對單元測試的支持, 關(guān)于JUnit和NUnit的文章也已經(jīng)有很多了. 在這里,我們介紹一下如何使用QUnit對Javascript腳本進行單元測試.
在這里我們使用一個簡單的撲克的例子. 首先,我們用Javascript寫一個簡單的撲克牌類:
var Card = function(opts) {
var C = {};
C._normalizeArg = function(arg) {
if (_.isString(arg)) {
arg = arg.replace(/s+/g,'').split(",");
}
if (!_.isArray(arg)) {
arg = [arg];
}
return arg;
};
C.extend = function(obj) {
_(C).extend(obj);
return C;
};
C.CardKind = {
"Spade" : "spade",
"Heart" : "heart",
"Diamond" : "diamond",
"Club" : "club",
"Special" : "special"
};
C.CardNum = {
"Ace" : 1,
"Two" : 2,
"Three" : 3,
"Four" : 4,
"Five" : 5,
"Six" : 6,
"Seven" : 7,
"Eight" : 8,
"Nine" : 9,
"Ten" : 10,
"Jack" : 11,
"Queen" : 12,
"King" : 13,
"JokerS" : 14,
"Joker" : 15
};
C.Card = Class.extend({
init : function(kind, num) {
this.kind = kind;
this.num = num;
},
name : function() {
return this.kind + this.num;
},
isComparable : function(card) {
return this.kind == card.kind;
},
compareTo : function (card) {
if (this.isComparable(card)) {
return this.num - card.num;
}
}
});
C.Deck = Class.extend({
init : function(numOfDecks, includeJokers, jokersAreDifferent, cards) {
this.numOfDecks = numOfDecks == undefined ? 1 : numOfDecks;
this.includeJokers = includeJokers == undefined ? false : includeJokers;
this.jokersAreDifferent = jokersAreDifferent == undefined ? false : jokersAreDifferent;
this.cards = [];
this.setup(cards);
},
setup : function(cards) {
if (cards == undefined) {
var kinds = _.filter(C.CardKind, function(kind) {return kind != C.CardKind.Special; });
var nums = _.filter(C.CardNum, function(num) {return num <= C.CardNum.King; });
for (var i = 1; i <= this.numOfDecks; i++) {
for (var kind in kinds) {
for (var num in nums) {
this.cards.push(new C.Card(kinds[kind], nums[num]));
}
}
if (this.includeJokers) {
if (this.jokersAreDifferent) {
this.cards.push(new C.Card(C.CardKind.Special, C.CardNum.JokerS));
this.cards.push(new C.Card(C.CardKind.Special, C.CardNum.Joker));
} else {
this.cards.push(new C.Card(C.CardKind.Special, C.CardNum.Joker));
this.cards.push(new C.Card(C.CardKind.Special, C.CardNum.Joker));
}
}
}
}