This error is happening because the compiler can't guarantee that the value type of the map returned by getValue
is in fact List<Bar>
. The type Map<Foo, ? extends Collection>
means "a Map
of Foo
s to some unknown type implementing Collection
".
This is a good example of why using wildcards in return types is discouraged, because they generally inhibit the caller by obscuring the generic type information about what's returned (conversely, using wildcards in method parameters is encouraged because it makes things easier for the caller). I would recommend getting rid of the wildcard if possible:
Map<Foo, Collection<Bar>> getValue();
And use:
model = Mockito.mock(Model.class);
Map<Foo, Collection<Bar>> value = new HashMap<Foo, Collection<Bar>>();
Mockito.when(model.getValue()).thenReturn(value);
If you're unable to change the method's return type, you could use a "capture helper" method for the test:
private <T extends Collection<Bar>> test(Map<Foo, T> actual) {
Map<Foo, T> expected = new HashMap<Foo, T>();
Mockito.when(actual).thenReturn(expected);
}
...
model = Mockito.mock(Model.class);
test(model.getValue()); // T is resolved to wildcard capture
Of course this is very limiting because you can only test for an empty map without knowing what T
is.