spring-boot - Use different file path for testing in Spring Boot
问题描述
I have a class in my project housing a method to retrieve files (as a list). In order to write unit tests, and to be able to put everything into a versioning tool, I want put a small example directory into my project. However, when I do that, my method needs to be able to distinguish whether or not it should read from the real (project-external) path or the testing environment.
This is my method:
fun getDirectoryContentObject(baseUserDir: String): UserLicenses {
val dirExists = Files.exists(Paths.get(licenseLocation + baseUserDir))
if(!dirExists) {
return UserLicenses(baseUserDir, listOf())
}
val userLicenses = UserLicenses(baseUserDir, listOf())
Files.walk(Paths.get(licenseLocation + baseUserDir)).forEach { outerIt ->
val dirOrFileName = outerIt.fileName.toString()
if (dirOrFileName != baseUserDir && !dirOrFileName.endsWith(licenseFileExtension)) {
val fileList: MutableList<String> = mutableListOf()
Files.walk(Paths.get(outerIt.toString())).forEach { innerIt ->
val subDirOrFileName = innerIt.fileName.toString()
if (subDirOrFileName.endsWith(licenseFileExtension)) {
fileList += subDirOrFileName
}
}
userLicenses.licenseVersions += LicenseVersions(dirOrFileName, fileList)
}
}
return userLicenses
}
The licenseLocation value is set by @Value from application.yml and point to the files outside the project.
How can I tell the method to get the files from the inside the project if it is being executed by a unit test?
解决方案
您可以使用 spring 资源 api 来获取文件实例。
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/ResourceUtils.html
外部示例:
filepath: file:/some-os-path/some-file-somewhere.abc
ResourceUtils.getFile(filepath);
测试示例:
filepath: classpath:file-from-resources-folder.abc
ResourceUtils.getFile(filepath);
推荐阅读
- ruby-on-rails - 如何从另一个控制器修改模型的表(没有控制器)?
- html - Asp.Net core 3.0 'value'中的路径必须以'/'开头
- sql - 数组的 JSONB 子集
- javascript - Javascript - 在 Group-by 之后将一个数组转换为两个
- filter - 有没有办法使用 DTO 将过滤器添加到自定义端点?
- calendar - flatpickr:禁用以前选择的日期
- java - 当目标日期在界限内时,领域“日期之间的查询”的问题
- ajax - HttpMessageNotReadableException:缺少所需的请求正文(偶尔)- SpringMVC 默认控制器请求映射 HTTP 方法?
- scala - 使用 Akka Stream 和 Kafka 偏移提交将事件从 Kafka 流式传输到 Couchbase
- javascript - 从 WFS 加载时不保留 OpenLayers 几何名称