3

I have a root module that installs a child module. For example:

public class RootModule extends AbstractModule {
 @Override
 protected void configure() {
     install(new ChildModule());
 }
}
public class ChildModule extends AbstractModule {
 @Override
 protected void configure() {

 }

 @Provides
 @Singleton
 public Bar getBar(@Named("FooImpl") Foo foo) {
  return BarBuilder.withFoo(foo).build();
 }
}

I was able to test the ChildModule by creating injector by binding its required dependencies (Foo.class) with Mock and testing the behavior.

To test the root Module, should I explicitly pass all the dependencies that the ChildModule consumes since the root module installs ChildModule or is there a workaround to override the installed ChildModule with a Mock?

KraZy
  • 87
  • 6
  • Have you checked this https://stackoverflow.com/questions/26710191/how-to-test-implementations-of-guice-abstractmodule? – olgacosta Jul 16 '19 at 10:05
  • To clarify: are you trying to test something within `RootModule` after instantiating it, or are you just trying to test that `RootModule` does in fact install a `ChildModule`? – MyStackRunnethOver Jul 19 '19 at 21:52

1 Answers1

0

You can make the child Module(s) an instance variable of RootModule. Then you can pass a mocked Module into the constructor of RootModule when you are testing.

For example, a generic root module with children could look like this:

public class RootModule extends AbstractModule {

    private List<Module> childModules;

    public RootModule(List<Module> childModules) {
        this.childModules = childModules;
    }

    @Override
    protected void configure() {
        for (Module childModule : childModules) {
            install(childModule);
        }
    }
}
Matthew Pope
  • 7,212
  • 1
  • 28
  • 49