使用正确的Guice绑定调用方法

时间:2016-03-17 14:18:09

标签: java integration-testing junit4 guice

Guice是否提供任何手段"手动"使用正确的Guice绑定参数调用方法?就像使用provider methodsconstructor injection或构造函数自动执行的那样?例如:

@Inject
public void myMethod(Component component, @Productive Configuration configuration) {
    // ...
}

背景:我写了一个基于JUnit的集成测试框架,它使用Guice进行依赖注入。每个测试套件或案例都可以声明它将使用的modules。这是集成测试的一个例子:

@RunWith(GuiceRunner.class)
@GuiceModules(SomeIntegrationTestModule.class)
public class SomeIntegrationTestSuite {

    @Inject
    Component component;

    @Test
    public void someIntegrationTest() {
        // do something with component
    }

}

这非常有效,只需在@GuiceModules添加/删除值即可轻松切换模块配置。但是,大多数测试用例需要不同的对象(上例中的component),所以它们都在类声明中加起来。我想拥有的是这样的:

@RunWith(GuiceRunner.class)
@GuiceModules(SomeIntegrationTestModule.class)
public class SomeIntegrationTestSuite {

    @Test
    @Inject
    public void someIntegrationTest(Component component) {
        // do something with component
    }

}

我确实知道如何扩展JUnit以便自己运行测试方法,但我不知道如何使用Guice Injector调用带有正确绑定的方法来解析Guice的形式参数管理对象。

简而言之:如何使用正确的Guice托管绑定调用someIntegrationTest(Component component)之类的方法(包括对scopesbinding annotations的支持,...)?

1 个答案:

答案 0 :(得分:0)

您实际上可以将Injector对象传递给JUNIT设置方法,然后使用它来获取注入的Component对象。

像这样的东西

injector.getInstance(Component);

会返回你的Guice注入对象

相关问题