首页 > 解决方案 > 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-bootunit-testingkotlin

解决方案


您可以使用 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);

推荐阅读