1

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()?

placplacboom
  • 614
  • 8
  • 16

1 Answers1

1

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
madhead
  • 31,729
  • 16
  • 153
  • 201
  • Sounds good but it throws a null pointer exception. The file is inside `resources` under `test` folder – placplacboom Jun 22 '20 at 13:03
  • Play with the path. NPE most probably means that you're using a wrong path in `getResource()` call and the resulting resource is null. Search for this topic on SO, there are a plenty of questions and answers, like [this](https://stackoverflow.com/q/573679/750510). – madhead Jun 22 '20 at 13:11
  • Just curious why `this.javaClass.getResourceAsStream("/test.txt")` works and getResource() won't work - I have tried with `./test.txt` and `test.txt` – placplacboom Jun 22 '20 at 13:15
  • It's really hard to guess without looking at sources and debugging. – madhead Jun 22 '20 at 13:20
  • That's actually how I do that every time I write tests. Do I need to start it from slash or not? Do I need to call `getResource` for class or its classloader. After a few experiments I always find the right combination. – madhead Jun 22 '20 at 13:23