【发布时间】: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