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
2. Example of a service
public class HelloWorldService {
    private String name;
    public String getHelloMessage() {
        return "Hello " + this.name;
3. Example of a middle component
public class MiddleComponent {
    private HelloWorldService helloWorldService;
    public String getHelloMessage() {
        return helloWorldService.getHelloMessage();
4. This is a test class for the MiddleComponent
public class MockedBeanTest {
    private HelloWorldService helloWorldService;
    private MiddleComponent middleComponent;
    public void helloWorldIsCalledOnlyOnce() {
        // THEN HelloWorldService is called only once
        verify(helloWorldService, times(1)).getHelloMessage();