有没有可能创建一个用EasyMock实现多个接口的模拟对象?
例如,接口Foo和接口Closeable
在Rhino mock中,您可以在创建模拟对象时提供多个接口,但是EasyMock的createMock()方法只接受一种类型。
有没有可能用EasyMock来实现这一点,而不是求助于创建一个同时扩展Foo和Closeable的临时接口,然后对其进行模拟?
发布于 2009-07-23 10:41:51
EasyMock不支持这一点,所以你不得不使用临时接口的回退。
顺便说一句,我闻到了一点代码模糊的味道--一个方法真的应该把一个对象当做两个不同的东西来处理吗?这里是Foo和Closeable接口。
这意味着该方法正在执行多个操作,虽然我怀疑其中一个操作是“关闭”Closeable,但由调用代码决定是否需要“关闭”不是更有意义吗?
以这种方式构造代码使“打开”和“关闭”在同一个try ... finally块中,而IMHO使代码更具可读性,更不用说方法更通用,并允许您传递仅实现Foo的对象。
发布于 2009-08-13 08:14:18
虽然我基本上同意Nick Holt的回答,但我认为我应该指出,mockito允许您通过以下调用执行您所要求的操作:
Foo mock = Mockito.mock(Foo.class, withSettings().extraInterfaces(Bar.class));显然,当需要将模拟用作Bar时,您必须使用cast:(Bar)mock,但该强制转换不会抛出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) {
}
}发布于 2009-07-23 09:58:31
你有没有考虑过这样的事情:
interface Bar extends Foo, Closeable {
}然后模拟界面栏?
https://stackoverflow.com/questions/1170708
复制相似问题