Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock method with Consumer

I want to mock repository.actionOnFile(String path, Consumer<InputStream> action) in this source:

@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();
}

The problem is that the second argument is a lambda expression.

How to mock it with mockito, I need to pass to the accept method the input stream to test it?

like image 529
mystdeim Avatar asked Nov 10 '17 13:11

mystdeim


1 Answers

I found solution!

doAnswer(ans -> {
    Consumer<InputStream> callback = ans.getArgument(1, Consumer.class);
    InputStream stream = new ByteArrayInputStream("test".getBytes(StandardCharsets.UTF_8));
    callback.accept(stream);
    return null;
}).when(repository).actionOnFile(eq("any"), any(Consumer.class));
like image 130
mystdeim Avatar answered Sep 22 '22 14:09

mystdeim