I'm working in a Scala project using SBT, so the project follows the default directory structure:
project_name/
├── build.sbt
├── src
│ ├── main
│ │ ├── resources
│ │ │ └── production.txt
│ │ └── scala
│ │ └── ...
│ └── test
│ ├── resources
│ │ └── test.txt
│ └── scala
│ └── ...
When I try to read the files in the resources folder, in production code, I try this, and works just fine:
object FileReader extends App {
io.Source.fromResource("production.txt").getLines.toList.foreach(println(_))
}
But when I do try to do the same in test code:
class FileReaderTest extends FreeSpec with Matchers {
"Source" - {
"reads files from resources folder" in {
val lines = io.Source.fromResource("test.txt").getLines.toList
lines should be(List("Hello","World"))
}
}
}
I get a NPE exeption:
[info] Source
[info] - reads files from resources folder *** FAILED ***
[info] java.lang.NullPointerException:
[info] at java.io.Reader.<init>(Reader.java:78)
[info] at java.io.InputStreamReader.<init>(InputStreamReader.java:129)
[info] at scala.io.BufferedSource.reader(BufferedSource.scala:22)
[info] at scala.io.BufferedSource.bufferedReader(BufferedSource.scala:23)
[info] at scala.io.BufferedSource.charReader$lzycompute(BufferedSource.scala:33)
[info] at scala.io.BufferedSource.charReader(BufferedSource.scala:31)
[info] at scala.io.BufferedSource.scala$io$BufferedSource$$decachedReader(BufferedSource.scala:60)
[info] at scala.io.BufferedSource$BufferedLineIterator.<init>(BufferedSource.scala:65)
[info] at scala.io.BufferedSource.getLines(BufferedSource.scala:84)
[info] ...
When I try to read production.txt
file in the test, it works just fine too. So my guess is that for some reason, the test resources folder is not being loaded in the classpath. So with this, I've researched about SBT, and it seems that by default, the src/test/resources
folder is the default one already, in fact, just checking in the SBT shell, it yields the following:
> show test:resourceDirectory
[info] <path to project>/src/test/resources
> show test:unmanagedResources
[info] * <path to project>/src/test/resources
> show test:unmanagedResourceDirectories
[info] * <path to project>/src/test/resources
So obviously, I'm missing something, but no clue on where to continue researching.
By the way, I'm using Scala 2.12.4, SBT 1.0.2 and scalatest 3.0.4
Update
Seems the problem was related to either SBT build or the IDE, as I have done may experiments with the build.sbt
file, changing and playing around unmanagedResources
, resourceDirectory
, and some others in Test
scope, and at the end there was a corruption somewhere.
I'm using IntelliJ IDEA, and after removing all my experiments with the SBT Test
scope, deleting the .idea
folder and re-importing the SBT project, it just worked fine.
Also in regards of the question being a possible duplicate of other questions, I thought there was a difference, because at first it worked with the resources located at src/main/resources
but not with the src/test/resources
.