title: Spring auto populate list with mocks
body: <p>I would like to know if anybody has successfully @Autowired an auto-populated <em>list</em> of objects, injecting mocks, with Spring during the test phase of the build? What I want to be able to do is <em>override</em> Spring's auto-population of a list during test time and have it populated with mocks within a unit test, instead of the implementation classes. I have successfully accomplished this by specifying @Resource within the code instead of @Autowired, but then when I deploy the Spring web app, the auto-population does not execute with @Resource specified for my list (it's just empty). The oppposite happens when I specify @Autowired on the list. The list is auto-populated when the app runs, but then I cannot populate the list with mocks when the unit tests run. It seems to be a catch-22...</p>
  
  <p>So how do I use @Resource on a List type and have Spring still do the auto-population at runtime? Has anybody done this successfully - use auto-population at runtime, but substitute mocks into the list during the test phase? If so, could you possibly post relevant parts of your test @Configuration class? (Java annotations please, not XML). Thanks..</p>
  
  <p>This works for injecting mocks, but then auto-population of the list doesn't kick in at runtime:</p>
  
  <pre><code>@Resource(name = "myServices")
  private List&lt;MyService&gt; myServices;
  </code></pre>
  
  <p>And in my test config:</p>
  
  <pre><code>@Bean
  @Qualifier("myServices")
  public List&lt;MyService&gt; myServices() {
      List&lt;MyService&gt; myServices = new ArrayList&lt;&gt;();
      MyService mockService1 = Mockito.mock(MyService.class, Mockito.RETURNS_DEEP_STUBS);
      MyService mockService2 = Mockito.mock(MyService.class, Mockito.RETURNS_DEEP_STUBS);
      eventServices.add(mockService1);
      eventServices.add(mockService2);
      return myServices;
  }
  </code></pre>
  
  <p>And then with the following, auto-population is active all the time (at runtime and during the test phase), but I cannot override and inject the mocks during the test phase with @Autowired, as it ignores the myServices @Bean definition from the test config:</p>
  
  <pre><code>@Autowired
  @Qualifier("myServices")
  private List&lt;MyService&gt; myServices;
  </code></pre>
  
  <p>Thanks in advance for any insight on this.</p>