Модульный тест JAVA Mockito для resttemplate и retryTemplate ⇐ JAVA

Программисты JAVA общаются здесь
Anonymous
Модульный тест JAVA Mockito для resttemplate и retryTemplate

Сообщение Anonymous »

В настоящее время я пишу модульный тест для метода ниже

Код: Выделить всё

@Autowired
private RequestConfig requestConfig;

@Autowired
private RetryTemplate retryTemplate;

public ResponseEntity makeGetServiceCall(String serviceUrl) throws Exception {
try {
return retryTemplate.execute(retryContext -> {

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = requestConfig.createHttpHeaders();
HttpEntity entity = new HttpEntity("parameters", headers);
ResponseEntity response = restTemplate.exchange(serviceUrl, HttpMethod.GET, entity, String.class);
return response;

});
} catch (Exception e) {
throw new Exception("Generic exception while makeGetServiceCall due to" + e + serviceUrl);
}
}
ОБНОВЛЕННЫЙ МЕТОД:

Код: Выделить всё

@Autowired
private RequestConfig requestConfig;

@Autowired
private RetryTemplate retryTemplate;

@Autowired
private RestTemplate restTemplate;

public ResponseEntity makeGetServiceCall(String serviceUrl) throws Exception {
try {
return retryTemplate.execute(retryContext -> {

HttpHeaders headers = requestConfig.createHttpHeaders();
HttpEntity entity = new HttpEntity("parameters", headers);
ResponseEntity response = restTemplate.exchange(serviceUrl, HttpMethod.GET, entity, String.class);
return response;

});
} catch (Exception e) {
throw new Exception("Generic exception while makeGetServiceCall due to" + e + serviceUrl);
}
}
Я перепробовал все возможности, но не смог сделать все правильно. Вот мой тест ниже.

Код: Выделить всё

@Mock
private RestTemplate restTemplate;

@Mock
public RequestConfig requestConfig;

@InjectMocks
private RetryTemplate retryTemplate;

ServiceRequest serviceRequest;

@Test
public void makeGetServiceCall() throws Exception {
String url = "http://localhost:8080";
RetryTemplate mockRetryTemplate = Mockito.mock(RetryTemplate.class);
RestTemplate mockRestTemplate = Mockito.mock(RestTemplate.class);
ResponseEntity myEntity = new ResponseEntity(HttpStatus.ACCEPTED);
Mockito.when(mockRetryTemplate.execute(ArgumentMatchers.any(RetryCallback.class), ArgumentMatchers.any(RecoveryCallback.class), ArgumentMatchers.any(RetryState.class))).thenReturn(myEntity);

Mockito.when(mockRestTemplate.exchange(
ArgumentMatchers.eq(url),
ArgumentMatchers.eq(HttpMethod.GET),
ArgumentMatchers.any(),
ArgumentMatchers.any())
).thenReturn(myEntity);

ResponseEntity response = serviceRequest.makeGetServiceCall(url);
Assert.assertEquals(myEntity, response);
}
ОБНОВЛЕННЫЙ ТЕСТОВЫЙ ПРИМЕР:

Код: Выделить всё

 @Mock
public RequestConfig requestConfig;

@Mock
private RestTemplate restTemplate;

@Mock
private RetryTemplate retryTemplate;

@InjectMocks
ServiceRequest serviceRequest;

@Test
public void makeGetServiceCall() throws Exception {
//given:
String url = "http://localhost:8080";

when(requestConfig.createHttpHeaders()).thenReturn(null);
ResponseEntity myEntity = new ResponseEntity( HttpStatus.ACCEPTED);
when(retryTemplate.execute(any(RetryCallback.class), any(RecoveryCallback.class), any(RetryState.class))).thenAnswer(invocation -> {
RetryCallback retry = invocation.getArgument(0);
return retry.doWithRetry(/*here goes RetryContext but it's ignored in ServiceRequest*/null);
});
when(restTemplate.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), eq(String.class)))
.thenReturn(myEntity);

//when:
ResponseEntity response = serviceRequest.makeGetServiceCall(url);

//then:
assertEquals(myEntity, response);
}
Объект ответа, который я получаю от вызова метода makeGetServiceCall, всегда возвращает значение null. Когда я отлаживаю код, я вижу исключение org.mockito.Exceptions.misusing.WrongTypeOfReturnValue: ResponseEntity не может быть возвращено с помощью toString() toString() должен возвращать ошибку String в resttemplate, где я возвращаю myEntity< /code>

Я не уверен, что мне не хватает.

Подробнее здесь: https://stackoverflow.com/questions/549 ... rytemplate

Вернуться в «JAVA»