我想使用Mockito来模拟下面的代码片段。
Future<Optional<List<User>>> getUser =
executorService.submit(() -> userRepository.findById(user.getUserId()));
我试过使用下面的代码,但它没有工作
@Mock
private ExecutorService executorService;
@Mock
private userRepository userRepository;
when(executorService.submit(() -> userRepository.findById(USER_ID)))
.thenReturn(ConcurrentUtils.constantFuture(userList));
有人能给我一个解决办法吗?
发布于 2020-10-24 17:05:57
谢谢你的回答。我已经为这个场景找到了一个解决方案。
我们可以使用下面的代码片段来模拟executor服务调用。
when(executorService.submit(any(Callable.class)))
.thenReturn(ConcurrentUtils.constantFuture(userList()));
如果方法调用中有多个 ExecutorService调用,则可以通过将它们作为逗号分隔的列表添加到Mockito调用中来模拟每个响应,如下所示。
when(executorService.submit(any(Callable.class)))
.thenReturn(ConcurrentUtils.constantFuture(userList()),
ConcurrentUtils.constantFuture(Optional.of(departmentList())));
发布于 2020-10-21 14:50:03
您不想篡改ExecutorService
本身,而是模拟findById
以获得结果。只要模拟立即返回结果(除非让它在Thread.sleep
上停留一段时间),ExecutorService
中的调用本身是快速的,因此结果被包装在Future
中。
Mockito.when(userRepository.findById(Mockito.any()).thenReturn(userList);
然后您就根本不需要模拟ExecutorService
了,您想要使用真正的服务,否则它就不会做它应该做的事情。
https://stackoverflow.com/questions/64466093
复制相似问题