【发布时间】:2014-02-03 17:31:25
【问题描述】:
假设我有函数foo():
var foo = function(string) {
return string.replace(/a/g, '');
};
我对其进行了以下测试:
-
foo()存在; -
foo()从字符串中剥离a's 并且没有a's 对字符串不做任何事情; -
foo()抛出TypeError如果给出的不是字符串;
问题在于测试#3——但它从一开始就是绿色的,这不是我的优点。我希望能写出这样的东西:
var foo = function(string) {
if (typeof string !== 'string') {
throw new TypeError('argument should be a string');
}
return string.replace(/a/g, '');
};
但我不能,因为没有测试。所以foo()确实会抛出TypeError,但不是因为参数类型错误,而是因为作为参数给出的null、undefined、number、array、boolean、regexp等对象不提供replace()方法。
我认为我需要这个测试,只是因为 JS 团队可能会针对这种特殊情况将 TypeError 更改为 MissingMethodError 之类的东西,但我会违反 Red > Green > Refactor 原则。我应该如何解决这种情况?
【问题讨论】:
-
if(string && !string.replace){ throw "no replace on arg"; }
-
@dandavis,这不是关于“如何实施此检查”,而是“如果在实施检查之前检查是否为绿色,该怎么办”。
-
除此之外,传入
5(比如说)会过去。
标签: javascript unit-testing testing tdd methodology