简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM