我正在尝试编写单元测试。如果函数得到负数,则会抛出新错误。
Obj = function () {
};
Obj.prototype.Count = function (number) {
if (number < 0) {
throw new Error("There is no function for negative numbers");
} else...
我的unit-tet功能:
function test(then,expected) {
results.total++;
var m1=new Obj();
if (m1.Count(then)!=expected){
results.bad++;
alert(m1.Count(then)+" not equal "+expected);
}
}
var results = {
total: 0,
bad: 0
};
然后我正在尝试运行测试
test(5,120)
test(-5, "There is no function for negative numbers");
第一个正常工作,但我不知道对于负数会写什么'预期'。该示例不起作用。 你能告诉我吗?
谢谢!
答案 0 :(得分:0)
If you are going to test errors, you'll need to use a try ... catch.
var Obj = function() {};
Obj.prototype.count = function(num) {
if (num < 0) throw new Error("Invalid Number");
else return 0;
}
function test(value, expected) {
results.total++;
var obj = new Obj();
try {
obj.count(value);
}
catch (err) {
if (err.message != expected) results.bad++;
}
}
And then:
test(-5, 'Invalid Number'); // doesn't add one to results.bad