1

我阅读了几个教程和手册,但它们都跳过了我真正需要的部分,这是你运行这些东西的实际部分。

我的情况如下。

我有一个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 :SocketFactoryProdSocketFactoryTest.

我正在创建一个 TestConnection并且我想创建一个ConnectionImplwith SocketFactoryTest,但我真的不知道我是怎么做的。这是我一直缺少的部分,我应该在我的测试(或测试类setUp)中写什么。

4

1 回答 1

2

您可以在 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);
    }
}
于 2016-08-21T16:23:32.517 回答