Why isnt my mocking not working for responseEntity exchange? - spring

In groovy I'm trying to use the following to mock a return of a request but I keep getting a null pointer exception whenever my code calls:
ResponseEntity<AnimalVO> result = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headerUtil.headers()), AnimalVO.class);
In Test:
when(restTemplate.exchange(anyString(), any(HttpMethod.class, any(HttpEntity.class, any(ValueObject.class) as Class)).thenReturn(responseEntityMocked)
I'm using mockito 3.12
My test just fails with a null pointer exception and my restTemplate exchange (upon debugging) returns a null value.
Am I doing something wrong?
If it helps the rest Temple exchange has the following definition:
exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity.

Try the following:
when(restTemplate.exchange(anyString(), any(HttpMethod.class),
any(HttpEntity.class), eq(AnimalVO.class)).thenReturn(responseEntityMocked)

Related

mocking resttemplate exchange method returning null

I am trying to write the Junit test case for exchange method but it its returning null, can anybody tell me what is mistake I am doing here
My Actual Code is
HttpEntity httpEntity = cviBillingReportDateUtility.getHttpClient();
ResponseEntity<List<PersonDTO>> response = restTemplate.exchange(
personApiURI,
HttpMethod.GET,
httpEntity,
new ParameterizedTypeReference<List<PersonDTO>>() {
}
);
My Junit test code is like
when(restTemplate.exchange(any(String.class),
eq(HttpMethod.GET),
any(HttpEntity.class),
eq(new ParameterizedTypeReference<List<PersonDTO>>(){})
)).thenReturn(new ResponseEntity<List<PersonDTO>>(personList,HttpStatus.OK));
PowerMockito.when(restTemplate.exchange(ArgumentMatchers.anyString(), ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<ParameterizedTypeReference<List<cCustomerGroup>>>any()))
.thenReturn(responseEntity);
#You have to also mock endpoint url like below,
#Value("${url.customergroup}")
private String getCustomerGroups;
#Before
public void initialize() {
ReflectionTestUtils.setField(customerGroupService, "getCustomerGroups",
"http://localhost:8080/services/rest/customergroups");
}

RestTemplate - handle potential NullPointerException when response body is null

I'm writing client that calls some backend REST service. I'm sending Product object which will be saved in DB and returned in response body with generated productId.
public Long createProduct(Product product) {
RestTemplate restTemplate = new RestTemplate();
final String url = " ... ";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Product> productEntity = new HttpEntity<>(product, headers);
try {
ResponseEntity<Product> responseEntity = restTemplate.postForEntity(url, productEntity, Product.class);
Product product = responseEntity.getBody();
return product.getProductId();
} catch (HttpStatusCodeException e) {
logger.error("Create product failed: ", e);
throw new CustomException(e.getResponseBodyAsString(), e, e.getStatusCode().value());
}
This product.getProductId() looks like potential NullPointerException if product i.e. responseEntity.getBody() is null, should I handle it somehow?
I have looked examples over internet of using RestTemplate postFprEntity, getForEntity ... but didn't find any example that handle NPE. I suppose that if body of response cannot be set, it will be some exception thrown and status code 5xx.
Is it possible when response status code is 200, that body can be null?
Is it possible when response status code is 200, that body can be
null?
Yes, it is quite possible and totally depends on the server. Normally, some REST APIs and Spring REST Repositories will return 404 if resource is not found but better safe than sorry.
This product.getProductId() looks like potential NullPointerException
if product i.e. responseEntity.getBody() is null, should I handle it
somehow?
Of course you should.
You can check if responseEntity.hasBody() && responseEntity.getBody() != null. And from there either throw an Exception of your own or handle however you see fit.

Could not write request: no suitable HttpMessageConverter found for request type

I have used to RestTemplate class to call a rest service, I am getting the below exception.
org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [UmlerUpdateRequest]
The below is my code snippet that I have tried:
RestTemplate restTemplate = new RestTemplate();
UmlerUpdateRequest obj= new UmlerUpdateRequest();
obj.setTrnspEqpId(equipId);
obj.setLstMaintId(lesseeScac);
obj.setRecLseScac(userId);
obj.setTareWgt(tareWeight);
obj.setBldD(builtDate);
String returns = restTemplate.postForObject(url, obj, String.class);
Can anyone help me on this?

Get value from response body in RestClient

I am using Rest client of Firefox. I want to get value from response that is showing on Response body(Raw) in Rest-Client. I want to get this value in SpringBoot. Is it possible? If yes then How?
I have tried too many times but didn't get Satisfactory solution.
Using a Spring RestTemplate to make the calls will return a ResponseEntity. The simplest way to get the raw response would be this:
RestTemplate restTemplate = new RestTemplate();
try{
ResponseEntity<String> response = restTemplate.getForEntity(URI.create("http://example.org"),String.class);
System.out.println(response.getBody());
} catch (RestClientResponseException exception){
System.out.println(String.format("Error code %d : %s",e.getStatusCode().value(),e.getResponseBodyAsString()));
HttpHeaders errorHeaders = e.getResponseHeaders();
}
The ResponseEntity class will allow you to access the headers as well.
For more information on RestTemplate you can look at the docs here.

perform a get request with spring rest template and check returned status code is ok

Its just submitting the sitemap to google so far i have
RestTemplate restTemplate = new RestTemplate();
HttpEntity<?> responseEntity = restTemplate.getForEntity("http://www.google.com/webmasters/tools/ping?sitemap={url}", String.class,"http://mySite.com/sitemap.txt);
How do I check the server HTTP status that is returned?
restTemplate.getForEntity(String, Class<T>, String...) returns a ResponseEntity<T> (extends HttpEntity), which has a method for retrieving the status code.
ResponseEntity.getStatusCode()
You should utilize that instead of HttpEntity.
You need to execute request and check response status.
Example code:
//when
ResponseEntity<Void> response = restTemplate.exchange(uri, HttpMethod.GET, HttpEntity.EMPTY, Void.class);
//then
assertEquals(HttpStatus.OK, response.getStatusCode());

Resources