1

is there a standard way to create a test module out of a let say production module.

I have always done it had-doc, but i heard of override and etc... Is that the way to go to create module that might be filled of mock object ?

I did not see any example of it, could you please point me to it, if that is the solution ?

Thx

MaatDeamon
  • 9,532
  • 9
  • 60
  • 127

1 Answers1

4

Seems like what you'd want is something like this

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()));

Please read this SO answer which is where I took this example from.

Community
  • 1
  • 1
Miguel
  • 19,793
  • 8
  • 56
  • 46
  • >>>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.>>> I do not understand that. The all idea of encapsulating creation is to keep it in one place. If one inject by hand rather than by an injector, then if the constructor change you have a problem, you need to propagate that in all the test classes that do the creation by hand. Moreover is the constructor are made private as per the best practice recommended that cause a problem. – MaatDeamon Aug 21 '14 at 10:39
  • 1
    Here's what I believe he was trying to say. When you're unit testing you're usually testing a single class. When that's the case, you don't need dependency injection because you can simply provide the class you're testing the necessary Mocks for that specific test. That is done by hand. If you're running integration tests then having Test Modules can be useful. About private constructor you're right so it's usually best to package scope your `Constructors` to make them testable. – Miguel Aug 21 '14 at 12:03