Overriding Binding in Guice

This might not be the answer you’re looking for, but if you’re writing unit tests, you probably shouldn’t be using an injector and rather be injecting mock or fake objects by hand.

On the other hand, if you really want to replace a single binding, you could use 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()));

See details in the Modules documentation.

But as the javadoc for Modules.overrides(..) recommends, you should design your modules in such a way that you don’t need to override bindings. In the example you gave, you could accomplish that by moving the binding of InterfaceC to a separate module.

Leave a Comment