JSS
JSS

Reputation: 2193

Java Mockito with RestTemplate.exchange using Generics

I have a generic method which invokes specified URL using RestTemplate.exchange. Method itself is working and loading data fine but I am not able to unit test it using Mockito.

Main Method

@Service
public class MyClass{
    private <T> List<T> loadData(String url) {
        return restTemplate.exchange(
            url, GET, null, new ParameterizedTypeReference<List<T>>(){}
        ).getBody().stream().collect(toList()));
    }
}

Unit Test

@Runwith(MockitoJUnitRunner.class)
public class MyTest {
    @Mock
    private RestTemplate restTemplate;

    @Test
    public void givenCall_myMethod_WillReturnData(){
        given(restTemplate.exchange(
            ArgumentMatchers.anyString(), ArgumentMatchers.any(), any(), any(Class.class)
        ))
        .willReturn(bodyData());
    }
}

If I use non-generic version then everything works fine, however mockito returns NullPointerException with generics version.

What's wrong or missing?

Upvotes: 1

Views: 2156

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

The last wildcard you have defined as: any(Class.class).

The exchange method has signature:

exchange(String url,
             HttpMethod method,
             HttpEntity<?> requestEntity,
             ParameterizedTypeReference<T> responseType) throws RestClientException

You should define it as: any(ParameterizedTypeReference.class)

Also I would suggest replacing the very vague any() set-us with a any(Class) equivalents.

Upvotes: 3

Related Questions