spring - 在 Rest Controller 类中模拟 ResponseEntity
问题描述
我试图通过模拟服务返回 ResponseEntity 对象。下面是我的代码
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
LinkedHashMap<Object, Object> mockResponseObj = new LinkedHashMap<Object, Object>();
ArrayList<Object> list = new ArrayList<Object>();
LinkedHashMap<Object, Object> nestedObj = new LinkedHashMap<Object, Object>();
nestedObj.put("key1", "val1");
list.add(nestedObj);
mockResponseObj.put("data", list);
ResponseEntity<Object> responseEntity = new ResponseEntity<>(mockResponseObj, header, HttpStatus.OK);
Mockito.when(myService.getDataListByAccount(Mockito.any(MyRequestBody.class))).thenReturn(responseEntity);
我收到以下编译器错误
OngoingStubbing<ResponseEntity<capture#1-of ?>> 类型中的 thenReturn(ResponseEntity<capture#1-of ?>) 方法不适用于参数 (ResponseEntity)
在我的服务类里面
public ResponseEntity<?> getDataListByAccount(MyRequestBody obj) {
ResponseEntity<?> transactionHistoryResponse = null;
try {
historyResponse = restTemplate.postForEntity(url, obj, Object.class);
} catch(Exception e) {
LOGGER.error(e.getLocalizedMessage());
return new ResponseEntity<>(new MyCustomException(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR, "Internal Error Occurred"), HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(historyResponse.getBody(), HttpStatus.OK);
}
解决方案
推荐阅读
- terraform - Terraform template_provider 数据源输出的正确方法
- python - AttributeError:“Ui_MainWindow”对象没有属性“btn_click”
- scala - {} 块如何表示 scala 中的函数?
- json - 使用 React-Native 从 JSON 中提取数据
- php - 使用带有 Twig 和表单扩展的独立 Symfony4 表单组件
- angular - 如果我在动画的完成事件中更改状态名称,则状态不适用
- ruby-on-rails - Rails 5.1 和地理编码器:SSL_connect 返回=1 errno=0 状态=错误:证书验证失败
- c# - 重复使用内存中的数据,而不是执行新的 sql 查询
- swift - AVFoundation 会话问题
- python - 动态数组的 Python 实现的内存大小不会增加