我阅读了几个教程和手册,但所有这些都跳过了我真正需要的部分,这是你运行这些东西的实际部分。
我的情况如下。
我有一个Connection
界面:
public interface Connection {
void open(Selector selector);
void send(NetMessage message);
}
我的生产实施需要SocketFactory
:
public class ConnectionImpl implements Connection {
// members
@Inject
public ConnectionImpl(@Assisted SecurityMode securityMode, @Assisted long connectionId,
@Assisted EntityAddresses addresses, SocketFactory socketFactory)
所以我创建了一个ConnectionFactory
:
public interface ConnectionFactory {
SioConnection create(SecurityMode securityMode, long connectionId, EntityAddresses addresses);
}
现在,我有SocketFactory
的两个实现:SocketFactoryProd
和SocketFactoryTest
。
我正在为Connection
创建一个测试,我想用ConnectionImpl
创建一个SocketFactoryTest
,我真的不知道我是怎么做的。这是我一直缺少的部分,我应该在我的测试中(或在测试类setUp
中写)。
答案 0 :(得分:0)
您可以在Guice模块中选择绑定到界面的内容:
public class MyTest {
@Inject
private ConnectionFactory connectionFactory;
@Before
public void setUp() {
Injector injector = Guice.createInjector(
<your modules here>,
new AbstractModule() {
@Override
protected void configure() {
install(new FactoryModuleBuilder()
.implement(Connection.class, ConnectionImpl.class)
.build(ConnectionFactory.class));
bind(SocketFactory.class).to(SocketFactoryTest.class);
}
}
);
injector.injectMembers(this);
}
}
如果要覆盖其中一个生产模块的SocketFactory的现有绑定,可以执行以下操作:
public class MyTest {
@Inject
private ConnectionFactory connectionFactory;
@Before
public void setUp() {
Injector injector = Guice.createInjector(
Modules.override(
<your modules here. Somewhere the
FactoryModuleBuilder is installed here too>
).with(
new AbstractModule() {
@Override
protected void configure() {
bind(SocketFactory.class).to(SocketFactoryTest.class);
}
}
)
);
injector.injectMembers(this);
}
}