How to access test resources in Scala?

ScalaSbt

Scala Problem Overview


I have a file data.xml in src/test/resources/.

How can I read that file into a new FileReader in my test data.scala in src/test/scala/?

Scala Solutions


Solution 1 - Scala

Resources are meant to be accessed using the special getResource style methods that Java provides. Given your example of data.xml being in $SBT_PROJECT_HOME/src/test/resources/, you can access it in a test like so:

import scala.io.Source

// The string argument given to getResource is a path relative to
// the resources directory.
val source = Source.fromURL(getClass.getResource("/data.xml"))

Of course that source is now just a normal Scala IO object so you can do anything you want with it, like reading the contents and using it for test data.

There are other methods to get the resource as well (for example as a stream). For more information look at the getResource methods on the Java Docs: Class.

Solution 2 - Scala

Another alternative (especially if you need to access resource as a File); is to obtain it's path via:

val path = getClass.getResource("/testData.txt").getPath
val file = new File(path)

as has been pointed out in https://stackoverflow.com/questions/23831768/scala-get-file-path-of-file-in-resources-folder

Solution 3 - Scala

sbt copies files from src/test/resources to target/scala-[scalaVersion]/test-classes.

You can access the resources in your tests as follows:

Source.fromURL(getClass.getResource("/testData.txt"))

It does assume that testData.txt was directly under the folder src/test/resources. Add any subdirectories, otherwise.

Solution 4 - Scala

And in cases where getClass.getResource does not work (don't know nor care when or why exactly), com.google.common.io.Resources.getResource from Google Guava usually does

testCompile "com.google.guava:guava:18.0"

Solution 5 - Scala

To know where you are in file system during test, you can do something like this in a dummy test:

 import scala.collection.JavaConversions._
  for(file <- new File(".").listFiles ){
   println(file.getAbsolutePath)
  }

Then, when you know your path, in your test you can use it as:

new File("./src/test/resources/yourfile.xml")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAaron YodaikenView Question on Stackoverflow
Solution 1 - ScalaMitchellView Answer on Stackoverflow
Solution 2 - ScalaNeilView Answer on Stackoverflow
Solution 3 - ScalaNick A MillerView Answer on Stackoverflow
Solution 4 - ScalaoseiskarView Answer on Stackoverflow
Solution 5 - ScalaheralightView Answer on Stackoverflow