Using Mockito to mock classes with generic parameters Using Mockito to mock classes with generic parameters java java

Using Mockito to mock classes with generic parameters


I think you do need to cast it, but it shouldn't be too bad:

Foo<Bar> mockFoo = (Foo<Bar>) mock(Foo.class);when(mockFoo.getValue()).thenReturn(new Bar());


One other way around this is to use @Mock annotation instead.Doesn't work in all cases, but looks much sexier :)

Here's an example:

@RunWith(MockitoJUnitRunner.class)public class FooTests {    @Mock    public Foo<Bar> fooMock;        @Test    public void testFoo() {        when(fooMock.getValue()).thenReturn(new Bar());    }}

The MockitoJUnitRunner initializes the fields annotated with @Mock.


You could always create an intermediate class/interface that would satisfy the generic type that you are wanting to specify. For example, if Foo was an interface, you could create the following interface in your test class.

private interface FooBar extends Foo<Bar>{}

In situations where Foo is a non-final class, you could just extend the class with the following code and do the same thing:

public class FooBar extends Foo<Bar>{}

Then you could consume either of the above examples with the following code:

Foo<Bar> mockFoo = mock(FooBar.class);when(mockFoo.getValue()).thenReturn(new Bar());