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

后端 未结 6 2034
清酒与你
清酒与你 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条回答
  •  猫巷女王i
    2020-12-30 19:24

    Although I fundamentally agree with Nick Holt's answer, I thought I should point out that mockito allows to do what you ask with the following call :

    Foo mock = Mockito.mock(Foo.class, withSettings().extraInterfaces(Bar.class));
    

    Obviously you'll have to use the cast: (Bar)mock when you need to use the mock as a Bar but that cast will not throw ClassCastException

    Here is an example that is a bit more complete, albeit totally absurd:

    import static org.junit.Assert.fail;
    import org.junit.Test;
    import static org.mockito.Mockito.*;
    import org.mockito.Mockito;
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.*;
    import org.hamcrest.Matchers;
    
    import java.util.Iterator;
    
    
    public class NonsensicalTest {
    
    
        @Test
        public void testRunnableIterator() {
            // This test passes.
    
            final Runnable runnable = 
                        mock(Runnable.class, withSettings().extraInterfaces(Iterator.class));
            final Iterator iterator = (Iterator) runnable;
            when(iterator.next()).thenReturn("a", 2);
            doThrow(new IllegalStateException()).when(runnable).run();
    
            assertThat(iterator.next(), is(Matchers.equalTo("a")));
    
            try {
                runnable.run();
                fail();
            }
            catch (IllegalStateException e) {
            }
        }
    
        

    提交回复
    热议问题