SteveSt
SteveSt

Reputation: 1297

How to use a mock Object with Assisted Inject instead of real implementation class

I have the following abstract class :

public abstract class MyClass

Then I have the two following abstract classes which extend this one :

public abstract class AClass extends MyClass

and

public abstract class BClass extends MyClass

I have to use dependency injection for the instantiation of my objects. The constructor of the classes which extend the classes AClass and BClass receive a String as an argument and for this reason I use the AssistedInject extension from Google Guice.

In my normal BinderModule I have the following code :

public class BinderModule implements Module{

@Override
public void configure(Binder binder) {
    binder.install(
            new FactoryModuleBuilder().
                    implement(AClass.class, AClassImpl.class).
                    build(AClassFactory.class));

    binder.install(
            new FactoryModuleBuilder().
                    implement(BClass.class, BClassImpl.class).
                    build(BClassFactory.class));
}
}

I also want to use a Module for testing purposes which will have mocked Objects for substituting AClassImpl and BClassImpl.

When I have used injection so far I did something like this :

InterfaceA myMockObj = EasyMock.createMock(InterfaceAImpl.class);
binder.bind(InterfaceA.class).toInstance(myMockObj);

The problem is that now the implement method receives only Class arguments and I cannot connect the mocked Objects to the Abstract classes.

Any ideas on how I can overcome this ?

Upvotes: 0

Views: 1681

Answers (1)

Tavian Barnes
Tavian Barnes

Reputation: 12922

In general, unit tests are simpler if you don't use Guice at all. But if you really want to, you could mock the factory interface like this:

BClass myMockObj = EasyMock.createMock(BClass.class);
BClassFactory mockFactory = EasyMock.createMock(BClassFactory.class);
EasyMock.expect(mockFactory.create(arguments)).andStubReturn(myMockObj);
bind(BClassFactory.class).toInstance(mockFactory);

instead of using assisted injection which isn't going to play nice with mocks.

Upvotes: 1

Related Questions