enablemockedbean
If you are using spring and mockito for testing you are likely to use the annotations @InjectMocks and @Mock. These annotations along with the static initializer MockitoAnnotations.initMocks(this), offer a way to inject mock beans into the spring beans.

This technique has at least two limitations:

  • Only works for those spring beans present in the test class. If you need to inject the mock in every bean that depends on, you must declare and autowire all those beans ( although you do not require them ).
  • Mocks are injected after all the Spring initializations and post-processing. If you are using @PostConstruct, FactoryBean or similar, your mocks will be injected too late and will not be invoked.

An alternative is to use @MockedBean and @EnableMockedBean. By means of these annotations, mocks are created and directly injected into the Spring Context. The original beans are replaced by the mocks, before any initialization and post-processing happen.

An Example.

1. Add the dependency
<dependency>
    <groupId>net.therore.spring.mockito</groupId>
    <artifactId>therore-spring-mockito</artifactId>
    <version>RELEASE</version>
</dependency>
2. Example of a service
@Component
public class HelloWorldService {
    @Value("${name:Spring-Boot}")
    private String name;
    public String getHelloMessage() {
        return "Hello " + this.name;
    }
}
3. Example of a middle component
@Component
public class MiddleComponent {
    @Autowired
    private HelloWorldService helloWorldService;
    public String getHelloMessage() {
        return helloWorldService.getHelloMessage();
    }
}
4. This is a test class for the MiddleComponent
@EnableMockedBean
@SpringBootApplication
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=MockedBeanTest.class)
public class MockedBeanTest {
    @MockedBean
    private HelloWorldService helloWorldService;
    @Autowired
    private MiddleComponent middleComponent;
    @Test
    public void helloWorldIsCalledOnlyOnce() {
        middleComponent.getHelloMessage();
        // THEN HelloWorldService is called only once
        verify(helloWorldService, times(1)).getHelloMessage();
    }
}