我正在使用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.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的,并且UNAUTHORIZED不会捕获任何400系列异常。您还可以从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);
}

09-28 10:17