如何模拟文件系统功能

时间:2019-02-04 14:14:07

标签: java junit mockito

我不知道如何模拟将文件所有者从第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"));
    }

我遇到了一个异常,因为“ userName”不是用户。我想模拟在Windows用户中寻找匹配项的呼叫。当我设置窗口的用户名而不是“ userName”时,它可以工作,但是我不允许窗口的用户名。

我试图嘲笑fs.getUserPrincipalLookupService();和upls.lookupPrincipalByName(usernameSession);,但我不知道返回什么来模拟通话。

非常感谢!

1 个答案:

答案 0 :(得分:2)

首先,您应该考虑Single Responsibility principle并进一步剖析您的代码。

含义:创建一个 helper 类,为您所有这些低级文件系统访问抽象。然后,在此处提供该帮助程序类的 mocked 实例,只需确保使用所需的参数调用helper方法即可。这将使您的服务方法uploadEndpoint()更加容易测试。

然后,您的 new 助手类可能只需要File对象。这样一来,您就可以传递一个模拟的文件对象,突然之间,您可以控制thatMockedFileObject.newPath()的返回内容。

换句话说:您的首要目标应该是编写不使用staticnew()的代码,以防止使用Mockito进行简单的模拟。每当遇到“我需要PowerMock(ito)来测试我的生产代码”的情况时,第一个冲动应该是:“我应该避免这种情况,并改进我的设计”。

FileSystem fs = FileSystems.getDefault();相同...而不是尝试进入“模拟静态呼叫业务”,而是确保您的助手类接受一些FileSystem实例。突然之间,您可以传递一个简单的Mockito模拟对象,并且可以完全控制它。