Search code examples
scalamavenscalatest

Unable to access file in relative path in Scala for test resource


I have setup my SCALA project using Maven, now I am writing test and need to access a file under sub directory of resource path is like:

src/test/resource/abc/123.sql

Now I am doing following:

val relativepath = "/setup/setup/script/test.sql"
val path = getClass.getResource(relativepath).getPath
println(path)

but this is pointing to src/main/resource folder instead of test resource, anyone has the idea what I am doing wrong here?


Solution

  • Just like in Java, it is a good practice to put your resource files under src/main/resources and src/test/resources, as Scala provides a nice API from retrieving resource files.

    Considering you put your test.sql file under src/test/resources/setup/setup/script/test.sql, you can easily read the file by doing the following:

    Scala 2.12

    import scala.io.Source
    val relativePath = "setup/setup/script/test.sql"
    val sqlFile : Iterator[String] = Source.fromResource(relativePath).getLines
    

    Prior Scala versions

    import scala.io.Source
    val relativePath = "setup/setup/script/test.sql"
    val stream : InputStream = getClass.getResourceAsStream(relativePath)
    val sqlFile : Iterator[String] = Source.fromInputStream(stream).getLines         
    

    Doing so, you can even have the same file put under the same relative path in src/main/resources. When trying to access the resource file in a test, the file from the src/test/resources will be considered.

    I hope this is helpful.