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?
The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called.
mock() method allows us to create a mock object of classes and interfaces. The Mockito. mock() is usually placed in the test set up method annotated with @Before in JUnit4 or @BeforeEach in JUnit 5. We called it before each test to create a new fresh mock object.
The Mockito framework provides a variety of methods such as mock(), verify(), when(), etc., used to test Java applications. Using these predefined methods makes testing very easy.
Starting with Mockito version 3.5. 0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With