0

I don't understand why this code with Java generics fails to compile. Given this class:

public static class X {
    public List<? extends X> getList() {
        return null;
    }
}

there's no way to mock the getList return value:

X x = mock(X.class);
// Error: Cannot resolve method 'thenReturn(List<T>)'
when(x.getList()).thenReturn(Collections.singletonList(new X()));
// Error: Cannot resolve method 'thenReturn(List<capture of ? extends X>)'
when(x.getList()).thenReturn((List<? extends X>) Collections.singletonList(new X()));
// Error: Cannot resolve method 'thenReturn(List<capture of ?>)'
when(x.getList()).thenReturn((List<?>) Collections.singletonList(new X()));

The only way of making it work with "when...then" seems to be stripping generics entirely, at the cost of a compiler warning:

when(x.getList()).thenReturn((List) Collections.singletonList(new X()));

Ultimately, only this works:

doReturn(Collections.singletonList(new X())).when(x.getList());
MaDa
  • 10,511
  • 9
  • 46
  • 84
  • 1
    checked [here](https://stackoverflow.com/questions/7366237/mockito-stubbing-methods-that-return-type-with-bounded-wild-cards/7655709#7655709)? – Pp88 Jul 28 '22 at 16:24

1 Answers1

0

This seems to be the most elegant answer:

when(x.getList()).thenAnswer(unused -> Collections.singletonList(new X()));

I still don't know what the problem is with the original statement, though.

MaDa
  • 10,511
  • 9
  • 46
  • 84