I\'ve read plenty of articles about how to mock Spring\'s bean and their autowired fields. But there is nothing I could find about autowired lists of beans.
Conc
I finally figured it out...
Sometimes, asking a question can give you a better approach to your problems :p
The problem is I was linking the validators to the list before they were mocked. The validators was then null and no reference could be updated when the MockitAnnotations.initMocks(this)
was called.
Moreover, to avoid iterator problems on List
, I had to use @Spy
instead of @Mock
.
Here is the final solution:
@Mock
private EsmRegexValidator regexValidator;
@Mock
private EsmFormNotNullValidator notNullValidator;
@Mock
private EsmFormDataTypeValidator dataValidator;
@InjectMocks
private EsmFormValidatorManager validatorManager;
@Spy
private List<IEsmFormValidator> validators = new ArrayList<IEsmFormValidator>();
@Mock
private ColumnDTO columnDTO;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
validators.add(notNullValidator);
validators.add(regexValidator);
validators.add(dataValidator);
Mockito.when(columnDTO.getTitle()).thenReturn("Mock title");
Mockito.when(columnDTO.getName()).thenReturn("Mock name");
}