java—如何模拟文件系统功能

busg9geu  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(368)

我不知道如何模拟我正在从第行更改文件所有者的部分 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());

        FileSystem fs = FileSystems.getDefault();
        UserPrincipalLookupService upls = fs.getUserPrincipalLookupService();

        UserPrincipal newOwner = upls.lookupPrincipalByName(usernameSession);
        foav.setOwner(newOwner);

        UserPrincipal changedOwner = foav.getOwner();
        System.out.format("New owner  of  %s  is %s%n", path,
                changedOwner.getName());

        return "ok";
    }

下面是测试:

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

我得到一个例外,因为“用户名”不是一个用户。我想模拟调用,它在windows的用户中寻找匹配项。当我设置我的窗口的用户名而不是“username”时,它可以工作,但是我不能让我的窗口的用户名。
我试着嘲笑他 fs.getUserPrincipalLookupService() ; 以及 upls.lookupPrincipalByName(usernameSession); 但我不知道该回什么电话。
非常感谢!

ou6hu8tu

ou6hu8tu1#

首先,您应该考虑单一责任原则,并进一步剖析您的代码。
含义:创建一个helper类,为您抽象所有这些低级文件系统访问。然后在这里提供一个helper类的模拟示例,只需确保helper方法使用预期参数被调用。这将使你的服务方式 uploadEndpoint() 更容易测试。
然后,新的helper类只需要一个file对象。这使您能够将一个模拟文件对象传递给它,突然之间您就可以控制什么了 thatMockedFileObject.newPath() 会回来的。
换句话说:您的第一个目标应该是编写不使用 static 或者 new() 以防止使用mockito进行简单的模拟的方式。每当您遇到“我需要powermock(ito)来测试我的产品代码”的情况时,第一个冲动应该是:“我应该避免这种情况,并改进我的设计”。
同样适用于 FileSystem fs = FileSystems.getDefault(); ... 不要试图进入“模拟静态调用业务”,而是确保助手类接受某个文件系统示例。突然间你可以传递一个简单的mockito-mock对象,你就可以完全控制它了。

相关问题