'How can I mock this piece of code of Spring Boot using Mockito?

Consider:

return attachmentList.stream().map(attachment -> {
    AttachmentBO attachmentBO = new AttachmentBO();
    attachmentBO.setId(attachment.getId());
    attachmentBO.setTitle(attachment.getName());
    attachmentBO.setType(attachment.getValue().get("type").toString());
    attachmentBO.setCreatorId(attachment.getAuditUserId());
    String[] filteredPermissionsForNote = this.filterPermissionCommand.filterPermissions(answer.getTopicId(), attachment.getAuditUserId(), topicDetails.getPermissions(), topicDetails.getEffectiveRoles(), true);
    attachmentBO.setPermissions(filteredPermissionsForNote);

    if (attachmentBO.getType().equalsIgnoreCase("URL")) {
        attachmentBO.setUrl(String.valueOf(attachment.getMediaInfo().get("url")));
    } else if (attachmentBO.getType().equalsIgnoreCase("FILE")) {
        attachmentBO.setSize((Double) attachment.getValue().get("size"));
    }

    return attachmentBO;
}).collect(Collectors.toList());

I have mocked the attachmentList using Mockito, so I am getting the attachmentList. But how should I mock the remaining code? I have even mocked filterpermission.



Solution 1:[1]

Do not mock the list elements. Instead mock one level higher to return you a test list instead.

To clarify:

List<Attachment> attachmentList = List.of(RealAttachment1, RealAttachment2); // <-- Nothing is using Mockito here.

when(someMethodWhichReturnsAttachmentList()).thenReturn(attachmentList);

Then in your business logic:

attachmentList = someMethodWhichReturnsAttachmentList(); // Mockito will return you the test list you created earlier.


// You will now map the test List elements, as in a normal business logic
return attachmentList.stream().map(attachment -> {
    AttachmentBO attachmentBO = new AttachmentBO();
    attachmentBO.setId(attachment.getId());
    attachmentBO.setTitle(attachment.getName());
    attachmentBO.setType(attachment.getValue().get("type").toString());
    attachmentBO.setCreatorId(attachment.getAuditUserId());
    String[] filteredPermissionsForNote = this.filterPermissionCommand.filterPermissions(answer.getTopicId(), attachment.getAuditUserId(), topicDetails.getPermissions(), topicDetails.getEffectiveRoles(), true);
    attachmentBO.setPermissions(filteredPermissionsForNote);

    if (attachmentBO.getType().equalsIgnoreCase("URL")) {
        attachmentBO.setUrl(String.valueOf(attachment.getMediaInfo().get("url")));
    } else if (attachmentBO.getType().equalsIgnoreCase("FILE")) {
        attachmentBO.setSize((Double) attachment.getValue().get("size"));
    }

    return attachmentBO;
}).collect(Collectors.toList());

The business logic will return the List.of(attachments) you created in your test, and run through them all, including map/collect.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen