Is it possible to create a mock object that implements multiple interfaces with EasyMock?

后端 未结 6 2024
清酒与你
清酒与你 2020-12-30 18:35

Is it possible to create a mock object that implements several interfaces with EasyMock?

For example, interface Foo and interface Closeable

6条回答
  •  一向
    一向 (楼主)
    2020-12-30 19:25

    An alternative of the most voted answer still based on Mockito but with annotations. You can set the extraInterfaces directly from the Mock annotation as next:

    @RunWith(MockitoJUnitRunner.class)
    public class MyTest {
        @Mock(extraInterfaces = Closeable.class)
        private Foo foo;
        ...
    }
    

    NB: extraInterfaces is of type Class[] so you can specify several interfaces if needed.

    If you need to mock method calls of the extra interfaces you will need to cast your mock. For example let's say that I want to throw an IOException when I call close() on my mock foo, the corresponding code would then be:

    Mockito.doThrow(IOException.class).when((Closeable) foo).close();
    

提交回复
热议问题