0
Ello all,所以我一直在試圖編寫一個單元測試,預計某種類型的異常。我有一個拋出該異常的函數,但是我仍然遇到了一個失敗的測試。爲了排除故障,我儘可能拋出相同的異常並仍然失敗。我可以通過比較消息來通過,但這似乎是一個可怕的想法。柴期望拋出異常不匹配使用Typescript相同的異常
我該如何處理匹配自定義異常的測試?
類代碼
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;
}
}
}
MyException
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);
}
這是一個勝利,謝謝!
這不是確切的解決方案,但完全讓我走上了正確的道路。謝謝!!! – Terrance
您可能在[上次編輯](https://stackoverflow.com/revisions/46018605/2)之前閱讀我的答案。不幸的是,SO崩潰了編輯接連完成,但我最後的編輯是改變傳遞給'expect'的參數,使其成爲一個函數。我最初鎖定在構造函數和實例問題上,錯過了。 – Louis