[英]How to test exception scenario in junit 5 in spring boot?
我有一個 void 方法,它執行一些嘗試測試異常場景的任務,但測試用例失敗了。
public void completetask(){
try{
RemoteUser rm = usrRepo.findById(12);
assistenRepo.save(rm);
}catch(Exception e){
log.error("Exception occurred while making changes {}", e,getMessage());
}
}
我們如何在 JUnit 5 上測試這里的異常場景?
我已經試過了,但沒用
@Test
public void completetaskTest(){
RemoteUser rm = getDummyRemoteUsr();
Mockito.when(usrRepo.findById(12)).thenReturn(rm);
Mockito.when(assistenRepo.save(rm)).thenThrow(new Exception("Error Abnormal"));
Exception exception = Assestions.assertThrow(Exception.class, () -> usrService.completetask());
String expectedMessage = "Exception occurred while making changes";
String actualMessage = exception.getMessage();
Assertions.assetTrue(actualMessage.contains(expectedMessage));
}
我收到此測試用例的錯誤 - 檢查異常對此方法無效無效 java.lang.Exception:錯誤
我能知道我在這里做錯了什么嗎?
您期望您的方法拋出異常,但在您的代碼中,您正在處理和記錄異常並且沒有拋出異常:
public void completetask(){
try {
RemoteUser rm = usrRepo.findById(12);
assistenRepo.save(rm); // <-- Exception is thrown...
} catch(Exception e){ // <-- Catched here
log.error("Exception occurred while making changes {}", e,getMessage());
}
// <-- Method finishes normally.
}
您應該在 output 中看到以下內容:
Exception occurred while making changes Error Abnormal
但是您的測試將在這里失敗:
Exception exception = Assestions.assertThrow(Exception.class, () -> usrService.completetask());
因為從未拋出異常。 如果您注釋掉異常處理try / catch
它將通過該點,但現在它將無法比較錯誤消息。
編輯:
我知道這種情況,但這里的問題是如何解決這個問題? 我們如何為這種情況編寫測試場景 -
如果你想驗證你的異常是否被處理,只需刪除驗證:
@Test
public void completetaskTest(){
RemoteUser rm = getDummyRemoteUsr();
when(usrRepo.findById(12)).thenReturn(rm);
when(assistenRepo.save(rm)).thenThrow(new Exception("Error Abnormal"));
assertTrue(true); // if we reached this line, in means the error has handled.
}
如果你真的想進一步 go 並檢查消息是否匹配(這可能有點矯枉過正)你可以檢查記錄器,但同樣,我不會推薦它。
像這樣:
@Auto
Logger log;
...
@Test
public void completetaskTest(){
RemoteUser rm = getDummyRemoteUsr();
when(usrRepo.findById(12)).thenReturn(rm);
when(assistenRepo.save(rm)).thenThrow(new Exception("Error Abnormal"));
// Verify the `log.error` was invoked with exactly those parameters
verify(log, times(1)).error("Exception occurred while making changes {}", "Error Abnormal");
}
這意味着異常被拋出、被緩存並且記錄器被調用。
您不是在拋出錯誤,您只是在用一個日志行編寫日志。
catch(Exception e){
log.error("Exception occurred while making changes {}", e,getMessage());
}
這是Assertions.assertThrows
上的 javadoc:
斷言提供的可執行文件的執行會拋出 expectedType 的異常並返回異常。 如果沒有拋出異常,或者拋出不同類型的異常,則此方法將失敗。 如果您不想對異常實例執行額外的檢查,請忽略返回值。
這就是為什么您的assertThrows
方法在任何情況下都會失敗。
因此,要么在你要測試的方法中拋出一個錯誤,要么檢查異常中的日志打印以進行測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.