相关代码如下:服务代码:@Overridepublic ResponseEntity<AppointmentResponse> createAppointment(AppointmentRequest partnerFulfillmentRequest) { RestTemplate rt = null; ResponseEntity<AppointmentResponse> response = null; String uri = null; HttpEntity<AppointmentRequest> httpEntity = null; HttpHeaders headers = null; try { rt = new RestTemplate(); rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); rt.getMessageConverters().add(new StringHttpMessageConverter()); uri = new String(internalServiceUrl+"/"+APP_NAME_INTERNAL+"/appointment"); log.info("Calling internal service URL : "+uri); headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); httpEntity = new HttpEntity<AppointmentRequest>(partnerFulfillmentRequest, headers); response = rt.exchange(uri, HttpMethod.PUT, httpEntity, AppointmentResponse.class); if (response != null) { log.info("Got response from internal servicec-->statusCode: "+response.getStatusCodeValue()); log.info("Got response from internal service--> Body "+response.getBody()); } }catch(HttpClientErrorException hceEx) { //hceEx.printStackTrace(); AppointmentResponse res = new AppointmentResponse(); return new ResponseEntity<AppointmentResponse>(mapResponse(hceEx.getResponseBodyAsString()), hceEx.getResponseHeaders(), hceEx.getStatusCode()); }我得到 java.lang.AssertionError: Expected :500 Actual :200 并且可以理解,因为它实际上并没有调用运行.thenReturn(responseEntity);逻辑。我的百万美元问题是,为什么?它应该返回 responseEntity 值。我有 exchange() 到 any() 的所有参数,希望尽可能频繁地触发条件,因为我总是可以在不同的时间缩小条件。我没有正确地嘲笑我的 restTemplate 吗?这是我目前对发生的事情的怀疑。任何建议都会有所帮助!
1 回答
芜湖不芜
TA贡献1796条经验 获得超7个赞
您正在RestTemplate测试方法内部创建一个新实例。这意味着该exchange方法将从新实例调用,而不是模拟。如果包含该方法的类createAppointment具有RestTemplate.
你想要的是模拟新实例的构造函数RestTemplate,以便在创建新实例时将其替换。不幸的是,Mockito 无法模拟构造函数,因此您应该使用PowerMockito来模拟构造函数。
whenNew(RestTemplate.class).withNoArguments().thenReturn(restTemplate);
responseEntity = new ResponseEntity<>(
"some response body",
HttpStatus.OK
);
when(restTemplate.exchange(Mockito.anyString(),
Mockito.<HttpMethod> any(),
Mockito.<HttpEntity<?>> any(),
Mockito.<Class<Object>> any()))
.thenReturn(responseEntity);
添加回答
举报
0/150
提交
取消