Unit testing 包装器方法可测试性的推荐访问修饰符
我在测试中开始做的一件事是将错误消息和字符串连接包装到方法或变量中,以便在错误消息内容以后更改时保持测试的健壮性 例如,我会重构如下内容:Unit testing 包装器方法可测试性的推荐访问修饰符,unit-testing,typescript,jasmine,Unit Testing,Typescript,Jasmine,我在测试中开始做的一件事是将错误消息和字符串连接包装到方法或变量中,以便在错误消息内容以后更改时保持测试的健壮性 例如,我会重构如下内容: try{ someMethod(); }catch(e){ throw new Error('error message.'); } 为此: let errorMessage = 'error message'; ... try{ someMethod(); }catch(e){ throw new Error(errorM
try{
someMethod();
}catch(e){
throw new Error('error message.');
}
为此:
let errorMessage = 'error message';
...
try{
someMethod();
}catch(e){
throw new Error(errorMessage);
}
或者类似的错误消息,如果错误消息包含变量或其他内容
我的问题是,在Typescript中,什么是最好的方法?在Java中,我希望它们受到包保护,但在这里,Jasmine似乎无法访问这样的方法,如果它们受到保护的话。我也试着让它们静止
有更好的方法吗?这是一个你可以从其他语言中转移一些好的实践的场合 如果创建自定义异常,则可以测试它们的类型,而不是字符串,还可以确保错误消息的一致性 这个例子看起来有点复杂,但它应该给你一个想法(改编自第163-168页Pro Typescript)
CustomException
类,该类实现了Error
接口,并将位于应用程序中所需的任何自定义错误类型之下InvalidDateException
来表示特定的错误类别,这是应用程序中需要存储错误消息字符串的唯一位置instanceof
检查类型的错误Error
接口兼容,该接口需要name
和toString()
这很有道理。非常感谢。相关问题:您是否会为字符串连接包装提供类似的方法,例如那些基于一个或多个参数组成url的包装?
class CustomException implements Error {
protected name = 'CustomException';
constructor(public message: string) {
}
toString() {
return this.name + ': ' + this.message;
}
}
class InvalidDateException extends CustomException {
constructor(public date: Date) {
super('The date supplied was not valid: ' + date.toISOString());
this.name = 'InvalidDateException';
}
}
try {
throw new InvalidDateException(new Date());
} catch (ex) {
if (ex instanceof InvalidDateException) {
alert(ex.toString());
}
}