如何模拟文件系统功能

Maj*_*tic 3 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";
    }
Run Code Online (Sandbox Code Playgroud)

这是测试:

@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"));
    }
Run Code Online (Sandbox Code Playgroud)

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

我试图嘲笑fs.getUserPrincipalLookupService();但upls.lookupPrincipalByName(usernameSession);我不知道要返回什么来模拟呼叫。

非常感谢 !

Gho*_*ica 6

首先,您应该考虑单一职责原则并进一步剖析您的代码。

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

然后,您的帮助器类可以简单地期望一个 File 对象。这使您能够将模拟的File对象传递给它,突然间您就可以控制将返回的内容。thatMockedFileObject.newPath()

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

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