Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

For example, interface Foo and interface Closeable?

In Rhino Mocks you can provide multiple interfaces when creating a mock object, but EasyMock's createMock() method only takes one type.

Is it possbile to achieve this with EasyMock, without resorting to the fallback of creating a temporary interface that extends both Foo and Closeable, and then mocking that?

like image 430
Daniel Fortunov Avatar asked Jul 23 '09 09:07

Daniel Fortunov


2 Answers

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.<Object>equalTo("a")));          try {             runnable.run();             fail();         }         catch (IllegalStateException e) {         }     } 
like image 69
Thomas Dufour Avatar answered Sep 23 '22 00:09

Thomas Dufour


have you considered something like:

interface Bar extends Foo, Closeable { } 

and then mock interface Bar?

like image 22
extraneon Avatar answered Sep 22 '22 00:09

extraneon