我想使用 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));
谁能给我一个解决方案吗?
感谢您的回答。我已经找到了针对这种情况的解决方案。
我们可以使用以下代码片段来模拟执行程序服务调用。
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())));
您不想摆弄
ExecutorService
本身,而是模拟 findById
来获得结果。只要模拟立即返回结果(除非你让它 Thread.sleep
一会儿),ExecutorService
中的调用本身就很快,因此结果被包装在 Future
中。
Mockito.when(userRepository.findById(Mockito.any()).thenReturn(userList);
那么你根本不需要模拟
ExecutorService
,你想使用真正的服务,否则它不会做它应该做的事情。
接受的答案对我不起作用,因为编译器一直告诉我将
any(Callable.class)
转换为 Runnable
。所以,我用(类似于实现)来嘲笑它:
when(executorService.submit(() -> any(Callable.class)))
.thenReturn(ConcurrentUtils.constantFuture(userList()));