I would like to know if anybody has successfully @Autowired an auto-populated list of objects, injecting mocks, with Spring during the test phase of the build? What I want to be able to do is override 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...
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..
This works for injecting mocks, but then auto-population of the list doesn't kick in at runtime:
@Resource(name = "myServices")
private List<MyService> myServices;
And in my test config:
@Bean
@Qualifier("myServices")
public List<MyService> myServices() {
List<MyService> myServices = new ArrayList<>();
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;
}
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:
@Autowired
@Qualifier("myServices")
private List<MyService> myServices;
Thanks in advance for any insight on this.
Aucun commentaire:
Enregistrer un commentaire