我正在使用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
的,并且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);
}