Ganymed
Ganymed

Reputation: 89

Mockito anyListOf() List<List<String>>

I'm using mockito-core:2.8.47 and Java 7 and want to use in a when and verify anyListOf or some other any method. My Problem is, if I just use anyList it says:

The method name( int, List < List < String > >) in the type Y is not
applicable for the arguments ( int, List < Object > )

How can I fix this?

ArgumentMatchers.anyListOf(ArgumentMatchers.anyListOf( String.class ) ) doesn't work...

Upvotes: 4

Views: 24269

Answers (2)

Philzen
Philzen

Reputation: 4647

There are two approaches to this:

  1. simply casting on any() acts as a sufficient type hint:
Mockito.doReturn("1")
    .when(classMock)
    .name(eq(1), (List<List<String>>) any());
  1. providing additional generics information to anyList().
    This is basically the same approach as below answer, only a little more concise as the alias Mockito is used, which maps to the ArgumentMatcher implementation.
Mockito.doReturn("1")
    .when(classMock)
    .name(eq(1), Mockito.<List<String>> anyList());

There are subtle but notable differences between the two. Imagine name() had the following two overloads:

// Overload A (target of this test)
String name(int id, Object entities) {...}

// Overload B (not targeted in this test)
String name(int id, List<CustomMapImpl> entities) {...}

When the second argument becomes null in the code under test, approach 1. will also properly match overload A, while approach 2. will resolve to overload B. In order match that specific case with generics it would need to be explicitly defined using a different ArgumentMatcher:

Mockito.doReturn(null)
    .when(classMock)
    .name(eq(1), Mockito.<List<List<String>>>isNull());

Upvotes: 0

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

In my opinion you can get away with just the basic anyList() method with additional generics information:

Mockito.doReturn("1").when(classMock).name(ArgumentMatchers.eq(1)
                , ArgumentMatchers.<List<String>>anyList());

This worked for me and also remember to add the ArgumentMatcher for the first int variable otherwise Mockito will fail.

Upvotes: 9

Related Questions