您的位置:软件测试 > 开源软件测试 > 开源软件测试解决方案 > 开源测试工具组合
通过Qunit对Javascript代码进行单元测试
作者:网络转载 发布时间:[ 2013/12/11 9:12:44 ] 推荐标签:

  在现在的软件开发中,单元测试已经变得越来越重要了.相比程序员与测试QA的手工测试,单元测试可以在项目每次build的时候集成运行,来为程序员提供Regression Test的反馈.这在敏捷开发中为程序员提供了很重要的支持,可以很容易的进行重构. 现在的主流编程语言都有很好的对单元测试的支持, 关于JUnit和NUnit的文章也已经有很多了. 在这里,我们介绍一下如何使用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));
}
}
}
}

上一页123下一页
软件测试工具 | 联系我们 | 投诉建议 | 诚聘英才 | 申请使用列表 | 网站地图
沪ICP备07036474 2003-2017 版权所有 上海泽众软件科技有限公司 Shanghai ZeZhong Software Co.,Ltd