Pregunta

Suppose I have class Z, which injects class A:

class Z {
  @Inject
  public Z(.., A arg, ..) {
    ..
  }
}

Suppose class A has this constructor:

@Inject
public A(B arg0, C arg1, D arg2) {
 ...
}

I want injection to work normally, except in special cases, where I want to provide one of the arguments. e.g., Constuct A using cObject of C class. Note that A is itself constructed using Z.

I want this because I am writing a functional tests for Z, where I want to provide different kinds of fakes depending on the test. One test file will contain only one kind of fake for B, or C, or D.

¿Fue útil?

Solución

I would recommend using Modules.override here, which has documentation about its use for functional testing. Use it sparingly, as things can get very messy and hard-to-follow otherwise, but it would look like this:

@Before
public void createInjector() {
  this.injector = Guice.createInjector(
      Modules.override(new YourZABCDModule()).with(new AbstractModule() {
        @Override public void configure() {
          bind(B.class).to(FakeB.class);
        }
      }));
}

Or, as in the Modules.override documentation, just use smaller modules for more-granular combinations:

@Before
public void createInjector() {
  this.injector = Guice.createInjector(
      new ZAModule(),
      new FakeBModule(),
      new CModule(),
      new DModule());
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top