Ello all,所以我一直在尝试编写期望某种异常类型的单元测试。我有一个引发该异常的函数,但是我仍然无法通过测试。为了进行故障排除,我已经尝试了抛出相同的异常而仍然失败。我可以通过比较消息来使其通过,但这似乎是一个可怕的主意。
我应该如何处理匹配的自定义异常的测试?
export class EventEntity {
comments : Array<string> = new Array<string>();
constructor() {}
public addComment(comment : string) {
this.comments.push(comment);
}
public getCommentCount() : number {
return this.comments.length;
}
public getCommentByOrder(commentNumber : number) : string {
console.log(`getCommentByOrder with arg:${commentNumber}`);
let offset = 1;
try {
let result = this.comments[commentNumber - offset];
return result;
} catch (err){
console.log(`getCommentByOrder:Error: ${err.toString()}`);
console.log(`err: with arg:${commentNumber}`);
if(err instanceof RangeError){
throw new CommentNotFoundException();
}
throw err;
}
}
}
export class CommentNotFoundException extends Error {
constructor(m?:string)
{
let message : string = m?m:"Comment number not found in event's comments.";
super(message);
Object.setPrototypeOf(this, CommentNotFoundException.prototype);
}
}
@test shouldThrowIfCommentNumberIsGreaterThanTotalNumberOfComments() {
let testEvent = new EventEntity();
let expectedException = new CommentNotFoundException();
//expect(testEvent.getCommentByOrder(5)).to.throw(expectedException);
expect(()=> {
throw new CommentNotFoundException();
}).to.throw(new CommentNotFoundException());
}
好的,我修改了。这按预期工作。没有以以下形式获取异常:
expect(testEvent.getCommentByOrder(5)).to.throw(CommentNotFoundException);
但是这样做:
expect(()=>{
testEvent.getCommentByOrder(5);
}).to.throw(CommentNotFoundException);
这是带有更新代码的清单:
public getCommentByOrder(commentNumber : number) : string {
let offset = 1;
let result = this.comments[commentNumber - offset];
if (!result) {
throw new CommentNotFoundException();
} else {
return result;
}
}
@test shouldThrowIfCommentNumberIsGreaterThanTotalNumberOfComments() {
let testEvent = new EventEntity();
expect(()=>{
testEvent.getCommentByOrder(5);
}).to.throw(CommentNotFoundException);
}
胜利,谢谢!
您正在将错误实例传递给.throw(...)
方法。您需要改为传递一个构造函数。并且传递给您的expect
必须是expect
将要调用的函数。您注释掉的行应编辑为:
expect(() => testEvent.getCommentByOrder(5)).to.throw(CommentNotFoundException);
您可以将实例传递给该方法,但是只有当被测试函数引发的实例以及为.throw(...)
满足与之比较而传递的实例时,断言才会通过===
。换句话说,这两个值必须是完全相同的JS对象。在测试实际代码(而不是琐碎的示例)时,几乎绝不会在出现错误之前获取错误实例,因此传递实例通常是您无法做到的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句