亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何模擬文件系統功能

如何模擬文件系統功能

拉莫斯之舞 2022-06-04 16:59:50
我不知道如何模擬我將文件所有者從行Path path = newFile.toPath();更改到末尾的部分。這是我的功能:@RequestMapping(value = "/upload", method = RequestMethod.POST)    @ResponseBody    public String uploadEndpoint(@RequestParam("file") MultipartFile file,                                 @RequestParam("usernameSession") String usernameSession,                                 @RequestHeader("current-folder") String folder) throws IOException {        String[] pathArray = file.getOriginalFilename().split("[\\\\\\/]");        String originalName = pathArray[pathArray.length-1];        LOGGER.info("Upload triggerred with : {} , filename : {}", originalName, file.getName());        String workingDir = URLDecoder.decode(folder.replace("!", "."),                StandardCharsets.UTF_8.name())                .replace("|", File.separator);        LOGGER.info("The file will be moved to : {}", workingDir);        File newFile = new File(workingDir + File.separator + originalName);        //UserPrincipal owner = Files.getOwner(newFile.toPath());        file.transferTo(newFile);        Path path = newFile.toPath();        FileOwnerAttributeView foav = Files.getFileAttributeView(path, FileOwnerAttributeView.class);        UserPrincipal owner = foav.getOwner();        System.out.format("Original owner  of  %s  is %s%n", path, owner.getName());    }這是測試:@Test    public void uploadEndpointTest() throws Exception {        PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(file);        Mockito.when(multipartFile.getOriginalFilename()).thenReturn("src/test/resources/download/test.txt");        assertEquals("ok", fileExplorerController.uploadEndpoint(multipartFile, "userName", "src/test/resources/download"));    }我遇到了一個例外,因為“userName”不是用戶。我想模擬它在 Windows 用戶中尋找匹配項的調用。當我設置我的窗口的用戶名而不是“userName”時它可以工作,但我不能讓我的窗口的用戶名。我試圖嘲笑fs.getUserPrincipalLookupService();但upls.lookupPrincipalByName(usernameSession);我不知道要返回什么來模擬通話。
查看完整描述

1 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

首先,您應該考慮單一職責原則并進一步剖析您的代碼。

含義:創建一個幫助類,為您抽象所有這些低級文件系統訪問。然后在此處提供該助手類的模擬實例,并確保使用預期參數調用助手方法。這將使您的服務方法uploadEndpoint()更容易測試。

然后,您的助手類可以簡單地期望一個 File 對象。這使您能夠將模擬的 File 對象傳遞它,并且突然之間您可以控制thatMockedFileObject.newPath()將返回的內容。

換句話說:您的第一個目標應該是編寫不使用staticnew()以防止使用 Mockito 進行簡單模擬的方式的代碼。每當您遇到您認為“我需要 PowerMock(ito) 來測試我的生產代碼”的情況時,第一個沖動應該是:“我應該避免這種情況,并改進我的設計”。

同樣的FileSystem fs = FileSystems.getDefault();......而不是試圖進入“模擬靜態調用業務”,你確保你的幫助類接受一些 FileSystem 實例。突然之間,您可以傳遞一個簡單的 Mockito 模擬對象,并且您可以完全控制它。


查看完整回答
反對 回復 2022-06-04
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號