how to init guice if my running class is junit?

2019-08-15 16:43发布

问题:

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());
  }
}