how to init guice if my running class is junit?

感情迁移 提交于 2019-12-13 01:25:26

问题


I'm writing an API module.

while developing I use junit to run the code

however eventually some other modules will use my API.

I want to use dependency injection pattern

a) Where should be my main entry where I init all the dependencies or global utils?

b) I thought it be neater using guice injector,

but where should I init it?


回答1:


It depends on what you're trying to do. I find, with BoundFieldModule and the @Bind annotation in Guice 4.0, that it's generally easiest to just use Guice directly. For example:

@RunWith(JUnit4.class)
public final class TestMyInjectableCode {
  @Bind @Mock @SomeAnnotation Foo myFoo;
  @Bind @SomeAnnotation String myAnnotationString = "some constant";

  @Bind(lazy = true) @ShouldDoSomeThing Boolean shouldDoSomeThing = false;

  @Inject Provider<SystemUnderTest> systemUnderTest;

  @Before public void setUpInjector() {
    MockitoAnnotations.initMocks(this);
    Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);
  }

  @Test public void test_ShouldDoSomeThing() {
    shouldDoSomeThing = true;
    SystemUnderTest sut = systemUnderTest.get();
    assertEquals("expected value", sut.getValue());
  }
}


来源:https://stackoverflow.com/questions/27604727/how-to-init-guice-if-my-running-class-is-junit

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