title: How to prevent Spring from injecting @Autowired references inside a mock?
body: <p>I want to test a class using Spring + JUnit + Mockito but I don't manage to make it work properly.</p>
  
  <p>Let's say my class references a Service:</p>
  
  <pre><code>@Controller
  public class MyController 
  {
  
      @Autowired
      private MyService service;
  
      @PostConstruct
      public void init() {
          service.whatever();
      }
  
      public void doSomething() {
          service.create();
      }
  }
  </code></pre>
  
  <p>And this Service references a Repository:</p>
  
  <pre><code>@Service
  public class MyService {
  
      @Autowired
      private MyRepository repository;
  
      public void whatever() {}
  
      public void create() {
          repository.save();
      }
  }
  </code></pre>
  
  <p>When testing the MyController class, I want the service to be mocked. The problem is: <strong>even when the service is mocked, Spring tries to inject the repository in the mock</strong>.</p>
  
  <p>Here is what I did. Test class:</p>
  
  <pre><code>@RunWith(SpringJUnit4ClassRunner.class)
  @ContextConfiguration(classes = { MyControllerTestConfiguration.class })
  public class MyControllerTest {
  
      @Autowired
      private MyController myController;
  
      @Test
      public void testDoSomething() {
          myController.doSomething();
      }
  
  }
  </code></pre>
  
  <p>Configuration class:</p>
  
  <pre><code>@Configuration
  public class MyControllerTestConfiguration {
  
      @Bean
      public MyController myController() {
          return new MyController();
      }
  
      @Bean
      public MyService myService() {
          return Mockito.mock(MyService.class);
      }
  
  }
  </code></pre>
  
  <p>And the error I get: <code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [test.test.MyRepository] found for dependency</code></p>
  
  <p>I tried to initialize the mock using Mockito's <code>@InjectMocks</code> annotation but this fails because the <code>@PostConstruct</code> method is called before the mocks injection, generating a <code>NullPointerException</code>.</p>
  
  <p>And I cannot simply mock the repository because in real life that would make me mock A LOT of classes...</p>
  
  <p>Can anyone help me on this?</p>