Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test implementations of Guice AbstractModule?

How to test implementations of Guice AbstractModule in a big project without creating fake implementations? Is it possible to test bind() and inject() methods?

like image 311
Nikolas Avatar asked Nov 03 '14 08:11

Nikolas


People also ask

Should I unit test Guice modules?

If your modules have logic you should definitely unit test them. If you just want to ensure the bindings are ok, write a small unit test that boots up the injector in Stage. TOOL.

What does install in Guice do?

install allows for composition: Within its configure method, FooModule may install FooServiceModule (for instance). This would mean that an Injector created based only on FooModule will include bindings and providers in both FooModule and FooServiceModule.

What is abstract module in Guice?

* AbstractModule is a helper class used to add bindings to the Guice injector. * * <p>Simply extend this class, then you can add bindings by either defining @Provides methods (see.

What is Guice binding?

Overview of bindings in Guice. A binding is an object that corresponds to an entry in the Guice map. You add new entries into the Guice map by creating bindings.


1 Answers

Typically the best way to test Guice modules is to just create an injector in your test and ensure you can get instances of keys you care about out of it.

To do this without causing production stuff to happen you may need to replace some modules with other modules. You can use Modules.override to selectively override individual bindings, but you're usually better off just not installing "production" type modules and using faked bindings instead.

Since Guice 4.0 there's a helper class BoundFieldModule that 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's more documentation for BoundFieldModule on the Guice wiki.

like image 55
Daniel Pryden Avatar answered Oct 12 '22 04:10

Daniel Pryden