繁体   English   中英

如何使用 Mockito 模拟 spring 引导的这段代码?

[英]How to mock this piece of code of spring boot using Mockito?

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

我已经使用 Mockito 模拟了附件列表,所以我得到了附件列表,但是我应该如何模拟剩余的代码? 我什至嘲笑过filterpermission。

不要模拟列表元素,而是模拟更高级别的 1 级以返回一个测试列表。

澄清:

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

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

然后在您的业务逻辑中:

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

业务逻辑将返回您在 TEST 中创建的List.of(attachments) ,并运行所有这些,包括map/collect

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM