簡體   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