首页 > 解决方案 > 在 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);
}

标签: springspring-bootunit-testingjunitjunit5

解决方案


推荐阅读