如何嘲笑文件系统功能

问题描述 投票:1回答:1

我不知道该怎么嘲笑,我正在改变从线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”的不是用户。我想嘲笑它会在窗口的用户相匹配的呼叫。它的工作原理,当我把我的窗口的用户名代替“username”的,但我不能让我的窗口的用户名。

我试图嘲弄qazxsw POI;和qazxsw POI,但我不知道该怎么回嘲笑呼叫。

非常感谢 !

java junit mockito
1个回答
2
投票

首先,你应该考虑fs.getUserPrincipalLookupService(),并进一步剖析你的代码。

含义:创建一个抽象所有这些低级文件系统访问你一个辅助类。然后,你在这里提供一个辅助类的嘲笑实例,您只需确保辅助方法被调用使用所需的参数。这将使你的服务方法upls.lookupPrincipalByName(usernameSession);更容易测试。

然后,你的新助手类可以简单地指望一个文件对象。这使您能够在嘲笑File对象传递给它,一下子你是在什么Single Responsibility principle将返回控制。

换句话说:你的第一个目标应该是编写的代码,不使用uploadEndpoint()thatMockedFileObject.newPath()在防止利用简单的Mockito嘲讽的方式。每当你遇到这样的情况,你觉得情况:“我需要PowerMock(ITO)来测试我的生产代码”,那么第一个冲动应该是:“我应该避免这种情况,并提高我的设计”。

同为static ...而不是试图进入“模拟静态通话业务”,你确保你的助手类接受一些文件系统实例。突然之间,你可以通过一个简单的模拟的Mockito对象,你是在它的完全控制。

© www.soinside.com 2019 - 2024. All rights reserved.