slashms
slashms

Reputation: 978

Using AssistedInject in Tests

I read several tutorials and manuals but all of them skips the part that I actually need, which is the actual part where you run the stuff.

My scenario is as follows.

I have a Connection interface:

public interface Connection {
   void open(Selector selector);
   void send(NetMessage message);
}

I have a production implementation that needs a SocketFactory:

public class ConnectionImpl implements Connection {
    // members
    @Inject
    public ConnectionImpl(@Assisted SecurityMode securityMode, @Assisted long connectionId,
                          @Assisted EntityAddresses addresses, SocketFactory socketFactory)

So I created a ConnectionFactory:

public interface ConnectionFactory {
    SioConnection create(SecurityMode securityMode, long connectionId, EntityAddresses addresses);
}

Now, I have two implementations of SocketFactory : SocketFactoryProdand SocketFactoryTest .

I am creating a Test for Connection and I want to create a ConnectionImpl with SocketFactoryTest, and I really don't get how I do exactly. This is the part that I keep on missing, what I should write in my test (or in the test class setUp).

Upvotes: 4

Views: 1189

Answers (1)

JadN
JadN

Reputation: 81

You choose what to be bound to your interface in the Guice Module:

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);
    }
}

If you want to override an existing binding of the SocketFactory from one of your production modules, you can do this:

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);
    }
}

Upvotes: 3

Related Questions