Using Mockito to mock classes with generic parameters

后端 未结 7 1899
不知归路
不知归路 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:50

    Create a test utility method. Specially useful if you need it for more than once.

    @Test
    public void testMyTest() {
        // ...
        Foo mockFooBar = mockFoo();
        when(mockFooBar.getValue).thenReturn(new Bar());
    
        Foo mockFooBaz = mockFoo();
        when(mockFooBaz.getValue).thenReturn(new Baz());
    
        Foo mockFooQux = mockFoo();
        when(mockFooQux.getValue).thenReturn(new Qux());
        // ...
    }
    
    @SuppressWarnings("unchecked") // still needed :( but just once :)
    private  Foo mockFoo() {
        return mock(Foo.class);
    }
    

提交回复
热议问题