Test doubles

During testing we often want to wire the bean context but supply some test doubles for certain dependencies. We can use BootContext.withBean() to achieve this.

public void myComponentTest() {

  // we have some test doubles we want to use
  MyRedisApi mockRedis = mock(MyRedisApi.class);
  MyDatabaseApi mockDb = mock(MyDatabaseApi.class);

  // create the context programmatically with some
  // test doubles rather than the real dependencies
  try (BeanContext context = new BootContext()
    .withBeans(mockRedis, mockDb)
    .load()) {

    // perform a component test (using the test doubles)
    CoffeeMaker coffeeMaker = context.getBean(CoffeeMaker.class);