We want to add 100% coverage on our Spring Boot Java program we run so there are 2 strange tests that require us to create a folder and a file with access permission denied .
因为文件非常简单:
File file = new file(....path...);
.... just creating the file with some simple code...
//now deny permissions
file.setReadable(false);
file.setWritable(false);
//Some code trying to write on that file
throwing exception (happy junit test is passed)
但是我想创建一个目录,让我们将其命名为 parentDir
并使同一个 java 程序不可能在其中创建文件或文件夹。所以在相同的逻辑中 :
File parentDir= new file(....parentDirPath...);
parentDir.mkDir();
parentDir.setReadable(false);
parentDir.setWritable(false);
//Some code to create another folder inside the parentDir
File childDir= new file(....parentDirPath/childDir...);
directoryExistsOrElseCreate(childDir.toPath());
//WHOT IT CREATES THE FOLDER even if i don't want ...
为什么它仍然能够在 parentDir
上创建新文件和文件夹?
更新,刚刚深入研究代码,发现我们正在使用 Files.createDirectories(path);
而不是 file.mkDir();
我正在测试的方法是这样的:
public void directoryExistsOrElseCreate(final Path path) {
try {
if (Files.notExists(path)) {
log.warn("Directory={} does NOT EXIST, creating...", path);
Files.createDirectories(path);
} else {
log.warn("Directory={} ALREADY EXISTS, skipping...", path);
}
} catch (final IOException e) {
log.error("Error during creating directory: path={}, error={}", path.toString(), e.getMessage());
throw new AtsGenericException(AtsGenericErrorCode.IO_ERROR, new Object[]{e.getMessage()});
}
}
最佳答案
我只有一个答案给你:不要浪费你的精力来获得 100% 的代码覆盖率。在很多情况下,这样做是不值得的,因此会浪费时间和金钱。此外,难以理解和维护的复杂测试覆盖了私有(private)构造函数、实用程序类的异常或与系统(文件、网络等)的直接交互等难以测试的东西。它们只会为您的应用程序增加技术债务,而根本不会增加任何值(value)。
也不要为贫血模型类编写单独的单元测试(即只有字段、getter 和 setter 而没有逻辑的 POJO)。这些类应该在其他地方使用,并作为其他测试的一部分。
将目标设定在 60-80% 的范围内,并将您的测试编写工作集中在您的业务和转换逻辑上,例如 Controller ,映射器,服务。这是难以理解、最常更改并决定应用程序功能的逻辑。
要覆盖任何未发现代码中的错误配置或错误,请使用 stub 环境组件(例如 H2 数据库或具有固定响应的 WireMock 端点)编写一些基本集成(端到端)测试。这些将显示您的系统是否无法在基本级别进行交互,而不是任何精心设计的反射缠身单元测试。
关于无法在其中创建子文件夹或文件的 Java mkdir() 文件夹(抛出访问被拒绝),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52868909/