Using Mockito to mock classes with generic parameters

Tim Clemons picture Tim Clemons · Oct 30, 2009 · Viewed 183.6k times · Source

Is there a clean method of mocking a class with generic parameters? Say I have to mock a class Foo<T> which I need to pass into a method that expects a Foo<Bar>. I can do the following easily enough:

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

Assuming getValue() returns the generic type T. But that's going to have kittens when I later pass it into a method expecting Foo<Bar>. Is casting the only means of doing this?

Answer

John Paulett picture John Paulett · Oct 31, 2009

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