我不知道如何模拟将文件所有者从行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);,但是我不知道该返回什么来模拟调用。
非常感谢!
发布于 2019-02-04 14:20:50
首先,您应该考虑单一责任原则并进一步剖析代码。
意义:创建一个帮助类,为您抽象所有这些低级文件系统访问。然后,在这里提供该助手类的一个模拟实例,只需确保使用预期参数调用helper方法。这将使您的服务方法uploadEndpoint()更易于测试。
然后,您的新助手类可以简单地期望File对象。这使您能够向传递--一个模拟的文件对象--并且您突然控制了thatMockedFileObject.newPath()将返回的内容。
换句话说:您的第一个目标应该是编写不使用static或new()的代码,以防止使用Mockito进行简单的嘲弄。每当您遇到“我需要PowerMock(ito)来测试我的产品代码”的情况时,第一个冲动应该是:“我应该避免这种情况,并改进我的设计”。
FileSystem fs = FileSystems.getDefault();也一样..。您不必尝试进入“模拟静态调用业务”,而是确保您的助手类接受某些FileSystem实例。突然之间,您可以传递一个简单的Mockito模拟对象,您可以完全控制它。
https://stackoverflow.com/questions/54518045
复制相似问题