我正在编写一个API模块。
在开发时,我使用junit来运行代码。
但是,最终其他一些模块将使用我的API。
我想使用依赖注入模式
a)在哪里应该是我初始化所有依赖项或全局实用程序的主要条目?
b)我认为使用guice injector会更简洁,
但是我应该在哪里初始化它呢?
发布于 2014-12-23 04:07:04
这取决于你想要做什么。我发现,在Guice4.0中使用BoundFieldModule和@Bind注释时,直接使用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());
}
}https://stackoverflow.com/questions/27604727
复制相似问题