虽然我基本上同意Nick Holt的答案,但我认为我应该指出,mockito允许通过以下电话做你要求的事情:
Foo mock = Mockito.mock(Foo.class, withSettings().extraInterfaces(Bar.class));
显然,你必须使用演员阵容:当你需要使用模拟作为一个,但该演员阵容不会抛出(Bar)mock
Bar
ClassCastException
这里有一个更完整的例子,尽管完全是荒谬的:
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) {
}
}