javagenericstestingjunitmockito

Having an issue with mocking a method which has a generic (? extends Collection) return type


I am having a problem with mocking a method with mockito that looks like the following:

Map<Foo, ? extends Collection<Bar>> getValue();

The following is how I am using it in the test:

model = Mockito.mock(Model.class);
Map<Foo, List<Bar>> value = new HashMap<Foo, List<Bar>>();
Mockito.when(model.getValue()).thenReturn(value);

It gives the following error:

error: no suitable method found for thenReturn(Map<Foo,List<Bar>>)


Solution

  • You may use the following:

    model = Mockito.mock(Model.class);
    final Map<Foo, List<Bar>> value = new HashMap<Foo, List<Bar>>();
    
    Mockito.when(model.getValue()).thenAnswer(new Answer<Map<Foo, List<Bar>>> () {
      public Map<Foo, List<Bar>> answer(InvocationOnMock invocation) throws Throwable {
        return value;
      }
    });
    

    Above can be shortened using lambda as:

    Mockito.when(model.getValue()).thenAnswer(invocationOnMock -> value)