gpt4 book ai didi

java - 是否可以使用 EasyMock 创建一个实现多个接口(interface)的模拟对象?

转载 作者:IT老高 更新时间:2023-10-28 20:42:05 28 4
gpt4 key购买 nike

是否可以使用 EasyMock 创建一个实现多个接口(interface)的模拟对象?

例如接口(interface)Foo和接口(interface)Closeable

在 Rhino Mocks 中,你可以在创建 mock 对象时提供多个接口(interface),但 EasyMock 的 createMock() 方法只接受一种类型。

是否可以使用 EasyMock 来实现这一点,而无需求助于创建一个扩展 FooCloseable 的临时接口(interface),然后对其进行模拟?

最佳答案

虽然我基本上同意尼克霍尔特的回答,但我认为我应该指出 mockito允许通过以下调用执行您所要求的操作:

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

显然,当您需要将模拟用作 Bar 但该 Actor 不会抛出 时,您必须使用类型转换:(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) {
}
}

关于java - 是否可以使用 EasyMock 创建一个实现多个接口(interface)的模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1170708/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com