Injecting JUnit tests with Guice using a Rule

05/04/2015

GuiceBerry is a pretty helpful library for injecting JUnit tests with Guice. However, it’s not super actively maintained and many of it’s methods and members are private making it difficult to change it’s behavior. Here’s a class, which essentially does what GuiceBerry does in one single class that you can edit yourself.

import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;

import com.connectifier.data.mongodb.MongoConnection;
import com.connectifier.data.mongodb.MongoDBConfig;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.mongodb.DB;
import com.mongodb.MongoClientOptions;

public class DbRule implements MethodRule  {

  private final Injector injector;
  
  public DbRule(Class envClass) {
    try {
      this.injector = Guice.createInjector(envClass.newInstance());
    } catch (InstantiationException | IllegalAccessException e) {
      throw new IllegalStateException(e);
    }
  }
  
  @Override
  public Statement apply(Statement base, FrameworkMethod method, Object target) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        try {
          injector.injectMembers(target);
          base.evaluate();
        } finally {
          runAfterTest();
        }
      }
    };
  }

  protected void runAfterTest() {
    DB db = MongoConnectionFactory.createDatabaseConnection(
        injector.getInstance(MongoDBConfig.class),
        injector.getInstance(MongoClientOptions.class));
    db.dropDatabase();
    db.getMongo().close();
  }

};

To use:

  @Rule
  public final DbRule env = new DbRule(DataEnv.class);
Be Sociable, Share!