Search code examples
javamultithreadingunit-testingmockitoexecutorservice

How to mock ExecutorService call using Mockito


I want to mock the following code snippet using Mockito.

Future<Optional<List<User>>> getUser =
       executorService.submit(() -> userRepository.findById(user.getUserId()));

I have tried with the following code, but it didn't work

    @Mock
    private ExecutorService executorService;

    @Mock
    private userRepository userRepository;

    when(executorService.submit(() -> userRepository.findById(USER_ID)))
           .thenReturn(ConcurrentUtils.constantFuture(userList));

Can anyone give me a solution for this?


Solution

  • Thanks for your answers. I have found a solution for this scenario.

    We can mock executor service call using the following code snippet.

    when(executorService.submit(any(Callable.class)))
          .thenReturn(ConcurrentUtils.constantFuture(userList()));
    

    And if you have more than one ExecutorService calls in your method call, you can mock every response by adding them as a comma-separated list to the Mockito call as follows.

    when(executorService.submit(any(Callable.class)))
          .thenReturn(ConcurrentUtils.constantFuture(userList()),
               ConcurrentUtils.constantFuture(Optional.of(departmentList())));