2

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).

Smajl
  • 7,555
  • 29
  • 108
  • 179

1 Answers1

1

With type safe method of Matchers ? One of the way to check method invocations with the generics.

Matchers.<ResponseType<MyEntity>>.any()

Source - Reference

To check the response of a method, ArgumentCaptor can be used.

Community
  • 1
  • 1
Vinay Veluri
  • 6,671
  • 5
  • 32
  • 56