簡體   English   中英

如何使用 mockito 拋出 HttpClientErrorException.Unauthorized 錯誤

[英]How do I use mockito to throw HttpClientErrorException.Unauthorized error

我正在使用 mockito 來模擬我的authenticationService.getUserInfo方法。

我在嘗試模擬HttpClientErrorException.Unauthorized時遇到了困難。

我不能只是新的HttpClientErrorException.Unauthorized

有沒有其他辦法?

執行:

try {
    result = authenticationService.getUserInfo(accessToken);

} catch (HttpClientErrorException.Unauthorized e) {

    String errorMsg = "Invalid access token - " + e.getMessage();

    throw new InvalidAccessTokenException(errorMsg);
}

測試用例:

@Test
public void givenInvalidToken_whenGetUserInfoThrows401Response_thenThrowInvalidAccessTokenExceptionAndFail() throws ServletException, IOException {

    HttpClientErrorException ex = new HttpClientErrorException(HttpStatus.UNAUTHORIZED);

    exceptionRule.expect(InvalidAccessTokenException.class);
    exceptionRule.expectMessage("Invalid access token - " + ex.getMessage());

    Mockito.when(authenticationService.getUserInfo(anyString())).thenThrow(ex);

    filter.doFilterInternal(this.request, this.response, this.mockChain);
}

運行測試用例的錯誤日志:

java.lang.AssertionError: 
Expected: (an instance of com.demo.security.common.exception.InvalidAccessTokenException and exception with message a string containing "Invalid access token - 401 UNAUTHORIZED")
     but: an instance of com.demo.security.common.exception.InvalidAccessTokenException <org.springframework.web.client.HttpClientErrorException: 401 UNAUTHORIZED> is a org.springframework.web.client.HttpClientErrorException
Stacktrace was: org.springframework.web.client.HttpClientErrorException: 401 UNAUTHORIZED

HttpClientErrorException.Unauthorized是兒童除外HttpStatusCodeException

public static final class HttpClientErrorException.Unauthorized
extends HttpClientErrorException

因此,當您拋出HttpStatusCodeException ,catch 塊將不會執行,因為子異常不會捕獲父異常。

所以創建HttpClientErrorException.Unauthorized並拋出它

HttpClientErrorException http = HttpClientErrorException.Unauthorized.create(HttpStatus.UNAUTHORIZED, null, null, null, null);

我還建議捕獲HttpStatusCodeException因為UNAUTHORIZED特定於401並且任何 400 系列異常都不會被UNAUTHORIZED捕獲。 您還可以從HttpClientErrorException獲取狀態代碼並驗證它,如我的回答所示

try {

result = authenticationService.getUserInfo(accessToken);

} catch (HttpClientErrorException e) {

if(e.getStatusCode().equals(HttpStatus.UNAUTHORIZED))
  //do something

String errorMsg = "Invalid access token - " + e.getMessage();

throw new InvalidAccessTokenException(errorMsg);
}

暫無
暫無

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

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