消费者模拟方法 [英] Mock method with Consumer
本文介绍了消费者模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在此源中模拟repository.actionOnFile(String path, Consumer<InputStream> action)
:
@Autowired
private FileRepositoryService repository;
public Document getDocument(URL url) {
MutableObject<Document> obj = new MutableObject<>();
Consumer<InputStream> actionOnFile = inputStream -> obj.setValue(getDocument(inputStream));
try {
repository.actionOnFile(url.toExternalForm(), actionOnFile);
} catch (S3FileRepositoryException e) {
throw e.getCause();
}
return obj.getValue();
}
问题在于第二个参数是lambda表达式.
The problem is that the second argument is a lambda expression.
如何使用模仿器模拟它,我需要将输入流传递给accept
方法以对其进行测试?
How to mock it with mockito, I need to pass to the accept
method the input stream to test it?
推荐答案
我找到了解决方法!
doAnswer(ans -> {
Consumer<InputStream> callback = (Consumer<InputStream>) ans.getArguments()[1];
InputStream stream = new ByteArrayInputStream(
"test".getBytes(StandardCharsets.UTF_8.name()));
callback.accept(stream);
return null;
}).when(repository).actionOnFile(eq("any"), any(Consumer.class));
这篇关于消费者模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文