Integrating guice and junit4

A JUnit4 Method rule to perform injection on your test fixture before each test case:

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
 
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
 
public class PerTestGuiceRule implements MethodRule
{
   private final Module module;
 
   public PerTestGuiceRule(final Module module)
   {
      this.module = module;
   }
 
   @Override
   public Statement apply(
            final Statement base,
            @SuppressWarnings("unused") final FrameworkMethod method,
            final Object target)
   {
      return new Statement()
      {
         @Override
         public void evaluate() throws Throwable
         {
            final Injector injector = Guice.createInjector(module);
 
            injector.injectMembers(target);
 
            base.evaluate();
         }
      };
   }
}

Use it by putting this code in you test fixture:

@Rule public PerTestGuiceRule guiceRule = 
                   new PerTestGuiceRule(new MyModule());
 
@Inject MyInjectableType myInjectableType;

You might want to check out GuiceBerry. I tried to use it, but for my case it seems very complex, or maybe impossible, to create your module per-test due to the static map of module class -> module instance used internally by guiceberry. There is a test scope included, but I don’t see a really clean way to use that if you want to test your production guice modules.

Leave a Reply

Your email address will not be published. Required fields are marked *