如果我的跑步课是junit,如何初始化guice? [英] how to init guice if my running class is junit?

查看:103
本文介绍了如果我的跑步课是junit,如何初始化guice?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个API模块.

I'm writing an API module.

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

while developing I use junit to run the code

但是最终其他模块将使用我的API.

however eventually some other modules will use my API.

我想使用依赖注入模式

a)我的主条目应该在哪里初始化所有依赖项或全局utils?

a) Where should be my main entry where I init all the dependencies or global utils?

b)我认为使用Guice注射器更整洁,

b) I thought it be neater using guice injector,

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

but where should I init it?

推荐答案

这取决于您要执行的操作.我找到了 BoundFieldModule

It depends on what you're trying to do. I find, with BoundFieldModule and the @Bind annotation in Guice 4.0, that it's generally easiest to just use Guice directly. For example:

@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());
  }
}

这篇关于如果我的跑步课是junit,如何初始化guice?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆