gpt4 book ai didi

java - 模拟请求实体调用以进行单元测试

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:45 25 4
gpt4 key购买 nike

我想模拟请求实体和响应以测试 Controller 方法上的方法,此代码是由另一位开发人员编写的,我应该使用mockito来测试它。我正在模拟 Controller 类

我正在尝试模拟请求实体值和响应实体值,但它不起作用,并且在尝试调试时遇到反射错误

    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);

}

最佳答案

这是因为在执行 REST 调用时,未通过 Spring IOC 注入(inject) RestTemplate 实例。您需要在应用程序启动期间(即组件扫描期间)扫描的组件类中声明 getRestTemplate 方法。从而使 restTemplate 可用于 autowire

关于java - 模拟请求实体调用以进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55332139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com