我正在编写一个 API 模块。
在开发时我使用junit来运行代码
但是最终其他一些模块将使用我的 API。
我想使用依赖注入(inject)模式
a)初始化所有依赖项或全局实用程序的主条目应该在哪里?
b) 我认为使用 guice 注入(inject)器会更简洁,
但是我应该在哪里初始化它呢?
最佳答案
这取决于您想要做什么。我发现,与 BoundFieldModule
和 @Bind
Guice 4.0 中的注释表明直接使用 Guice 通常是最简单的。例如:
@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());
}
}
关于java - 如果我的运行类是 junit,如何初始化 guice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27604727/