Mocking varargs in an overloaded function

1,399 views
Skip to first unread message

Karthik Kumar

unread,
Feb 5, 2018, 12:49:07 AM2/5/18
to mockito

I am not able to mock varargs on an overloaded constructor in Mockito, and I hope that someone can help. 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 assume the following forms

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 call the first one. 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, and any assistance is appreciated

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, 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?

Christian Schwarz

unread,
Jun 26, 2018, 8:28:26 AM6/26/18
to mockito
Have you tried this?


when(restTemplate.getForObject(anyString(), eq(User[].class)).thenReturn(new User[] {user});





Reply all
Reply to author
Forward
0 new messages