Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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?
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())));
You don't want to fiddle with the ExecutorService
itself but rather mock findById
to get the result. As long as the mock returns the result immediately (unless you let it Thread.sleep
for a while) the call itself in the ExecutorService
is quick and the result is hence wrapped inside the Future
.
Mockito.when(userRepository.findById(Mockito.any()).thenReturn(userList);
Then you don't need to mock the ExecutorService
at all, you want to use a real service, or else it doesn't do what it's supposed to do.
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.