Skip to content
Advertisement

How to mock a autowired list of Spring beans?

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.

Concrete problem

I’ve a class called FormValidatorManager. This class loop through several validators which implements IFormValidator.

JavaScript

I would like to test this class. But I can’t find a way to mock validators property.

What I’ve tried

Since IFormValidators are singleton, I tried to mock several instances of these beans hoping them to be reflected in FormValidatorManager.validators but without success.

Then, I tried to create a list of IFormValidators which was annotated as @Mock. By initiating the List manually, I was hoping initMocks() to inject the created list. That was still without success.

Here is my last try:

JavaScript

An NPE is thrown in IFormValidator.validate() which I thougth would be mocked. The concrete implementation should not be called.

This leads to a really bad behavior since some of my tests on that class are false positives while others completly fail.

I’m trying to figure out how to mock an autowired list of beans while still having the possibility to mock specific implementations.

Do you have an idea start of solution ?

Regards

Advertisement

Answer

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:

JavaScript
Advertisement