In my application I am using a FactoryModuleBuilder to automatically create instances of some class:
new AbstractModule() {
@Override
protected void configure() {
install(new FactoryModuleBuilder().implement(A.class,B.class).build(A.AFactory.class));
}
});
In my test I don't really want to use the implementation (class B) so I would like to configure a module so the factory would return a Mockito mock like this:
new AbstractModule() {
@Override
protected void configure() {
install(new FactoryModuleBuilder().implement(A.class,myMockInstance).build(A.AFactory.class));
}
});
Obviously the above doesn't make sense because implement() tells which implementation is supposed to be used for interface A but I hope it gets my point across that I want the created factory to use my mock object. Then I could use my mock as usual:
Mockito.when(myMockInstance.doStuff()).thenReturn(result);
Is this possible or do I have to create manually a class C implementing A which will act as a mock?
Why use FactoryModuleBuilder at all? It exists to automate the handling of @Assisted parameters from A.AFactory to B's constructor, but in a test you don't need that—especially if the factory returns a mock. Instead, mock your own A.AFactory, and make it accessible through Guice.
final A myMockInstance = createAMock();
new AbstractModule() {
@Override protected void configure() {}
@Provides
A.AFactory createAFactory() {
A.AFactory factory = mock(A.AFactory.class);
when(factory.createA(anyString(), anyInt(), any(Dependency.class)))
.thenReturn(myMockInstance);
return factory;
}
});
I use a @Provides method here, but you could easily just write your own five-line named A.AFactory instead and bind using bind(A.AFactory.class).to(AFactoryForTest.class), or set up your mock factory elsewhere and bind(A.AFactory.class).toInstance(myMockInstance);.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With