mys*_*eim 2 java lambda mocking
我想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();
}
Run Code Online (Sandbox Code Playgroud)
问题在于第二个参数是lambda表达式。
如何使用模仿来模拟它,我需要accept将输入流传递给方法以对其进行测试?
我找到了解决方案!
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));
Run Code Online (Sandbox Code Playgroud)