mercredi 2 mars 2016

Mockito and RestTemplate with generic types

I am trying to unit test the following Spring boot code with RestTemplate sending a request to the API and retrieving some resources from it:

final URI targetUri = UriComponentsBuilder.fromUriString(baseUri)
                .path("/myEntities").build().toUri();

final RequestEntity<Void> request = RequestEntity.get(targetUri).accept(HAL_JSON).build();
final Resources<MyEntity> resourceAccounts = restTemplate.exchange(request, new ResourcesType<MyEntity>() {
        }).getBody();

In the unit test, I am mocking this request-response using Mockito:

final Resources<MyEntity> myEntities = new Resources<>(myEntityList, links);
final ResponseEntity<Object> response = new ResponseEntity<Object>(myEntities, HttpStatus.OK);

when(restTemplate.exchange(any(RequestEntity.class), any(ResourcesType.class))).thenReturn(response);

It works fine but I am getting Unchecked invocation exchanged because I am not using the generics correctly.

I just wonder what is the correct and bullet-proof way of doing this? I tried casting the ResponseEntity type to MyEntity but this does causes compile exception (the constructor ResponseEntity<MyEntity> is undefined).

Aucun commentaire:

Enregistrer un commentaire