1
 ResponseEntity<List<AgreementRecord>> myEntity = new 
 ResponseEntity<List<AgreementRecord>>(HttpStatus.ACCEPTED);

    when(restTemplate.exchange(
             ArgumentMatchers.anyString(),
             ArgumentMatchers.any(HttpMethod.class),
             ArgumentMatchers.<HttpEntity<?>>any(),
             ArgumentMatchers.<Class<?>>any())).thenReturn(myEntity);

The rest template returns a list from the application Eclipse throws a compilation error

The method thenReturn(ResponseEntity) in the type OngoingStubbing> is not applicable for the arguments (ResponseEntity>)

Rest template

      ResponseEntity<List<AgreementRecord>> responseEntity = 
      restTemplate.exchange(smoUrl+ GET_AGREEMENT_RECORDS + customerId 
      ,HttpMethod.GET,null,new 
      ParameterizedTypeReference<List<AgreementRecord>>() {
       });
      responseEntity.getBody();
  • Perhaps you should consider using Spring's MockRestServiceServer instead of mocking the RestTemplate. Have a look at the java docs here: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/web/client/MockRestServiceServer.html – Sarah Micallef Jul 10 '18 at 12:10

1 Answers1

0

One thing you can do is to side-step Mockito's compile-time type checking with doReturn().

doReturn(myEntity)
    .when(restTemplate)
    .exchange(
        ArgumentMatchers.anyString(),
        ArgumentMatchers.any(HttpMethod.class)
        ArgumentMatchers.<HttpEntity<?>>any(),
        ArgumentMatchers.<Class<?>>any()));

This will return myEntity without compile-time type check. if you've got the type wrong, you'll find out as soon as you run your test.

Edit:

@Test()
public void test() {
    class AgreementRecord {}

    ResponseEntity<List<AgreementRecord>> myEntity = new ResponseEntity<>(
        Arrays.asList(new AgreementRecord()), HttpStatus.ACCEPTED);
    doReturn(myEntity)
        .when(restTemplate)
        .exchange(
            anyString(),
            any(HttpMethod.class),
            any(),
            any(ParameterizedTypeReference.class));

    ResponseEntity<List<AgreementRecord>> responseEntity = restTemplate.exchange(
            "url", HttpMethod.GET, null, new ParameterizedTypeReference<List<AgreementRecord>>() {});

    List<AgreementRecord> body = responseEntity.getBody();

    assertTrue(responseEntity.getStatusCode().is2xxSuccessful());
    assertNotNull(body);
}
Januson
  • 4,533
  • 34
  • 42