0

I am trying to read a file "my_data.txt" that sit in my /src/test/resources/data folder.

––– src

  –– main

  –– test

   ––– resources

      ––– data

          ––– my_data.txt

I have the following piece of code to do that:

val filename = getClass.getResource("/src/test/resources/data/my_data.txt").getPath

When I compile it, the compilation went well, however, when I run the test in ducker, I am getting the following error message:

java.lang.NullPointerException
    at (xxxx.scala:128)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
    at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
    at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
    at org.scalatest.Transformer.apply(Transformer.scala:22)
    at org.scalatest.Transformer.apply(Transformer.scala:20)
    at org.scalatest.FunSpecLike$$anon$1.apply(FunSpecLike.scala:454)
    at org.scalatest.TestSuite.withFixture(TestSuite.scala:196)
    at org.scalatest.TestSuite.withFixture$(TestSuite.scala:195)
    at org.scalatest.FunSpec.withFixture(FunSpec.scala:1630)
    at org.scalatest.FunSpecLike.invokeWithFixture$1(FunSpecLike.scala:452)
    at org.scalatest.FunSpecLike.$anonfun$runTest$1(FunSpecLike.scala:464)
    at org.scalatest.SuperEngine.runTestImpl(Engine.scala:289)
    at org.scalatest.FunSpecLike.runTest(FunSpecLike.scala:464)
    at org.scalatest.FunSpecLike.runTest$(FunSpecLike.scala:446)


When I try to print the path that I am reading from I got `null` as an output.

Another attempts

Apart from above I tried the following code:

  1. val ss = scala.io.Source.fromResource("/src/test/resources/data/my_data.txt")
  2. ClassLoader.getSystemResource("/src/test/resources/data/my_data.txt").getPath

Also, I added src/test/resources/data to the resources in POM file

Finally

As this mentioned, I checked if I have the .txt included in the compiler ( I am using MAC)

Rahman
  • 101
  • 1
  • 12

1 Answers1

0

Well, I got this resolved by using getAbsolutePath to get the absolute path. I pointed out to the test.properties file to have the dataDir. Here is what I did:

properties.load(getClass.getClassLoader.getResourceAsStream("test.properties"))
testDataDirectory = new File(properties.getProperty("dataDir"))
val file = new File(testDataDirectory.getAbsolutePath +"/data/my_data.txt"

for (line <- Source.fromFile(file).getLines) {
   println(line)
}

This does not means that is the "best" way to do that, but just in case that you face similar issue, above what I used to resolve it.

Rahman
  • 101
  • 1
  • 12