If I use Mockito, do I even need Guice?

I found out about Injection Dependency (e.g. Guice) and it seems to me that one of the main drivers, testability, is already pretty well covered by Mocking (e.g. Mockito). The difference between dependency injection and the Mocking system (Ninject vs RhinoMock or Moq) is a good summary of the generality between Injection Dependency and Mockito, but it does not provide recommendations for use when they overlap in capabilities.

I'm going to develop an API, and I'm wondering if I should:

A] Use only Mockito

B] Use Guice and develop two interface implementations - one for real and one for testing.

C] Use Mockito AND Guice together - if so, how?

I guess the correct answer is C, to use both of them, but I would like a few words of wisdom: where can I use either Injection Dependency or Mocking, which I have to choose and why?

+4
source share
2 answers

Guice and Mockito have very different and complementary roles, and I would say that they work best.

Consider this contrived class example:

public class CarController {
  private final Tires tires = new Tires();
  private final Wheels wheels = new Wheels(tires);
  private final Engine engine = new Engine(wheels);
  private Logger engineLogger;

  public Logger start() {
    engineLogger = new EngineLogger(engine, new ServerLogOutput());
    engine.start();
    engineLogger.recordEvent(ENGINE_STARTED);
    return engineLogger;
  }
}

, : , , : , , , , , . ?

DI-friendly:

public class CarController { /* with injection */
  private final Engine engine;
  private final Provider<Logger> loggerProvider;
  private Logger engineLogger;

  /** With Guice, you can often keep the constructor package-private. */
  @Inject public Car(Engine engine, Provider<Logger> loggerProvider) {
    this.engine = engine;
    this.loggerProvider = loggerProvider
  }

  public Logger start() {
    engineLogger = loggerProvider.get();
    engine.start();
    engineLogger.recordEvent(ENGINE_STARTED);
    return engineLogger;
  }
}

CarController , , , , , . , DI : Logger SnowTires RacingTires .   , : , FakeEngine DummyLogger, CarControllerTest. (, setter , , Guice. Guice .)

, : Guice, Mockito, Logger , :

public class FakeEngine implements Engine {
  RuntimeException exceptionToThrow = null;
  int callsToStart = 0;
  Logger returnLogger = null;

  @Override public Logger start() {
    if (exceptionToThrow != null) throw exceptionToThrow;
    callsToStart += 1;
    return returnLogger;
  }
}

Mockito, , :

@Mock Engine mockEngine;
// To verify:
verify(mockEngine).start();
// Or stub:
doThrow(new RuntimeException()).when(mockEngine).start();

... . (CarController), (Tires, Wheels, ServerLogOutput) . Mockito , , .

: Guice, Mockito API, . Guice ; Mockito . , OO - .


, :

  • , Guice ; @Inject test doubles, . , , , , , , Mockito .

  • Mockito " " @InjectMocks, @Mock /, . mocks, , , , . , , DI, .

+17

All Articles