Class BoundFieldModule

java.lang.Object
com.google.inject.testing.fieldbinder.BoundFieldModule
All Implemented Interfaces:
Module

public final class BoundFieldModule extends Object implements Module
Automatically creates Guice bindings for fields in an object annotated with Bind.

This module is intended for use in tests to reduce the code needed to bind local fields (usually mocks) for injection.

The following rules are followed in determining how fields are bound using this module:

Example use:


 public class TestFoo {
   // bind(new TypeLiteral<List<Object>>() {}).toInstance(listOfObjects);
   @Bind private List<Object> listOfObjects = Lists.of();

   // bind(String.class).toProvider(new Provider() { public String get() { return userName; }});
   @Bind(lazy = true) private String userName;

   // bind(SuperClass.class).toInstance(aSubClass);
   @Bind(to = SuperClass.class) private SubClass aSubClass = new SubClass();

   // bind(String.class).annotatedWith(MyBindingAnnotation.class).toInstance(myString);
   @Bind
   @MyBindingAnnotation
   private String myString = "hello";

   // bind(Object.class).toProvider(myProvider);
   @Bind private Provider<Object> myProvider = getProvider();

   @Before public void setUp() {
     Guice.createInjector(BoundFieldModule.of(this)).injectMembers(this);
   }
 }
 
See Also:
  • Method Details

    • of

      public static BoundFieldModule of(Object instance)
      Create a BoundFieldModule which binds the Bind annotated fields of instance.
      Parameters:
      instance - the instance whose fields will be bound.
      Returns:
      a module which will bind the Bind annotated fields of instance.
    • configure

      public void configure(Binder binder)
      Description copied from interface: Module
      Contributes bindings and other configurations for this module to binder.

      Do not invoke this method directly to install submodules. Instead use Binder.install(Module), which ensures that provider methods are discovered.

      Specified by:
      configure in interface Module