Mockito mock restTemplate 不使用返回的 mock 值



相关代码如下:

服务代码:

@Override
public 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());
    }catch(Exception e) {
        e.printStackTrace();
        AppointmentResponse res = new AppointmentResponse();
        ResponseEntity<AppointmentResponse> wfmErrResponse = new ResponseEntity<AppointmentResponse>(res, HttpStatus.INTERNAL_SERVER_ERROR);
        log.error("ERROR WHILE CALLING INTERNAL SERVICE");
        log.error(uri);
        log.error(e);
        return wfmErrResponse;
    }
    return response;
}

测试代码:

@RunWith(MockitoJUnitRunner.class)
public class PartnerFulfillmentServiceImplTest {
@Mock
RestTemplate restTemplate;
@Mock
HttpHeaders httpHeaders;
@Mock
ResponseEntity responseEntity;
@InjectMocks
PartnerFulfillmentServiceImpl partnerFulfillmentService;
@Test
public void createAppointmentTest() {
    Whitebox.setInternalState(partnerFulfillmentService, "internalServiceUrl", "http://localhost:8080");
    AppointmentRequest appointmentRequest = new AppointmentRequest();
    appointmentRequest.setPartnerName("CENTRICITY");
    appointmentRequest.setTicketNumber("123ABC");
    httpHeaders = new HttpHeaders();
    httpHeaders.set("Content-type", "application/json");
    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);
    ResponseEntity<AppointmentResponse> response = partnerFulfillmentService.createAppointment(appointmentRequest);
    Assert.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
}

我得到了java.lang.AssertionError:预期 :500实际 :200 这是可以理解的,因为它实际上并没有调用运行.thenReturn(responseEntity);逻辑。我的百万美元问题是,为什么?它应该返回响应实体值。我有 exchange(( 到 any(( 的所有参数,希望尽可能多地触发条件,因为我总是可以在不同的时间缩小条件。我嘲笑我的休息模板不正确吗?这是我目前对正在发生的事情的怀疑。任何建议都会有所帮助!

谢谢!

就像@JB Nizet指出的那样,您正在测试方法中创建RestTemplate的新实例。这意味着将从新实例调用 exchange 方法,而不是模拟实例。如果包含该方法的类具有RestTemplate的依赖项注入,则可以按照createAppointment的方式实现它。

你想要的是模拟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);

相关内容

  • 没有找到相关文章

最新更新