I am not able to mock varargs on an overloaded constructor in Mockito. This is the method I want to test
@Override
public List<User> fetchDataFromExternalService() {
return Arrays.asList(this.restTemplate.getForObject(URL, User[].class));
}
User
is a POJO class that has attributes, getters and setters. RestTemplate instance is Spring's Rest Template..
This function is an overloaded function and has the the following methods
1) public <T> T getForObject(java.lang.String url,
java.lang.Class<T> responseType,
java.lang.Object... uriVariables)
throws RestClientException
2) public <T> T getForObject(java.lang.String url,
java.lang.Class<T> responseType,
java.util.Map<java.lang.String,?> uriVariables)
throws RestClientException
I am trying to mock the first function to return an array of users, but not matter what I try, it always returns null
. I don't know what I am doing wrong.
My mocking function.
User user = new User();
Mockito.when(this.restTemplate.getForObject(
Mockito.anyString(), Mockito.eq(User[].class), (Object[]) Mockito.any())).thenReturn(new User[] {user});
I tried using a custom argument matcher as follows,
Mockito.when(this.restTemplate.getForObject(
Mockito.anyString(), Mockito.eq(User[].class),
Mockito.argThat(new MyVarargMatcher()))).thenReturn(new User[] {user});
but it still returned null
for me.
class MyVarargMatcher implements ArgumentMatcher<Object[]>, VarargMatcher {
@Override
public boolean matches(Object[] argument) {
return true;
}
}
I tried using the approach in this post, but the method is deprecated.
How to properly match varargs in Mockito
https://static.javadoc.io/org.mockito/mockito-core/2.2.7/org/mockito/ArgumentMatchers.html#any()
Maven configuration
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.13.0</version>
<scope>test</scope>
</dependency>
How can I resolve this issue?