我试图模仿一个名为cat: no such file or directory.
的协作者并捕获其方法Worker
的参数,该参数在不同的线程中运行。
但是,该方法本身具有方法引用作为参数:execute
和childService::listClients
。
当我使用捕获的参数断言方法引用时,我得到不同的lambda对象。
有没有办法以正确的方式触及和断言?
正在测试的课程:
childService::refreshObjects
测试:
public class ParentService {
private ChildService childService;
private Worker worker;
...
public void doAction() {
worker.execute(
childService::listClients,
childService::refreshObjects
);
}
}
断言错误:
@Test
public void shouldUseChildService() {
ArgumentCaptor<Callable> callableCaptor = ArgumentCaptor.forClass(Callable.class);
ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class);
parentService.doAction();
verify(worker).execute(callableCaptor.capture(), consumerCaptor.capture());
assertEquals((Callable) childService::listClients, callableCaptor.getValue());
assertEquals((Consumer) childService::refreshObjects, consumerCaptor.getValue());
}
答案 0 :(得分:5)
首先用Mockito模拟你的Worker
(就像你一样)。同时嘲笑你的ChildService
。然后:
@Test
public void shouldUseChildService() {
ArgumentCaptor<Callable> callableCaptor = ArgumentCaptor.forClass(Callable.class);
ArgumentCaptor<Consumer> consumerCaptor = ArgumentCaptor.forClass(Consumer.class);
parentService.doAction();
verify(worker).execute(callableCaptor.capture(), consumerCaptor.capture());
callableCaptor.getValue().call(); //this will execute whatever was captured
consumerCaptor.getValue().accept(null);//this will execute whatever was captured
// now verify that childService::listClients and childService::refreshObjects have been called
}