我正在尝试使用mockito模拟HttpStatus方法
@Autowired
Handler handler;
@Mock
Request request;
@Mock
Response aAResponse;
@Mock
RestHandler restHandler
logger.info("Response's HttpStatus is2xxSuccessful is false");
try {
Mockito.when(restHandler.getResponse(request)).thenReturn(aAResponse);
Mockito.when(aAResponse.getHttpStatus()).thenReturn(HttpStatus.ACCEPTED);
Mockito.when(aAResponse.getHttpStatus().is2xxSuccessful()).thenReturn(false);
handler.fetchDetails(notification, provider, mapping);
} catch (Exception e) {
logger.error("Exception -> {}", e.getMessage());
}
但是
aAResponse.getHttpStatus()
给我 null。如何使用 Mockito 模拟枚举值及其方法。模拟枚举值及其方法是否正确?
final Response response = restHandler.getResponse(request);
我知道响应是最终的,mockito 无法模拟最终对象,但为此我遵循了答案 https://stackoverflow.com/a/53837478/4478171
最佳答案
当你可以模拟返回枚举的方法时,为什么还要模拟枚举?
替换
Mockito.when(aAResponse.getHttpStatus().is2xxSuccessful()).thenReturn(false);
与
Mockito.when(aAResponse.getHttpStatus()).thenReturn(HttpStatus.NOT_FOUND);
您不希望模拟枚举返回特定值。您希望响应具有包含不成功错误代码的状态...
关于java - 如何模拟 Java 内置枚举(如 HttpStatus 及其方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59945382/