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());