How to mock a autowired list of Spring beans?

后端 未结 1 2010
时光取名叫无心
时光取名叫无心 2021-02-12 11:06

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

1条回答
  •  名媛妹妹
    2021-02-12 11:11

    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 validators = new ArrayList();
    
    @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");
    }
    

    0 讨论(0)
提交回复
热议问题