0

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 ?

Mattew Eon
  • 1,722
  • 1
  • 21
  • 38

2 Answers2

1

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 .. 
}
Arthur Klezovich
  • 2,595
  • 1
  • 13
  • 17
1

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

  • Thanks for this I can now handle Optional in my test with annotations. It leads to two issues now : this code is returning null in my constructor : `executors.orElseGet(ArrayList::new)` and the defined mockExecutor that extends the `BatchInputContentExecutor` is not in the Mocked list – Mattew Eon Nov 08 '21 at 13:32