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