2

When developing TestNG tests with Guice, a la this:

@Guice(modules=MyTestModule.class)
public class MyTestClass {
}

It's very easy to use field injection to declare the dependencies of the test class. Now, suppose we have this:

@Guice(modules=MyTestModule.class)
public class MyTestClass {
    @Inject private Foo foo;

    @Test
    public void myTest() {
        Injector injector = Guice.createInjector(new SomeOtherModule());
    }
}

Because of field injection, if SomeOtherModule doesn't provide a binding for Foo, myTest() will fail due to CreationException, because it does not have the ability to create a MyTestClass, even if we do not intend for the test to create a MyTestClass with that injector.

Is there a way to express that intention, without changing into constructor injection of the Foo? That is, is there a way to somehow make it not an error to create the injector, but do make it an error when trying to specifically provision a MyTestClass, without changing how MyTestClass is written?

Kelvin Chung
  • 1,327
  • 1
  • 11
  • 23
  • 1
    What? In that example, `MyTestModule` will be injecting `Foo`, not `SomeOtherModule`. – Tavian Barnes Dec 06 '14 at 22:37
  • Right. `MyTestModule`, governing the creation of `MyTestClass` by TestNG, will be created (and a `Foo` injected) fine. However, the test itself, upon the creation of the injector local variable, will fail, due to `SomeOtherModule` lacking a binding for `Foo`. – Kelvin Chung Dec 08 '14 at 03:52
  • 1
    No it won't? `Guice.createInjector()` doesn't care about the class that calls it. If you did `injector.injectMembers(this)` then that would fail, so don't do that. – Tavian Barnes Dec 08 '14 at 15:24

0 Answers0