Generally, the best way to test Guice modules is to simply create an injector in your test and make sure that you can get instances of the keys you care about.
To do this without producing material, you may need to replace some modules with other modules. You can use Modules.override to selectively redefine individual bindings, but usually you better not just install modules like "production" and use fake bindings instead.
Since Guice 4.0 contains the helper class BoundFieldModule , which can help with this. I often set up tests like:
public final class MyModuleTest { @Bind @Mock DatabaseConnection dbConnection; @Bind @Mock SomeOtherDependency someOtherDependency; @Inject Provider<MyThing> myThingProvider; @Before public void setUp() { MockitoAnnotations.initMocks(this); Guice.createInjector(new MyModule(), BoundFieldModule.of(this)) .injectMembers(this); } @Test public void testCanInjectMyThing() { myThingProvider.get(); } }
There is more documentation for the BoundFieldModule on the Guice wiki.
source share