How to test implementations of Guice AbstractModule?

随声附和 提交于 2019-12-22 03:55:29

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26710191/how-to-test-implementations-of-guice-abstractmodule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!