Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mockito to mock classes with generic parameters

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?

like image 359
Tim Clemons Avatar asked Oct 30 '09 22:10

Tim Clemons


People also ask

Can Mockito mock a class?

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.

What is difference between @mock and Mockito mock?

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.

What are the different approaches that we can use to mock objects using Mockito?

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.

Can we mock constructor using Mockito?

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.


2 Answers

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()); 
like image 130
John Paulett Avatar answered Sep 28 '22 03:09

John Paulett


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.

like image 34
Marek Kirejczyk Avatar answered Sep 28 '22 04:09

Marek Kirejczyk