I am trying to make a unit test with Mockito and I cannot find any way to mock my constructor's optional autowired field.
Here is my constructor:
@Autowired
public BatchInputManager(
BatchInputContentRepository batchInputContentRepository,
Optional<List<BatchInputExecutor>> batchInputExecutors) {
// ...
}
And here is how I try to mock these fields :
@InjectMocks
BatchInputManager batchInputManager;
@Mock
BatchInputContentRepository batchInputContentRepository;
@Mock
List<BatchInputExecutor> executors;
For the record, the BatchInputExecutor
class is an abstract class and I defined a class that extends it in my test.
When I run my code, the optional that should contains all the extended classes of BatchInputExecutor
is not empty, it is null; and the repository is not null.
How am I supposed to mock the value of the optional field in my constructor ?
CodePudding user response:
I'd setup the mocks in the @BeforeEach/@BeforeAll
method of the JUnit test.
@BeforeEach
public void mocking(){
var repoMock = ... mock repo ..
var executorMock = mock(BatchInputExecutor.class)
// configure executorMock here
var batchInputExecutors = Optional.of(List.of(executorMock))
var batchInputManager = new BatchInputManager()
... set the class level fields here ..
}
CodePudding user response:
If you really want to use Mockito's annotations in this case:
Change this
@Mock
List<BatchInputExecutor> executors;
To this
@Mock
Optional<List<BatchInputExecutor>> executors;
And configure mockito to supports final classes and methods. See this https://stackoverflow.com/a/40018295/10744129