Java 如何模拟文件系统功能
我不知道如何模拟将文件所有者从第行Java 如何模拟文件系统功能,java,junit,mockito,Java,Junit,Mockito,我不知道如何模拟将文件所有者从第行Path Path=newFile.toPath()更改为的部分结束 以下是我的功能: @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String uploadEndpoint(@RequestParam("file") MultipartFile file,
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用户中查找匹配项。当我设置窗口的用户名而不是“用户名”时,它可以工作,但我不能让我的窗口的用户名
我试图模拟fs.getUserPrincipalLookupService()
;和upls.lookupPrincipalByName(usernameSession)但是我不知道返回什么来模拟调用
非常感谢首先,你应该考虑并进一步剖析你的代码。
含义:创建一个帮助器类,为您抽象所有这些低级文件系统访问。然后在这里提供该helper类的模拟实例,并确保使用预期参数调用helper方法。这将使您的服务方法uploadEndpoint()
更易于测试
然后,您的新助手类可以只需要一个File对象。这使您能够将模拟的文件对象传递给它,然后突然您就可以控制该模拟文件对象将返回的内容
换句话说:您的第一个目标应该是编写不使用static
或new()
的代码,以防止使用Mockito进行简单的模拟。每当您遇到“我需要PowerMock(ito)来测试我的生产代码”的情况时,第一个冲动应该是:“我应该避免这种情况,并改进我的设计”
与文件系统fs=FileSystems.getDefault()相同代码>。。。不要试图进入“模拟静态调用业务”,而是确保助手类接受某个文件系统实例。突然间你可以传递一个简单的Mockito mock对象,你可以完全控制它 @J-Alex我认为它可能更短,但它总是关于平衡:没有足够的努力,没有足够的向上流动;-)谢谢!我听从了你的建议,效果很好,我现在会觉得测试不一样;)我感谢你的快速接受!