簡體   English   中英

使用 Mockito Junit 測試異常類型

[英]Test Exception type using Mockito Junit

Hi all I am completely new to spring-boot and Junit Mockito I am trying to check if my method is throwing a correct exception Below is the method from my service class

    public Optional<User> getUserByEmail(String emailaddress) {
    System.out.println("From DB");
    Optional<User> user = userDao.findByEmailAddress(emailaddress);
    user.orElseThrow(() -> new BadRequestException("User Not Found"));
    return user;
}

以下是我的測試方法

    @Test
@DisplayName("TextCase to check if We are able to get Correct User")
public void getUserByEmailExceptionTest() {
    Mockito.when(userDao.findByEmailAddress("mokal006@gmail.com"))
    .thenThrow(UserNotFoundException.class);
     assertThrows(UserNotFoundException.class, () -> {
        LibraryUserDetailsService.getUserByEmail("mokal006@gmail.com");
    });
    
    
}

現在,即使我在實際方法中拋出了錯誤的異常,這個測試也通過了。

要了解為什么您的測試用例會因錯誤的異常類型而通過,請檢查assertThrows在內部是如何工作的。 AssertThrows.java

try {
    // execute lambda expression passed in assertThrows
} catch (Throwable var5) {
    if (expectedType.isInstance(var5)) {
        // if type matches returns the exception back
        return var5; 
    }
    // ..
    // Else throws different exception
    throw new AssertionFailedError(message, var5);
}

JUnit 5 檢查異常類型調用Class.isIntance(..) , Class.isInstance(..)將返回 true 即使拋出的異常是父類型。 在您的情況下,拋出的異常很可能是父類型。

您可以通過斷言Class來修復它。

Throwable throwable =  assertThrows(Throwable.class, () -> {
    LibraryUserDetailsService.getUserByEmail("mokal006@gmail.com");
});
assertEquals(UserNotFoundException.class, throwable.getClass());

或使用此處的解決方案JUnit 5:如何斷言拋出異常?

[編輯]

正如johanneslink在評論中指出的那樣, user.orElseThrow將永遠不會被執行。 userDao.findByEmailAddress(...)將拋出UserNotFoundException因為沒有catch塊異常將傳播回調用者,因此不會拋出BadRequestException並且測試用例將始終通過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM