Class InjectWithGuice

  • All Implemented Interfaces:
    org.junit.rules.MethodRule

    public class InjectWithGuice
    extends Object
    implements org.junit.rules.MethodRule
    Method rule to inject Google Guice dependencies to the annotated test class tests. Creates new injector for each executing test.

    Example of usage:

     public class Test
     {
         @Rule
         public InjectWithGuice injectWithGuice = new InjectWithGuice(new ModuleA(), new ModuleB());
    
         @Inject
         private IServiceFromModuleA serviceFromModuleA;
    
         @Inject
         private IServiceFromModuleB serviceFromModuleB;
    
         @Test
         public void shouldTestSomething()
         {
             serviceFromModuleA.use();
             serviceFromModuleB.use();
         }
     }
     
    • Constructor Detail

      • InjectWithGuice

        public InjectWithGuice​(com.google.inject.Module... modules)
        Creates an instance of InjectWithGuice.
        Parameters:
        modules - the modules to create Guice test support with, cannot be null, may be empty
      • InjectWithGuice

        public InjectWithGuice​(Collection<com.google.inject.Module> modules)
        Creates an instance of InjectWithGuice.
        Parameters:
        modules - the modules to create Guice test support with, cannot be null, may be empty
    • Method Detail

      • get

        public <T> T get​(Class<T> type)
        Returns the appropriate instance for the provided injection type.
        Parameters:
        type - the type of instance to get, cannot be null
        Returns:
        the appropriate instance for the provided injection type, never null
      • get

        public <T> T get​(com.google.inject.Key<T> key)
        Returns the appropriate instance for the provided injection key.
        Parameters:
        key - the key of instance to get, cannot be null
        Returns:
        the appropriate instance for the provided injection key, never null
      • apply

        public org.junit.runners.model.Statement apply​(org.junit.runners.model.Statement base,
                                                       org.junit.runners.model.FrameworkMethod method,
                                                       Object target)
        Specified by:
        apply in interface org.junit.rules.MethodRule