如何模拟特定的阅读文件?

How to mock a specific reading file?

我正在实施一个单元测试,它应该从特定路径读取文件并执行一些操作。

在实际情况下,我的文件将存在于 OS 的特定路径中 - 类似于 /users/placplac/file.txt.

如何在单元测试中实现模拟(或从资源中读取文件)?

这是我要模拟的代码片段:

class ReportServiceImpl(val filePath: String) {

    private fun getContent() {
      val reader = Mybject(File(filePath).bufferedReader()) // this is what I want to mock
      ....
    }
}

是否可以只模拟 File(filePath).bufferedReader() 部分?

只要路径不是硬编码并作为参数传递的,您就可以使用测试资源的路径调用此函数(在 src/test/resources 中):

val resource = this::class.java.classLoader.getResource("test.txt")
val file = Paths.get(resource.toURI()).toFile()
val absolutePath = file.getAbsolutePath()
val subject = ReportServiceImpl(absolutePath)

... do your tests