Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 包装器方法可测试性的推荐访问修饰符_Unit Testing_Typescript_Jasmine - Fatal编程技术网

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
    来表示特定的错误类别,这是应用程序中需要存储错误消息字符串的唯一位置
  • 您现在可以查看特定类型的错误,如示例catch语句中使用
    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());
        }
    }