我正在尝试编写一个单元测试来测试某些代码中的 IOException 处理。我想我可以通过从文件中删除权限并尝试删除它来创建一个 IOException 。但看起来该文件无论如何都会被删除。第一个问题是预期的行为?如果是这样,这对我来说似乎是一个很大的安全漏洞。第二个问题是任何人都对如何在 Files.delete() 或 commons.io FileUtils.deleteDirectory() 两种方法中的任何一种上创建 IOException 有任何建议。以下是单元测试代码,我在文件上尝试了 Files.delete,在目录上尝试了 FileUtils.deleteDirectory。在后一种情况下,我得到一个 fileNotFound 异常。第二个断言总是失败。使用调试器,我停止了代码并确保不可写的权限为 000。我在 Redhat 7 上运行 java 11。
public void testIOException() throws IOException {
binPath.toFile().mkdirs();
Path unwriteablePath = Paths.get(binPath.toString(), "unwriteable");
Path writeablePath = Paths.get(binPath.toString(),"writeable");
File unwriteable = unwriteablePath.toFile();
unwriteable.createNewFile();
File writeable = unwriteablePath.toFile();
writeable.createNewFile();
Assertions.assertTrue(unwriteable.exists());
Assertions.assertTrue(writeable.exists());
Set<PosixFilePermission> perms =
Files.readAttributes( unwriteablePath, PosixFileAttributes.class).permissions();
//make file unwriteable
perms.remove(PosixFilePermission.OWNER_WRITE);
perms.remove(PosixFilePermission.GROUP_WRITE);
perms.remove(PosixFilePermission.OTHERS_WRITE);
perms.remove(PosixFilePermission.OWNER_READ);
perms.remove(PosixFilePermission.GROUP_READ);
perms.remove(PosixFilePermission.OTHERS_READ);
Files.setPosixFilePermissions(unwriteablePath, perms);
Assertions.assertFalse(unwriteable.canWrite());
// Deleter deleter = new Deleter(mockConfig);
// deleter.run();
try {
Files.delete(Paths.get(unwriteable.getAbsolutePath()));
} catch (IOException e) {
System.out.println("Got expected exception");
}
Assertions.assertFalse(writeable.exists());
Assertions.assertTrue(unwriteable.exists());
}
}