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

标签 java junit dependency-injection inversion-of-control guice

我正在编写一个 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/

相关文章:

java - 如何旋转缓冲图像,然后将缓冲图像复制到像素数组中

java - 如何避免在显示警报后提交表单?

java - 注解和处理器之间的匹配

java - 在 junit 中运行代码时的不同行为

go - 函数定义了未命名的参数,但调用者仍然传递值

java - Dagger 2 瞄准镜使用生命周期

java - 两个 Activity 之间的 Intent 出现 NullPointerException

android - 纯 kotlin 模块中的 "Empty test suite."。 (斯波克/安卓)

java - 将值注入(inject)到注释中?

Java编程作业