java - 在 Guice 中覆盖绑定(bind)

标签 java unit-testing guice

我刚刚开始使用 Guice,我能想到的一个用例是,在测试中我只想覆盖单个绑定(bind)。我想我想使用其余的生产级绑定(bind)来确保一切设置正确并避免重复。

假设我有以下模块

public class ProductionModule implements Module {
    public void configure(Binder binder) {
        binder.bind(InterfaceA.class).to(ConcreteA.class);
        binder.bind(InterfaceB.class).to(ConcreteB.class);
        binder.bind(InterfaceC.class).to(ConcreteC.class);
    }
}

在我的测试中,我只想覆盖 InterfaceC,同时保持 InterfaceA 和 InterfaceB 的完整性,所以我想要类似的东西:

Module testModule = new Module() {
    public void configure(Binder binder) {
        binder.bind(InterfaceC.class).to(MockC.class);
    }
};
Guice.createInjector(new ProductionModule(), testModule);

我也尝试了以下方法,但没有成功:

Module testModule = new ProductionModule() {
    public void configure(Binder binder) {
        super.configure(binder);
        binder.bind(InterfaceC.class).to(MockC.class);
    }
};
Guice.createInjector(testModule);

有谁知道我是否可以做我想做的事,还是我完全找错了树??

--- 跟进: 如果我在接口(interface)上使用@ImplementedBy 标记,然后只在测试用例中提供一个绑定(bind),这似乎可以实现我想要的,当接口(interface)和实现之间存在 1-1 映射时,它可以很好地工作。

此外,在与同事讨论后,我们似乎会走上覆盖整个模块并确保我们正确定义模块的道路。尽管绑定(bind)在模块中放错位置并且需要移动,但这似乎可能会导致问题,因此可能会破坏大量测试,因为绑定(bind)可能不再可用于覆盖。

最佳答案

这可能不是您要寻找的答案,但如果您正在编写单元测试,您可能不应该使用注入(inject)器,而应该手动注入(inject)模拟或假对象。

另一方面,如果你真的想替换单个绑定(bind),你可以使用 Modules.override(..):

public class ProductionModule implements Module {
    public void configure(Binder binder) {
        binder.bind(InterfaceA.class).to(ConcreteA.class);
        binder.bind(InterfaceB.class).to(ConcreteB.class);
        binder.bind(InterfaceC.class).to(ConcreteC.class);
    }
}
public class TestModule implements Module {
    public void configure(Binder binder) {
        binder.bind(InterfaceC.class).to(MockC.class);
    }
}
Guice.createInjector(Modules.override(new ProductionModule()).with(new TestModule()));

详情见Modules documentation .

但正如 Modules.overrides(..) 的 javadoc 所建议的那样,您应该以不需要覆盖绑定(bind)的方式设计您的模块。在您给出的示例中,您可以通过将 InterfaceC 的绑定(bind)移动到单独的模块来完成此操作。

关于java - 在 Guice 中覆盖绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/483087/

相关文章:

java - 在 Guice 中使用命名注入(inject)

java - 如何使用@BeforeTest注释获取testng中的方法名称

Java - 为类方法编写一个条件,确保只能使用 HashMap 的某些项目。

java - 在 Lambda java 8 中改变实例或局部对象变量

java - 在其他类中模拟创建对象

java - 使用 GUICE 注入(inject) HttpClient 以在 Java 中获取模拟响应

java - 方法调用者和被调用者,循环类级别方法调用

c# - 在测试中使用已实现的方法是好主意还是坏主意?

unit-testing - 模拟扩展通用基类的 grails 服务时出现 IllegalArgumentException

java - 如何让 Guice 将带注释的注入(inject)绑定(bind)到单个实例