Here's how we are using Guice in a new application -
public class ObjectFactory {
private static final ObjectFactory instance = new ObjectFactory();
private final Injector injector;
private ObjectFactory() throws RuntimeException { this.injector = Guice.createInjector(new Module1()); }
public static final ObjectFactory getInstance() { return instance; }
public TaskExecutor getTaskExecutor() { return injector.getInstance(TaskExecutor.class); }
}
Module1 defines how the TaskExecutor needs to be constructed.
In the code we use ObjectFactory.getInstance().getTaskExecutor() to obtain and the instance of TaskExecutor.
In unit tests we want to be able to replace this with a FakeTaskExecutor essentially we want to get an instance of FakeTaskExecutor when ObjectFactory.getInstance().getTaskExecutor() is called.
I was thinking of implementing a FakeModule which would be used by the injector instead of the Module1.
Apologies if the question isn't too clear, this is because we're new to Guice. In Spring, we would just use the @Autowired annotation and then define separate beans for Test and Production code and run our tests with the Spring4JunitRunner, we're trying to do something similar with Guice.
Aucun commentaire:
Enregistrer un commentaire