Using Mockito to mock classes with generic parameters

后端 未结 7 1906
不知归路
不知归路 2020-11-30 19:37

Is there a clean method of mocking a class with generic parameters? Say I have to mock a class Foo which I need to pass into a method that expects a <

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 19:55

    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 fooMock;
    
        @Test
        public void testFoo() {
            when(fooMock.getValue()).thenReturn(new Bar());
        }
    }
    

    The MockitoJUnitRunner initializes the fields annotated with @Mock.

提交回复
热议问题