【问题标题】:Calling methods with the correct Guice bindings使用正确的 Guice 绑定调用方法
【发布时间】: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 托管绑定(包括对 scopesbinding annotations、...的支持)调用像 someIntegrationTest(Component component) 这样的方法?

【问题讨论】:

    标签: java integration-testing junit4 guice


    【解决方案1】:

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

    类似的东西

    injector.getInstance(Component);
    

    将返回您的 Guice 注入对象

    【讨论】:

    • 是的,我知道。但我不想自己分析参数(请记住,例如绑定注释),因为功能已经存在:Guice 将所有依赖项注入到 @Provides 方法和构造函数中。两者都可以像 someIntegrationTest 测试方法一样接受参数。
    猜你喜欢
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2017-08-20
    • 2018-04-29
    相关资源
    最近更新 更多