【发布时间】:2016-03-17 14:18:08
【问题描述】:
Guice 是否提供任何方法来“手动”调用具有正确 Guice 绑定参数的方法?就像使用constructor injection 时自动为provider methods 或构造函数做的那样?示例:
@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 托管绑定(包括对 scopes、binding annotations、...的支持)调用像 someIntegrationTest(Component component) 这样的方法?
【问题讨论】:
标签: java integration-testing junit4 guice