【问题标题】:How do I use mockito to throw HttpClientErrorException.Unauthorized error如何使用 mockito 抛出 HttpClientErrorException.Unauthorized 错误
【发布时间】:2020-05-22 00:18:00
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: java spring-boot unit-testing exception mockito


    【解决方案1】:

    HttpClientErrorException.UnauthorizedHttpStatusCodeException 的子异常

    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);
    }
    

    【讨论】:

    • 这是否意味着我需要做的就是在我的实现级别捕获父类,即HttpClientErrorException??
    • 是的,你可以从HttpClientErrorException获取状态码并验证状态码@shadow
    猜你喜欢
    • 1970-01-01
    • 2023-02-07
    • 2018-07-02
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2014-04-06
    相关资源
    最近更新 更多