【发布时间】:2019-03-25 06:13:25
【问题描述】:
我想模拟请求实体和响应以测试控制器方法上的方法,此代码已由另一个开发人员编写,我应该使用 mockito 对其进行测试。我正在模拟控制器类
我正在尝试模拟请求实体值和响应实体值,但它不起作用,并且在我尝试调试时遇到反射错误
public class InquiryController {
private static final Logger log =
LoggerFactory.getLogger(InquiryController.class);
@Autowired
private InquiryProperties inquiryProperties;
@Autowired
private InquiryService inquiryService;
@Autowired
RestTemplate restTemplate;
public static int count = 0;
@Bean
private RestTemplate getRestTemplate() {
return new RestTemplate();
}
@PostMapping(value = "/endCustomer", produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {
MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<List<EndCustomerDTO>> endCustomer(@RequestBody CustomerInfo customerInfo)
throws IOException, JSONException {
log.info("### InquiryController.endCustomer() ===>");
List<EndCustomerDTO> endCustomerDTOs = null;
try {
//RestTemplate restTemplate = new RestTemplate();
RequestEntity<CustomerInfo> body = RequestEntity.post(new URI(inquiryProperties.getEndCustomer()))
.accept(MediaType.APPLICATION_JSON).body(customerInfo);
ResponseEntity<List<EndCustomerDTO>> response = restTemplate.exchange(body,
new ParameterizedTypeReference<List<EndCustomerDTO>>() {
});
endCustomerDTOs = (response != null ? response.getBody() : new ArrayList<EndCustomerDTO>());
} catch (RestClientException | URISyntaxException e) {
log.error("InquiryController.endCustomer()" + e.getMessage());
}
log.info("### END InquiryController.endCustomer() ===>");
if (null == endCustomerDTOs) {
return new ResponseEntity<List<EndCustomerDTO>>(new ArrayList<EndCustomerDTO>(), HttpStatus.OK);
}
return new ResponseEntity<List<EndCustomerDTO>>(endCustomerDTOs, HttpStatus.OK);
}
【问题讨论】:
-
看起来您正在...尝试混合配置和控制器?用构造函数注入替换字段注入并使用
RestOperations接口而不是RestTemplate,您将能够轻松地模拟依赖关系。
标签: java rest junit mockito resttemplate