Java 如果我运行的类是junit,如何初始化GUI?

Java 如果我运行的类是junit,如何初始化GUI?,java,junit,dependency-injection,inversion-of-control,guice,Java,Junit,Dependency Injection,Inversion Of Control,Guice,我正在编写一个API模块 在开发过程中,我使用junit来运行代码 然而,最终一些其他模块将使用我的API 我想使用依赖注入模式 a Where应该是我初始化所有依赖项或全局util的主条目 b我觉得用guice注射器比较干净 但是我应该在哪里初始化它呢?这取决于你想做什么。我发现,在Guice 4.0中使用和注释,直接使用Guice通常是最简单的。例如: @RunWith(JUnit4.class) public final class TestMyInjectableCode { @Bi

我正在编写一个API模块

在开发过程中,我使用junit来运行代码

然而,最终一些其他模块将使用我的API

我想使用依赖注入模式

a Where应该是我初始化所有依赖项或全局util的主条目

b我觉得用guice注射器比较干净


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

这取决于你想做什么。我发现,在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());
  }
}

看看像Jukito这样的框架,它们在测试中为您管理Guice生命周期。如果可以的话,尽量避免单元测试中的注入,只需使用直接构造函数调用。