Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct usage of ParameterizedTypeReference

In a test I wish to hit an endpoint which returns a list of a type. Currently I have

@Test
public void when_endpoint_is_hit_then_return_list(){
   //Given
   ParameterizedTypeReference<List<Example>> responseType = new ParameterizedTypeReference<List<Example>>() {};

   String targetUrl = "/path/to/hit/" + expectedExample.getParameterOfList();

   //When

   //This works however highlights an unchecked assignment of List to List<Example>
   List<Example> actualExample = restTemplate.getForObject(targetUrl, List.class);

   //This does not work
   List<Example> actualExample = restTemplate.getForObject(targetUrl, responseType);

   //This does not work either
   List<Example> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});

   //Then
   //Assert Results
}

The problem for getForObject method is the ParameterizedTypeReference makes the getForObject method not resolve, as the types do not match up.

The problem for the exchange method is incompatible types. Required List but 'exchange' was inferred to ResponseEntity: no instance(s) of type variable(s) exist so that ResponseEntity conforms to List

How could I use the ParameterizedTypeReference correctly in this situation to safely return the List type I want?

like image 324
shirafuno Avatar asked Aug 17 '18 13:08

shirafuno


People also ask

What is the use of ParameterizedTypeReference?

Class ParameterizedTypeReference<T> The purpose of this class is to enable capturing and passing a generic Type .

How do you use RestTemplate getForObject?

Spring RestTemplate – HTTP GET Example getForObject(url, classType) – retrieve a representation by doing a GET on the URL. The response (if any) is unmarshalled to given class type and returned. getForEntity(url, responseType) – retrieve a representation as ResponseEntity by doing a GET on the URL.


1 Answers

From the documentation:

Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity. The given ParameterizedTypeReference is used to pass generic type information:

ParameterizedTypeReference<List<MyBean>> myBean =
   new ParameterizedTypeReference<List<MyBean>>() {};

ResponseEntity<List<MyBean>> response =
   template.exchange("http://example.com",HttpMethod.GET, null, myBean);

So in your case you can:

ResponseEntity<List<Example>> actualExample = restTemplate.exchange(targetUrl, HttpMethod.GET, null, new ParameterizedTypeReference<List<Example>>() {});
List<Example> exampleList = actualExample.getBody();
like image 171
Javad Alimohammadi Avatar answered Sep 23 '22 04:09

Javad Alimohammadi