首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果我运行的类是junit,如何初始化guice?

问如果我运行的类是junit,如何初始化guice?
EN

Stack Overflow用户
提问于 2014-12-22 22:33:11
回答 1查看 402关注 0票数 1

我正在编写一个API模块。

在开发时,我使用junit来运行代码。

但是,最终其他一些模块将使用我的API。

我想使用依赖注入模式

a)在哪里应该是我初始化所有依赖项或全局实用程序的主要条目?

b)我认为使用guice injector会更简洁,

但是我应该在哪里初始化它呢?

EN

回答 1

Stack Overflow用户

发布于 2014-12-23 04:07:04

这取决于你想要做什么。我发现,在Guice4.0中使用BoundFieldModule和@Bind注释时,直接使用Guice通常是最简单的。例如:

代码语言:javascript
复制
@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());
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27604727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档