placplacboom
placplacboom

Reputation: 899

How to mock a specific reading file?

I'm implementing a unit test that should read a file from a specific path and perform some operations.

In a real scenario, my file will exists in a specific path from OS - something like /users/placplac/file.txt.

How can I implement a mock (or read a file from resources) in unit test?

Here is the piece of code that I want to mock:

class ReportServiceImpl(val filePath: String) {

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

Is possible to mock just the part File(filePath).bufferedReader()?

Upvotes: 1

Views: 1266

Answers (1)

madhead
madhead

Reputation: 33412

As long as the path is not hard-coded and passed as a parameter, you can just invoke this function with a path to test resource (in 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

Upvotes: 1

Related Questions