Test doubles and Mockito

During testing we often want to wire the bean context but supply some test doubles for certain dependencies.

We use withMock and withSpy to use Mockito mocks and spys and otherwise use withBean to use some other test double that we supply.

 

BeanContext.withMock()

We can use withMock() to have Mockito mocks injected in place of the normal behaviour.

@Test
public void myComponentTest() {

  try (BeanContext context = new BootContext()
    .withMock(Pump.class)
    .withMock(Heater.class)
    .withMock(Grinder.class, grinder -> {
      // setup the mock
      when(grinder.grindBeans()).thenReturn("stub response");
    })
    .load()) {

    // Act
    CoffeeMaker coffeeMaker = context.getBean(CoffeeMaker.class);
    coffeeMaker.makeIt();

    Grinder grinder = context.getBean(Grinder.class);
    verify(grinder).grindBeans();
}

BeanContext.withSpy()

We can use withSpy() to get the beans to be enhanced with Mockito Spy.

We typically want to do this when we want the bean to have most or all of it's behaviour and only stub out some of it's behaviour and track it's interactions.

@Test
public void myComponentTest() {

  try (BeanContext context = new BootContext()
    .withSpy(Pump.class, pump -> {
      // setup the spy, only stub out pumpWater()
      doNothing().when(pump).pumpWater();
    })
    .load()) {

    // or setup here ...
    Pump pump = context.getBean(Pump.class);
    doNothing().when(pump).pumpSteam();

    // act
    CoffeeMaker coffeeMaker = context.getBean(CoffeeMaker.class);
    coffeeMaker.makeIt();

    verify(pump).pumpWater();
    verify(pump).pumpSteam();
  }

}

BeanContext.withBeans()

We can use withBeans() to supply our own test doubles.

@Test
public void myComponentTest() {

  // create our test doubles to use
  Pump pump = mock(Pump.class);
  Grinder grinder = mock(Grinder.class);

  try (BeanContext context = new BootContext()
    .withBeans(pump, grinder)
    .load()) {

    // act
    CoffeeMaker coffeeMaker = context.getBean(CoffeeMaker.class);
    coffeeMaker.makeIt();

    // assert
    assertThat(...)
  }

}