Spying Guice module throws CreationException during unit test

Viewed 63

In my unit test, I wanna spy on my guice module and stub part of the module functions. But it throws out errors when I create injector using the spied module, saying:

  • xxx binding was already configured at xxxx
  • Overriding @Provides methods is not allowed

Example:


class MyModule extends AbstractModule{
 @Override
 protected void configure() {
    // Some bindings...
 }

 @Provides
 public Car getCar(){
  try{
   return getCarFromDB();
  } catch (...){
   return getDefaultCar();
  }
 } 

 public Car getCarFromDB(){
  // may fail with connection error
 }
 public Car getDefaultCar(){
  // return a default car
 }

}

Then, test

@Test
public void testGetCar_WithDBConnectionFailed_ReturnesDefaultCar(){
  MyModule spyModule = spy(new MyModule());
  Injector injector = Guice.createInjector(spyModule); // errors
  
  doThrow( ... some connection errors ...).when(spyModule).getCarFromDB();

  Car car = injector.getInstance(Car.class);
  Assertions.assert...
}

Is there a way to spy on the guice module?

0 Answers
Related